<template>
  <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="groupForm" label-well-code="right" label-width="110px">
      <el-row :span="24">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model.trim="groupForm.groupName" :readonly="!isEditMode" clearable type="text" />
        </el-form-item>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属组织" prop="deptId">
            <dept-select v-show="isEditMode" v-model="groupForm.deptId" :dept-show="true" :need-top="true" placeholder="所属组织"/>
            <el-input v-show="!isEditMode" v-model="groupForm.deptName" :readonly="!isEditMode" type="text" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="	设备类型">
            <el-select v-model="groupForm.deviceType" :disabled="dialogStatus!=='create'" placeholder="设备类型" filterable clearable @change="changelist">
              <el-option v-for="item in groupList" :key="item.value" :label="item.name" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="设备列表">
            <el-select v-model="groupForm.deviceIds" placeholder="设备列表" filterable clearable multiple>
              <el-option v-for="item in deviceList" :key="item.value" :label="item.name" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-show="isEditMode" slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" type="primary" @click="saveData">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import DeptSelect from '@/components/DeptSelect'
import { addGroup, editGroup, getGroupDetail } from '@/api/system/device'
import { getAllControllerList, getAllLamppostList, getAllLampList, getAllLampboxList, getAllCircuitList } from '@/api/system/device'
import { getLampDeviceType } from '@/api/system/allDict'
export default {
  name: 'EditGroup',
  components: { DeptSelect },
  data() {
    const typeValidator = (rule, value, callback) => {
      if (value === 0 || value === '' || typeof (value) === 'undefined') {
        return callback(new Error('请选择一项'))
      } else {
        return callback()
      }
    }

    return {
      deviceList: [],
      groupList: [],
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update,detail
      groupForm: {
        id: '', // id
        groupName: '',
        deviceType: '',
        deviceIds: [],
        deptId: ''
      }, // 表单
      textMap: {
        update: '编辑分组',
        create: '新增分组',
        detail: '详情'
      }, // 表头显示标题
      rules: {
        groupName: [{ required: true, message: '分组名称不能为空', trigger: ['blur', 'change'] }],
        deptId: [{ required: true, message: '所在组织不能为空', trigger: ['blur', 'change'], validator: typeValidator }]
      }, // 前端校验规则
      streetList: [], // 道路列表
      isEditMode: false,
      btnLoading: true // 保存按钮是否不允许点击
    }
  },
  created() {
    getLampDeviceType().then(response => {
      this.groupList = response.data
    })
  },
  methods: {
    changelist() {
      this.deviceList = []
      this.groupForm.deviceIds = []
      console.log(this.groupForm.deviceType)
      if (this.groupForm.deviceType === '1') { // 路灯控制器
        getAllControllerList().then(response => {
          for (var i = 0; i < response.data.length; i++) {
            var item = { name: response.data[i].controllerCode, value: response.data[i].id }
            this.deviceList.push(item)
          }
        })
      } else if (this.groupForm.deviceType === '2') { // 灯杆
        getAllLamppostList().then(response => {
          for (var i = 0; i < response.data.length; i++) {
            var item = { name: response.data[i].lamppostName, value: response.data[i].id }
            this.deviceList.push(item)
          }
        })
      } else if (this.groupForm.deviceType === '3') { // 路灯
        getAllLampList().then(response => {
          for (var i = 0; i < response.data.length; i++) {
            var item = { name: response.data[i].lampName, value: response.data[i].id }
            this.deviceList.push(item)
          }
        })
      } else if (this.groupForm.deviceType === '4') { // 灯箱
        getAllLampboxList().then(response => {
          for (var i = 0; i < response.data.length; i++) {
            var item = { name: response.data[i].lampboxName, value: response.data[i].id }
            this.deviceList.push(item)
          }
        })
      } else if (this.groupForm.deviceType === '5') { // 回路
        getAllCircuitList().then(response => {
          for (var i = 0; i < response.data.length; i++) {
            var item = { name: response.data[i].circuitName, value: response.data[i].id }
            this.deviceList.push(item)
          }
        })
      }
    },
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.btnLoading = false
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.resetForm()
        this.isEditMode = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        getGroupDetail(row.id).then(response => {
          const proupData = response.data
          this.groupForm = {
            id: row.id,
            groupName: proupData.groupName,
            deviceType: proupData.deviceType,
            deviceIds: proupData.deviceList,
            deptId: proupData.deptId
          }
          this.deviceList = []
          if (this.groupForm.deviceType === '1') { // 路灯控制器
            getAllControllerList().then(response => {
              for (var i = 0; i < response.data.length; i++) {
                var item = { name: response.data[i].controllerCode, value: response.data[i].id.toString() }
                this.deviceList.push(item)
              }
              this.groupForm.deviceIds = proupData.deviceList
            })
          } else if (this.groupForm.deviceType === '2') { // 灯杆
            getAllLamppostList().then(response => {
              for (var i = 0; i < response.data.length; i++) {
                var item = { name: response.data[i].lamppostName, value: response.data[i].id }
                this.deviceList.push(item)
              }
              this.groupForm.deviceIds = proupData.deviceList
            })
          } else if (this.groupForm.deviceType === '3') { // 路灯
            getAllLampList().then(response => {
              for (var i = 0; i < response.data.length; i++) {
                var item = { name: response.data[i].lampName, value: response.data[i].id }
                this.deviceList.push(item)
              }
              this.groupForm.deviceIds = proupData.deviceList
            })
          } else if (this.groupForm.deviceType === '4') { // 灯箱
            getAllLampboxList().then(response => {
              for (var i = 0; i < response.data.length; i++) {
                var item = { name: response.data[i].lampboxName, value: response.data[i].id }
                this.deviceList.push(item)
              }
              this.groupForm.deviceIds = proupData.deviceList
            })
          } else if (this.groupForm.deviceType === '5') { // 回路
            getAllCircuitList().then(response => {
              for (var i = 0; i < response.data.length; i++) {
                var item = { name: response.data[i].circuitName, value: response.data[i].id }
                this.deviceList.push(item)
              }
              this.groupForm.deviceIds = proupData.deviceList
            })
          }
        })
        this.isEditMode = true
      }
    },
    // 清除数据
    resetForm() {
      this.groupForm = {
        id: '', // id
        groupName: '',
        deviceType: '',
        deviceIds: [],
        deptId: ''
      }

      this.btnLoading = false
    },
    // 保存数据
    saveData: function() {
      this.btnLoading = true

      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addGroup(this.groupForm).then(response => {
            if (response.code === 200) {
              this.$confirm('新增成功，是否继续新增?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetForm()
                this.$nextTick(() => {
                  this.$refs['dataForm'].clearValidate()
                })
              }).catch(() => {
                this.$emit('watchChild')
                this.dialogFormVisible = false
              })
            } else {
              this.btnLoading = false
            }
          }).catch(() => {
            this.btnLoading = false
          })
        } else {
          this.btnLoading = false
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editGroup(this.groupForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.cancel()
            } else {
              this.btnLoading = false
            }
          })
        } else {
          this.btnLoading = false
        }
      })
    },
    cancel: function() {
      this.dialogFormVisible = false
      this.$emit('watchChild')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-select{
    width: 100%;
  }
  .el-date-editor{
    width: 100%;
  }
  .dialog-footer {
    margin-top: -20px;
    text-align: center;
  }
</style>
