<template>
  <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="postForm" label-well-code="right" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="路灯杆编号" prop="lamppostCode">
            <el-input v-model.trim="postForm.lamppostCode" :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="lamppostName">
            <el-input v-model.trim="postForm.lamppostName" :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="lamppostType">
            <el-select v-model="postForm.lamppostType" placeholder="请选择路灯杆型号" clearable>
              <el-option v-for="item in typeList" :key="item.value" :label="item.name" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="灯杆高度" prop="height">
            <el-input v-model.trim="postForm.height" :maxlength="30" clearable type="text" placeholder="（单位：米，非必填）" />
          </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="postForm.streetId" 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="postForm.address" :maxlength="30" 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="postForm.longitude" :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="postForm.latitude" :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-model="postForm.deptId" :dept-show="true" :need-top="true" placeholder="所属组织"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div 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 { addLamppost, editLamppost } from '@/api/system/device'
import { getLamppostType } from '@/api/system/allDict'
import { getAllStreet } from '@/api/system/area'

export default {
  name: 'EditLamppost',
  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
      postForm: {
        id: '', // id
        lamppostCode: '', // 路灯杆编号
        lamppostName: '', // 路灯杆名称
        lamppostType: '', // 路灯杆类型
        height: '', // 灯杆高度
        streetId: '',
        address: '', // 地址
        longitude: 0,
        latitude: 0,
        deptId: ''
      }, // 表单
      textMap: {
        update: '编辑路灯杆',
        create: '新增路灯杆',
        detail: '详情'
      }, // 表头显示标题
      rules: {
        lamppostCode: [{ required: true, message: '路灯杆编号不能为空', trigger: ['blur', 'change'] }],
        streetId: [{ required: true, message: '所在道路不能为空', trigger: ['blur', 'change'], validator: typeValidator }],
        lamppostType: [{ required: true, message: '路灯杆类型不能为空', trigger: ['blur', 'change'], validator: typeValidator }],
        longitude: [{ required: true, trigger: ['blur', 'change'], validator: lonlatValidator }],
        latitude: [{ required: true, trigger: ['blur', 'change'], validator: lonlatValidator }]
      }, // 前端校验规则
      typeList: [], // 灯杆类型列表
      streetList: [], // 道路列表
      isEditMode: false,
      btnLoading: true // 保存按钮是否不允许点击
    }
  },
  created() {
    this.fetchLamppostType()// 获取设备类别
    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 = false
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.postForm = {
          id: row.id,
          lamppostCode: row.lamppostCode,
          lamppostName: row.lamppostName,
          lamppostType: row.lamppostType,
          height: row.height,
          streetId: row.streetId,
          address: row.address,
          longitude: row.longitude,
          latitude: row.latitude,
          deptId: row.deptId
        }
        this.isEditMode = true
      }
    },
    fetchLamppostType() {
      getLamppostType().then(response => {
        if (response.code === 200) {
          this.typeList = response.data
        }
      })
    },
    fetchStreetList() {
      getAllStreet().then(response => {
        if (response.code === 200) {
          this.streetList = response.data
        }
      })
    },
    // 清除数据
    resetForm() {
      this.postForm = {
        lamppostCode: '',
        lamppostName: '',
        controllerType: '',
        height: '',
        streetId: '',
        address: '',
        longitude: 0,
        latitude: 0,
        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) {
          addLamppost(this.postForm).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) {
          editLamppost(this.postForm).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>
