<!-- 巡查计划管理-水闸 -->
<script>
import { getDicts, postSZInspectionPlanlist, postSZInspectionPlan, putSZInspectionPlan, postSZInspectionProjectList, getSZInspectionPlan, deleteSZInspectionPlan, listUser } from '@/api/management'
import { uploadFileData } from '@/api/system/upload'

export default {
  name: 'InspectionItems',
  data() {
    return {
      searchInput: '',
      dialogVisible: false,
      patrolType: [], // 巡查周期类型
      personnelList: [], // 人员列表
      examType: [], // 检查类型
      tableData: [], // 检查列表
      patrolTableData: [], // 巡查项目列表
      pageData: {
        pageNum: 1, // 当前页
        pageSize: 10, // 请求数量
        pageSizes: [10, 20, 50, 100],
        total: 0 // 总数量
      },
      ruleForm: {
        name: '',
        type: '',
        xcId: '',
        frequency: '',
        cycleType: '',
        messageReminder: false,
        reminderTime: '',
        operators: [],
        otherConfig: {
          week: '',
          time: '',
          selectUser: []
        }
      },
      rules: {
        name: [
          { required: true, message: '请输入计划名称', trigger: 'blur' },
          { max: 50, message: '名称最长为50个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择巡查类型', trigger: 'change' }
        ],
        xcId: [
          { required: true, message: '请选择巡查项目名称', trigger: 'change' }
        ],
        cycleType: [
          { required: true, message: '请选择巡查周期', trigger: 'change' }
        ],
        messageReminder: [
          { required: true, message: '请选择消息提醒', trigger: 'change' }
        ],
        reminderTime: [
          { required: true, message: '请选择提醒时间', trigger: 'change' }
        ],
        'otherConfig.selectUser': [
          { required: true, message: '请选择责任人', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 编辑巡查项目
    editTableItem(row) {
      getSZInspectionPlan(row.id).then((res) => {
        // 遍历用户数据让select组件渲染选项
        if (res.data.otherConfig.selectUser) {
          this.personnelList = []
          res.data.otherConfig.selectUser.forEach(element => {
            listUser({
              data: {
                timeView: {
                  timeField: "create_time"
                },
              },
              cv: {
                name: "nickName",
                type: "like",
                value: element.nickName
              },
              pageSize: 10,
              pageNum: 1
            }).then((res) => {
              this.personnelList.push(res.records[0])
            })
          });
        }
        this.ruleForm = res.data
        this.ruleForm.type = res.data.type.toString()
        if (res.data.cycleType) {
          this.ruleForm.cycleType = res.data.cycleType.toString()
        }
        this.changePatrolType(res.data, false)
        this.dialogVisible = true
      })
    },
    // 删除对应巡查项目
    deleteTableItem(row) {
      deleteSZInspectionPlan(row.id).then((res) => {
        this.getTableData()
        this.$message.success('删除成功');
      })
    },
    // 路线设置
    routeSetting(row) {
      this.$router.push({
        path: 'patrolRouteSettings',
        query: { id: row.id, name: row.name, editor: true }
      })
    },
    // 保存巡查项目
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let user = []
          this.ruleForm.otherConfig.selectUser.forEach(element => {
            let a = {
              name: element.nickName,
              uid: element.id
            }
            user.push(a)
          });
          this.ruleForm.operators = user
          if (this.ruleForm.id) {
            putSZInspectionPlan(this.ruleForm).then((res) => {
              this.getTableData()
              this.dialogVisible = false
              this.$message.success('更新成功');
            })
          } else {
            postSZInspectionPlan(this.ruleForm).then((res) => {
              this.getTableData()
              this.dialogVisible = false
              this.$message.success('添加成功');
            })
          }
        } else {
          console.log('校验不通过');
          return false;
        }
      });
    },
    // 更改巡查类型
    changePatrolType(ruleForm, clear) {
      if (clear) {
        console.log('清空');
        this.ruleForm.frequency = ''
        this.ruleForm.cycleType = ''
        this.ruleForm.otherConfig.time = ''
        this.$set(ruleForm, 'xcId', '')
      }
      postSZInspectionProjectList({
        data: {
          timeView: {
            timeField: "create_time"
          },
          type: ruleForm.type
        },
        cv: {
          name: "name",
          type: "like"
        },
        pageSize: 999,
        pageNum: 1
      }).then((res) => {
        this.patrolTableData = res.records
      })
    },
    // 搜索用户
    searchUser(e) {
      listUser({
        data: {
          timeView: {
            timeField: "create_time"
          },
        },
        cv: {
          name: "nickName",
          type: "like",
          value: e
        },
        pageSize: 100,
        pageNum: 1
      }).then((res) => {
        this.personnelList = res.records
      })
    },
    // 关闭dialog
    closeDialog(ruleForm = 'ruleForm') {
      this.$refs[ruleForm].resetFields();
      this.ruleForm = {
        name: '',
        type: '',
        xcId: '',
        frequency: '',
        cycleType: '',
        messageReminder: false,
        reminderTime: '',
        operators: [],
        otherConfig: {
          week: '',
          time: '',
          selectUser: [],
        }
      }
      this.patrolTableData = []
    },
    // 获取数据
    getTableData(search) {
      postSZInspectionPlanlist({
        data: {
          timeView: {
            timeField: "create_time"
          }
        },
        cv: {
          name: "name",
          type: "like",
          value: search
        },
        pageSize: this.pageData.pageSize,
        pageNum: this.pageData.pageNum
      }).then((res) => {
        if (res) {
          this.tableData = res.records
          this.pageData.total = res.total
        }
      })
    },
    // 重置搜索
    resetSearch() {
      this.searchInput = ''
      this.getTableData()
    },
    // 上传前
    beforeAvatarUpload(e){
      console.log('beforeAvatarUpload >>>>>  ', e)
      let formData = new FormData()
      formData.append({
        file: e
      })
      uploadFileData(formData).then(res=>{
        console.log('res >>>>>  ', res)

      }).catch(e=>{
        console.log('e >>>>>  ', e)

      })
    },
    // 文件上传后
    handleChange(e){
      console.log('handleChange >>>>>  ', e)
    },
  },
  mounted() {
    // 获取列表数据
    this.getTableData()
    getDicts('xs_classfy').then((res) => {
      if (res.data && Array.isArray(res.data)) {
        res.data.forEach(element => {
          element.dictValue = element.dictValue
        });
        this.examType = res.data
      }
    })
    getDicts('xs_cycle_type').then((res) => {
      console.log('🚀res.data🚀', res.data)
      this.patrolType = res.data
    })
  },
}
</script>

<template>
  <div class="slider-right">
    <div class="top-title">
      基础信息管理
    </div>
    <div class="table-box">
      <div class="top-search">
        <span>计划名称：</span>
        <el-input class="search-input" v-model="searchInput" placeholder="请输入计划名称" />
        <el-button class="search-btn" type="success" @click="getTableData(searchInput)">搜索</el-button>
        <el-button @click="resetSearch()">搜索</el-button>
      </div>
      <el-button class="search-btn" style=" margin-right: 16px;margin-bottom: 8px; float: right;" type="success"
        @click="dialogVisible = true">添加</el-button>
      <el-table height="625" :data="tableData" border>
        <el-table-column type="index" align="center" label="序号" width="100" />
        <el-table-column prop="name" align="center" label="计划名称" />
        <el-table-column align="center" label="巡查类型">
          <template slot-scope="scope">
            <span v-if="examType.length > 0">{{ examType.find(item => item.dictValue == scope.row.type).dictLabel ||
              ''
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" align="center" sortable label="最近巡查时间" />
        <el-table-column prop="createTime" align="center" sortable label="创建时间" />
        <el-table-column prop="updateTime" align="center" sortable label="更新时间" />
        <el-table-column prop="address" align="center" label="操作">
          <template slot-scope="scope">
            <el-button style=" margin-right: 16px;" @click="editTableItem(scope.row)" type="text"
              size="small">编辑</el-button>
            <el-popconfirm confirm-button-text='确定' cancel-button-text='取消' icon="el-icon-info" icon-color="red"
              title="确定删除吗？" @confirm="deleteTableItem(scope.row)">
              <el-button style="color: red;margin-right: 16px;" type="text" size="small" slot="reference">删除</el-button>
            </el-popconfirm>
            <el-button @click="routeSetting(scope.row)" type="text" size="small">路线设置</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background class="pagination" style="margin-top: 16px;margin-right: 16px;float: right;"
        :current-page="pageData.pageNum" :page-sizes="pageData.pageSizes" layout="total, prev, pager, next, sizes, jumper"
        :total="pageData.total" @size-change="getTableData()">
      </el-pagination>
    </div>
    <el-dialog title="新增/编辑巡查计划" @close="closeDialog" :visible.sync="dialogVisible" width="50%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item label-width="120px" label="计划名称" prop="name">
          <el-input style="width: 202px;" v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label-width="120px" label="巡查类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择巡查类型" @change="changePatrolType(ruleForm, true)">
            <el-option v-for="item in examType" :label="item.dictLabel" :value="item.dictValue"
              :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="120px" label="巡查项目名称" prop="xcId">
          <el-select v-model="ruleForm.xcId" placeholder="请选择巡查项目名称">
            <el-option v-for="item in patrolTableData" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm.type == 0" label-width="120px" label="巡查周期" prop="cycleType">
          <el-input style="width: 202px;" v-model="ruleForm.frequency"></el-input>
          /次
          <el-select v-model="ruleForm.cycleType" placeholder="请选择日期">
            <el-option v-for="item in patrolType" :label="item.dictLabel" :value="item.dictValue"
              :key="item.id"></el-option>
          </el-select> /日期
        </el-form-item>
        <el-form-item v-else label-width="120px" label="检查日期" prop="reminderTime">
          <el-date-picker v-model="ruleForm.otherConfig.time" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label-width="120px" label="消息提醒" prop="messageReminder">
          <el-switch v-model="ruleForm.messageReminder" active-color="#31a08e" inactive-color="#dcdfe6">
          </el-switch>
        </el-form-item>
        <el-form-item label-width="120px" label="提醒时间" prop="reminderTime">
          <el-radio-group v-if="ruleForm.cycleType == 1 && ruleForm.type == 0" v-model="ruleForm.otherConfig.week">
            <el-radio :label="1">星期一</el-radio>
            <el-radio :label="2">星期二</el-radio>
            <el-radio :label="3">星期三</el-radio>
            <el-radio :label="4">星期四</el-radio>
            <el-radio :label="5">星期五</el-radio>
            <el-radio :label="6">星期六</el-radio>
            <el-radio :label="7">星期日</el-radio>
          </el-radio-group>
          <el-time-picker v-if="ruleForm.cycleType != 2 && ruleForm.type == 0" v-model="ruleForm.reminderTime"
            value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择时间点" />
          <el-date-picker v-if="ruleForm.cycleType == 2 || ruleForm.type != 0" v-model="ruleForm.reminderTime"
            value-format="yyyy-MM-dd hh:mm:ss" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label-width="120px" label="责任人" prop="otherConfig.selectUser">
          <el-select v-model="ruleForm.otherConfig.selectUser" multiple filterable remote :remote-method="searchUser"
            value-key="id" placeholder="请输入关键词搜索用户" prop="selectUser">
            <el-option v-for="item in personnelList" :key="item.id" :label="item.nickName" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm.type == 2" label-width="120px" label="检查依据" prop="checkList">
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :before-upload="beforeAvatarUpload"
            v-model:file-list="ruleForm.checkList"
            accept=".PDF,.docx,.doc,.excel,.ppt,.jpg,.png,.txt"
            :on-change="handleChange"
          >
            <el-button type="primary">上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持pdf,doc,docx,excel,ppt,jpg,png,txt等,500M以内
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitForm('ruleForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.top-title {
  height: 50px;
  background-color: white;
  display: flex;
  padding-left: 16px;
  align-items: center;
  font-weight: 600;
}

.table-box {
  height: calc(100% - 50px - 24px);
  margin-top: 24px;
  padding: 16px;
  background-color: white;

  .top-search {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    .search-input {
      width: 300px;
      margin-right: 10px;
    }

  }

  .search-btn {
    margin-left: 10px;
    background-color: #37b29e;
    border: none;

    &:hover {
      background-color: #5ac6b9;
    }

    &:active {
      background-color: #2b8070;
    }
  }
}
</style>