<template>
  <el-drawer
    :title="title"
    :modal-append-to-body="false"
    :modal="false"
    :wrapper-closable="false"
    size="36%"
    :visible.sync="dialogVisible"
  >
    <el-form
      ref="ruleForm"
      :model="formData"
      :rules="rules"
      label-position="right"
      label-width="160px"
    >
      <el-form-item label="设备名称" required>
        <el-input
          v-model="formData.goafDevName"
          placeholder="请输入设备名称"
          style="width: 260px"
        />
      </el-form-item>
      <el-form-item label="安装区域" required>
        <div class="safe-area">
          <el-select
            v-model="formData.goafOrebelt"
            class="safe-area-item"
            filterable
            placeholder="矿带"
            @change="changeArea(1)"
          >
            <el-option :value="0" label="请选择矿带" disabled />
            <el-option
              v-for="(item, index) in goafOrebelts"
              :key="index"
              :value="item.goafOrebelt"
              :label="item.goafOrebelt"
            />
          </el-select>
          <el-select
            v-model="formData.goafOrebody"
            class="safe-area-item"
            filterable
            placeholder="矿体"
            @change="changeArea(2)"
          >
            <el-option :value="0" label="请选择矿体" disabled />
            <el-option
              v-for="(item, index) in goafOrebodys"
              :key="index"
              :value="item.goafOrebody"
              :label="item.goafOrebody"
            />
          </el-select>
          <el-select
            v-model="formData.goafOreheight"
            class="safe-area-item"
            filterable
            placeholder="中段"
            @change="changeArea(3)"
          >
            <el-option :value="0" label="请选择中段" disabled />
            <el-option
              v-for="(item, index) in goafOreheights"
              :key="index"
              :value="item.goafOreheight"
              :label="item.goafOreheight"
            />
          </el-select>
          <el-select
            v-model="formData.goafId"
            class="safe-area-item"
            filterable
            placeholder="采空区名称"
            @change="changeArea(4)"
          >
            <el-option :value="0" label="请选择采空区" disabled />
            <el-option
              v-for="item in goafNames"
              :key="item.goafId"
              :value="item.goafId"
              :label="item.goafName"
            />
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="安装地点" required>
        <el-input v-model="formData.goafDevLocation" placeholder="请输入安装地点" style="width:260px" />
      </el-form-item>
      <el-form-item label="设备类型" required>
        <el-select
          v-model="formData.goafDevTypeId"
          style="width: 260px"
        >
          <el-option
            v-for="item in sensorCats"
            :key="item.sensorTypeId"
            :value="item.sensorTypeId"
            :label="item.sensorTypeName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备安装时间">
        <el-date-picker
          v-model="formData.goafInstallTime"
          type="date"
          placeholder="设备安装时间"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          style="width: 260px"
        />
      </el-form-item>
      <el-form-item label="设备负责人部门">
        <el-cascader
          v-model="formData.goafDevGroupid"
          :options="treeData"
          :props="{ checkStrictly: true, emitPath: false }"
          style="min-width: 260px"
          filterable
          clearable
          @change="handleChange"
        >
          <template slot-scope="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item label="责任人员" prop="executeAccountId">
        <el-select v-model="formData.goafDevAccountId" style="width:260px" filterable clearable @change="handleUserSelect">
          <el-option v-for="item in userList" :key="item.accountId" :value="item.accountId" :label="item.accountName" />
        </el-select>
      </el-form-item>
    </el-form>
    <div class="btn-group">
      <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
      <el-button class="cancel-btn" @click="dialogVisible = false">取消</el-button>
    </div>
  </el-drawer>
</template>
<script>
import { toTree } from '@/utils/build-tree'
import { getGroupByList } from '@/api/system/groupApi'
import { getUserByPage } from '@/api/system/userApi'
import { getSensorCat } from '@/api/goaf/sensorCatApi'
import { getGoafBaseInfo } from '@/api/goaf/info'
import { createSensor, updateSensor } from '@/api/goaf/sensor'
export default {
  name: 'CameraModel',
  data() {
    return {
      title: '摄像头配置',
      ops: {
        bar: {
          keepShow: false,
          background: 'rgba(144, 147, 153, 0.4)',
          onlyShowBarOnScroll: false
        }
      },
      dialogVisible: false,
      sensorCats: [],
      goaf: [],
      formData: {
        goafOrebelt: 0,
        goafOrebody: 0,
        goafOreheight: 0,
        goafId: 0,
        goafName: '',
        goafDevLocation: '',
        ocId: undefined,
        goafDevName: '',
        goafDevTypename: '',
        goafDevTypeId: '',
        goafDevAccountId: undefined,
        goafDevGroupid: '',
        goafDevAccountName: '',
        goafInstallTime: ''
      },
      rules: {},
      ctrlLevelList: [],
      positionList: [],
      viewData: {},
      actionType: '',
      treeData: [],
      userList: [],
      goafOrebelts: [],
      goafOrebodys: [],
      goafOreheights: [],
      goafNames: [],
      groupList: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      getSensorCat().then((res) => {
        this.sensorCats = res.data.filter(item => item.sensorTypeName.includes('摄像头'))
      })
      getGoafBaseInfo().then((res) => {
        this.goaf = res.data
        this.goafOrebelts = res.data
        this.goafOrebodys = res.data
        this.goafOreheights = res.data
        this.goafNames = res.data
      })
      getGroupByList().then((resp) => {
        const { code, data } = resp
        if (code === 0) {
          const temp = toTree(
            data,
            {
              value: 'value',
              name: 'label',
              pValue: 'parentId'
            },
            {
              value: 'groupId',
              name: 'groupName',
              pValue: 'parentId'
            }
          )
          this.treeData = temp
          this.groupList = data
        }
      })
      getUserByPage({
        page: 1,
        limit: 999999
      }).then((resp) => {
        const { data } = resp
        this.userList = data
      })
    },
    handleChange(groupId) {
      this.formData.goafDevAccountId = ''
      this.formData.goafDevAccountName = ''
      getUserByPage({
        page: 1,
        limit: 999999,
        keyword: '',
        groupId
      }).then((resp) => {
        const { data } = resp
        this.userList = data
      })
    },
    changeArea(type) {
      const goafOrebelts = this.deeepClone(this.goafOrebelts)
      let goafOrebodys = this.deeepClone(this.goafOrebodys)
      let goafOreheights = this.deeepClone(this.goafOreheights)
      let goafNames = this.deeepClone(this.goafNames)
      if (type === 1) {
        goafOrebodys = goafOrebelts.filter(
          (item) => item.goafOrebelt === this.formData.goafOrebelt
        )
        // goafOrebodys = this.unique(goafOrebodys, 'goafOrebelt')
        this.goafOrebodys = goafOrebodys
        this.goafOreheights = []
        this.goafNames = []
        this.formData.goafOrebody = ''
        this.formData.goafOreheight = ''
        this.formData.goafId = ''
      } else if (type === 2) {
        goafOreheights = goafOrebodys.filter(
          (item) => item.goafOrebody === this.formData.goafOrebody
        )
        // goafOreheights = this.unique(goafOreheights, 'goafOreheight')
        this.goafOreheights = goafOreheights
        this.goafNames = []
        this.formData.goafOreheights = ''
        this.formData.goafId = ''
      } else if (type === 3) {
        goafNames = goafOreheights.filter(
          (item) => item.goafOreheight === this.formData.goafOreheight
        )
        // goafNames = this.unique(goafNames, 'goafName')
        this.goafNames = goafNames
        this.formData.goafId = ''
      } else {
        for (let i = 0; i < goafNames.length; i++) {
          if (this.formData.goafId === goafNames[i].goafId) {
            this.formData.goafName = goafNames[i].goafName
          }
        }
      }
      this.$forceUpdate()
    },
    // Show Add Dialog
    showAddModel() {
      this.resetFormData()
      this.actionType = 'ADD'
      this.title = '新增摄像头配置'
      this.dialogVisible = true
    },

    // Show Edit Dialog
    showEditModel(data) {
      this.resetFormData()
      this.actionType = 'UPDATE'
      this.title = '修改摄像头配置'
      this.dialogVisible = true
      // Life minus one
      const sensorCat = this.sensorCats.filter(
        (item) => item.sensorTypeName === data.goafDevTypename
      )[0]
      this.formData = {
        ...data,
        goafDevTypeId: sensorCat.sensorTypeId
      }
    },

    // Reset Form Data
    resetFormData() {
      this.formData = {
        goafOrebelt: 0,
        goafOrebody: 0,
        goafOreheight: 0,
        goafId: 0,
        goafName: '',
        goafDevLocation: '',
        ocId: undefined,
        goafDevName: '',
        goafDevTypename: '',
        goafDevAccountId: undefined,
        goafDevAccountName: '',
        goafInstallTime: '',
        goafDevGroupid: ''
      }
    },
    handleUserSelect(accountId) {
      const item = this.userList.filter((item) => item.accountId === accountId)
      const user = item[0]
      this.formData.groupId = user.groupId
      this.formData.goafDevGroupname = user.groupName
      this.formData.goafDevAccountName = user.accountName
      this.formData.positionId = user.positionId
      this.formData.positionName = user.positionName
    },
    // 提交
    submitForm(formName) {
      this.formData.goafDevGroupname = this.groupList.filter(item => item.groupId === this.formData.goafDevGroupid)[0].groupName
      const sensorCat = this.sensorCats.filter(
        (item) => item.sensorTypeId === this.formData.goafDevTypeId
      )[0]
      this.formData.goafDevTypename = sensorCat.sensorTypeName
      this.formData.ocId = sensorCat.ocId
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (
            this.formData.goafId === undefined ||
            this.formData.goafId === 'undefined' ||
            this.formData.goafId === ''
          ) {
            this.$message.error('请选择采空区！')
            return
          }
          switch (this.actionType) {
            case 'ADD':
              createSensor(this.formData)
                .then((resp) => {
                  const { code, msg } = resp
                  if (code === 0) {
                    this.dialogVisible = false
                    this.$message.success(msg)
                    this.formSuccess()
                  } else {
                    this.$message.error(msg)
                  }
                })
                .catch((error) => {
                  console.log(error)
                })
              break

            case 'UPDATE':
              updateSensor(this.formData)
                .then((resp) => {
                  const { code, msg } = resp
                  if (code === 0) {
                    this.dialogVisible = false
                    this.$message.success(msg)
                    this.formSuccess()
                  } else {
                    this.$message.error(msg)
                  }
                })
                .catch((error) => {
                  console.log(error)
                })
              break
          }
        } else {
          this.$message.error('error submit!!')
          return false
        }
      })
    },
    handleSelectUser(item) {
      console.log({ item })
    },
    formSuccess() {
      this.$emit('formSuccess')
    },
    resetFormField(formName) {
      this.$refs[formName].resetFields()
    },
    unique(arr = [], name = 'name') {
      const res = new Map()
      return arr.filter((item) => !res.has(item[name]) && res.set(item[name], 1))
    },
    deeepClone(params) {
      return JSON.parse(JSON.stringify(params))
    }
  }
}
</script>
<style lang="scss" scoped>
.btn-group {
  padding-left: 160px;
  margin-top: 50px;
}
.safe-area {
  color: #fff;
  display: flex;
  flex-wrap: wrap;
  .safe-area-item {
    margin: 0 5px 10px 0;
    width: 20%;
    min-width: 120px;
  }
  .el-input__inner {
    text-align: left !important;
  }
}
::v-deep.el-select-tree {
  .label {
    color: #606266 !important;
  }
  .el-tree-node.is-current > .el-tree-node__content,
  .el-tree-node__content:hover {
    background-color: #fff !important;
    color: #606266;
  }
}
</style>
