<template>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body>
    <el-form ref="dataForm" :rules="rules" :model="concentratorForm" label-position="right" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="集中器编号" prop="concencode">
            <el-input v-model.trim="concentratorForm.concencode" :disabled="isEditMode" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="SIM卡号" prop="simid">
            <el-input v-model.trim="concentratorForm.simid" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经度" prop="lng">
            <el-input v-model.trim="concentratorForm.lng" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="lat">
            <el-input v-model.trim="concentratorForm.lat" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="安装位置" prop="position">
            <el-input v-model.trim="concentratorForm.position" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="安装日期" prop="setupdate">
            <el-date-picker
              v-model="concentratorForm.setupdate"
              :default-value="today"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="权属单位" prop="deptid">
            <dept-select v-model="concentratorForm.deptid" :need-top="deptShowTop" dept-type="03" placeholder="选择权属单位" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="saveData">
        保存
      </el-button>
      <el-button @click="cancel">
        取消
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addConcen, updateConcen } from '@/api/device/concentrator'
import DeptSelect from '../../components/DeptSelect/index'
import { getToday } from '@/utils/dateutils'

export default {
  name: 'EditConcentrator',
  components: { DeptSelect },
  data() {
    const validateLng = (rule, value, callback) => {
      if (value !== '') {
        if ((/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value) === false) {
          callback(new Error('请填写大于0的数字'))
        } else {
          callback()
        }
      } else {
        callback(new Error('经度不能为空'))
      }
    }
    const validateLat = (rule, value, callback) => {
      if (value !== '') {
        if ((/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value) === false) {
          callback(new Error('请填写大于0的数字'))
        } else {
          callback()
        }
      } else {
        callback(new Error('纬度不能为空'))
      }
    }
    const validateSimId = (rule, value, callback) => {
      if (value !== '') {
        if ((/^(\d){14}$/).test(value) === false) {
          callback(new Error('正确的sim卡号为14位数字'))
        } else {
          callback()
        }
      } else {
        callback(new Error('SIM卡号不能为空'))
      }
    }
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update,
      deptShowTop: false, // 权属单位下拉是否显示顶级
      isEditMode: false,
      today: getToday('yyyy-MM-dd'),
      concentratorForm: {
        id: '',
        concencode: '',
        simid: '',
        lng: '',
        lat: '',
        position: '',
        setupdate: '',
        deptid: ''
      }, // 表单
      textMap: {
        update: '编辑',
        create: '新增'
      }, // 表头显示标题
      rules: {
        concencode: [{ required: true, message: '集中器编号不能为空', trigger: ['blur', 'change'] }],
        simid: [{ required: true, trigger: ['blur', 'change'], validator: validateSimId }],
        lng: [{ required: true, trigger: ['blur', 'change'], validator: validateLng }],
        lat: [{ required: true, trigger: ['blur', 'change'], validator: validateLat }],
        position: [{ required: true, message: '安装位置不能为空', trigger: ['blur', 'change'] }],
        deptid: [{ required: true, message: '组织机构必选', trigger: 'change' }],
        setupdate: [{ required: true, message: '安装日期不能为空', trigger: ['blur', 'change'] }]
      } // 前端校验规则
    }
  },
  methods: {
    // 初始化对话框
    initDialog: function(dialogStatus, dialogFormVisible, row = null) {
      this.dialogStatus = dialogStatus
      this.dialogFormVisible = dialogFormVisible
      if (dialogStatus === 'create') { // 如果是新增，清除验证
        this.isEditMode = false
        this.resetForm()
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else if (dialogStatus === 'update') { // 如果是修改，将row中数据填写到输入框中
        this.isEditMode = true
        this.concentratorForm = {
          id: row.id,
          concencode: row.concencode,
          simid: row.simid,
          lng: row.lng,
          deptid: row.deptid,
          lat: row.lat,
          position: row.position,
          setupdate: row.setupdate
        }
      }
    },
    // 重置表单
    resetForm() {
      this.concentratorForm = {
        id: '',
        concencode: '',
        simid: '',
        lng: '',
        lat: '',
        deptid: '',
        position: '',
        setupdate: getToday('yyyy-MM-dd')
      }
    },
    // 保存数据
    saveData: function() {
      if (this.dialogStatus === 'update') {
        this.updateData()
      } else if (this.dialogStatus === 'create') {
        this.createData()
      }
    },
    // 新增数据
    createData: function() {
      this.$refs['dataForm'].validate((valid) => {
        console.log(this.concentratorForm)
        if (valid) {
          addConcen(this.concentratorForm).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
              })
            }
          })
        }
      })
    },
    // 修改数据
    updateData: function() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateConcen(this.concentratorForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.$emit('watchChild')
              this.dialogFormVisible = 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%;
  }
</style>
