<template>
  <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="boxForm" label-well-code="right" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="灯箱编号" prop="lampboxCode">
            <el-input v-model.trim="boxForm.lampboxCode" :readonly="!isEditMode" :maxlength="15" clearable type="text" placeholder="必填" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="灯箱名称" prop="lampboxName">
            <el-input v-model.trim="boxForm.lampboxName" :readonly="!isEditMode" :maxlength="30" clearable type="text" placeholder="必填" show-word-limit/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所在道路" prop="streetId">
            <el-select v-model="boxForm.streetId" :disabled="!isEditMode" placeholder="所在道路" filterable clearable>
              <el-option v-for="item in streetList" :key="item.id" :label="item.streetName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="灯箱地址">
            <el-input v-model.trim="boxForm.address" :maxlength="30" :readonly="!isEditMode" clearable type="text" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input ref="longitude" v-model.trim="boxForm.longitude" :readonly="!isEditMode" :maxlength="30" clearable type="text" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input ref="latitude" v-model.trim="boxForm.latitude" :readonly="!isEditMode" :maxlength="30" clearable type="text" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属组织">
            <dept-select v-show="isEditMode" v-model="boxForm.deptId" :dept-show="true" :need-top="true" placeholder="所属组织"/>
            <el-input v-show="!isEditMode" v-model="boxForm.deptName" :readonly="!isEditMode" type="text" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电信设备编号">
            <el-input v-model.trim="boxForm.teleId" clearable type="text" placeholder="非必填" />
          </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 { addLampbox, editLampbox } from '@/api/system/device'
import { getAllStreet } from '@/api/system/area'

export default {
  name: 'EditLampbox',
  components: { DeptSelect },
  data() {
    const typeValidator = (rule, value, callback) => {
      if (value === 0 || value === '' || typeof (value) === 'undefined') {
        return callback(new Error('请选择一项'))
      } else {
        return callback()
      }
    }
    const lonlatValidator = (rule, value, callback) => {
      if (value === 0 || value === '' || typeof (value) === 'undefined') {
        return callback(new Error('经纬度不能为空'))
      } else {
        const lonReg = /^(0?\d{1,2}(\.\d{1,10})?|1[0-7]?\d{1}(\.\d{1,10})?)$/
        const latReg = /^([0-8]?\d{1}(\.\d{1,10})?)$/

        const lon = this.$refs.longitude.value
        const lat = this.$refs.latitude.value

        if (lonReg.test(lon) === false || lon < 72 || lon > 136) {
          return callback(new Error('经度格式不正确'))
        } else if (latReg.test(lat) === false || lat > 54) {
          return callback(new Error('纬度格式不正确'))
        } else {
          return callback()
        }
      }
    }

    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update,detail
      boxForm: {
        id: '', // id
        lampboxCode: '', // 灯箱编号
        lampboxName: '', // 灯箱名称
        streetId: '',
        teleId: '',
        address: '', // 地址
        longitude: 116.397944,
        latitude: 39.910618,
        deptId: ''
      }, // 表单
      textMap: {
        update: '编辑灯箱',
        create: '新增灯箱',
        detail: '详情'
      }, // 表头显示标题
      rules: {
        lampboxCode: [{ required: true, message: '灯箱编号不能为空', trigger: ['blur', 'change'] }],
        streetId: [{ required: true, message: '所在道路不能为空', trigger: ['blur', 'change'], validator: typeValidator }],
        longitude: [{ required: true, trigger: ['blur', 'change'], validator: lonlatValidator }],
        latitude: [{ required: true, trigger: ['blur', 'change'], validator: lonlatValidator }]
      }, // 前端校验规则
      streetList: [], // 道路列表
      isEditMode: false,
      btnLoading: true // 保存按钮是否不允许点击
    }
  },
  created() {
    this.fetchStreetList() // 获取道路列表
  },
  methods: {
    // 初始化对话框
    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中数据填写到输入框中
        this.boxForm = {
          id: row.id,
          lampboxCode: row.lampboxCode,
          lampboxName: row.lampboxName,
          streetId: row.streetId,
          address: row.address,
          longitude: row.longitude,
          latitude: row.latitude,
          teleId: row.teleId,
          deptId: row.deptId
        }
        this.isEditMode = true
      } else if (dialogStatus === 'detail') {
        this.boxForm = {
          lampboxCode: row.lampboxCode,
          lampboxName: row.lampboxName,
          streetId: row.streetId,
          address: row.address,
          longitude: row.longitude,
          latitude: row.latitude,
          deptId: row.deptId,
          teleId: row.teleId,
          deptName: row.deptName
        }
        this.isEditMode = false
        this.$refs['dataForm'].clearValidate()
      }
    },
    fetchStreetList() {
      getAllStreet().then(response => {
        if (response.code === 200) {
          this.streetList = response.data
        }
      })
    },
    // 清除数据
    resetForm() {
      this.boxForm = {
        lampboxCode: '',
        lampboxName: '',
        streetId: '',
        address: '',
        teleId: '',
        longitude: 116.397944,
        latitude: 39.910618,
        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) {
          addLampbox(this.boxForm).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) {
          editLampbox(this.boxForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              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>
