<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="showModal"
      :close-on-click-modal="false"
      width="700px"
      :title="modalTitle"
    >
      <div>
        <Form id="edit-form" ref="formObj" :model="formObj" :rules="ruleValidate" :label-width="80">
          <Form-item label="城市编码" prop="code">
            <el-tooltip content="只能输入数字文且长度为6" placement="bottom-start">
              <el-input
                v-model="formObj.code"
                name="code"
                placeholder="请输入城市编码"
                style="width:100%"
                :maxlength="6"
              />
            </el-tooltip>
          </Form-item>
          <Form-item label="中文名" prop="cn">
            <el-tooltip content="只能输入中文文且长度为0-30" placement="bottom-start">
              <el-input
                v-model="formObj.cn"
                name="cn"
                placeholder="请输入中文名"
                style="width:100%"
                :maxlength="30"
              />
            </el-tooltip>
          </Form-item>
          <Form-item label="英文名" prop="en">
            <el-tooltip content="只能输入英文且长度为0-40" placement="bottom-start">
              <el-input v-model="formObj.en" name="en" placeholder="请输入英文名" style="width:100%" :maxlength="40" />
            </el-tooltip>
          </Form-item>
          <Form-item label="省份编码" prop="provinceCode">
            <el-select
              v-model="formObj.provinceCode"
              style="width:100%"
              clearable
              filterable
              placeholder="请选择省份编码"
            >
              <el-option
                v-for="item in provinceCodeList"
                :key="item.id"
                :value="item.code"
                :label="item.cn +' -- '+ item.code +' -- '+item.countryCode2"
              />
            </el-select>
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { sysCity, sysProvince } from '../../../api'
export default {
  data() {
    const validateCode = (rule, value, callback) => {
      // 验证城市编码
      const reg = /^\d{6}$/
      if (value === '') {
        callback(new Error('城市编码不能为空'))
      } else if (!reg.test(value) || value.length !== 6) {
        callback(new Error('请输入数字且长度为6'))
      } else {
        callback()
      }
    }
    const validateCn = (rule, value, callback) => {
      // 验证中文名称
      const reg = /[\u4E00-\u9FA5]+$/
      if (value === '') {
        callback(new Error('中文名不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('只能输入中文字符'))
      } else {
        callback()
      }
    }
    const validateEn = (rule, value, callback) => {
      // 验证英文名称
      const reg = /[A-Za-z]+$/
      if (value === '') {
        callback(new Error('英文名不能为空'))
      } else if (!reg.test(this.formObj.en)) {
        callback(new Error('请输入英文字符！'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      modalTitle: '添加',
      formObj: {
        cn: '',
        code: '',
        en: '',
        provinceCode: ''
      },
      ruleValidate: {
        cn: [{ required: true, validator: validateCn, trigger: 'blur' }],
        code: [{ required: true, validator: validateCode, trigger: 'blur' }],
        en: [{ required: true, validator: validateEn, trigger: 'blur' }],
        provinceCode: [
          { required: true, message: '省份编码不能为空', trigger: 'change' }
        ]
      },
      showModal: false,
      provinceCodeList: [],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ]
    }
  },
  methods: {
    // modal
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '保存':
          this._ok()
          break
      }
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _resultChange(result, msg) {
      if (result) {
        this.showModal = false
        this.$message.success(msg)
        this.$emit('on-result-change')
      }
      this._hideLoading()
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          data.provinceCode = this.formObj.provinceCode
          this._save(data)
        } else {
          this.$message.error('表单验证失败!')
          this._hideLoading()
        }
      })
    },
    _save: async function(data) {
      if (this.$string(this.id).isEmpty()) {
        const result = await sysCity.add(data)
        this._resultChange(result, '添加成功!')
      } else {
        const result = await sysCity.edit({ id: this.formObj.id, obj: data })
        this._resultChange(result, '编辑成功!')
      }
    },
    _cancel() {
      this.showModal = false
    },
    _open(formObj) {
      this.showModal = true
      this.$nextTick(() => {
        this.$refs.formObj.resetFields()
        this._getProvince()
        this._hideLoading()
        if (this.$string(formObj).isEmpty()) {
          this.id = ''
          this.modalTitle = '添加城市'
        } else {
          this.id = formObj.id
          this.formObj = formObj
          this.modalTitle = '编辑城市'
        }
      })
    },
    _getProvince: async function() {
      const result = await sysProvince.list()
      this.provinceCodeList = result
    }
  }
}
</script>
