<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="showModal"
      :close-on-click-modal="false"
      width="700px"
      :title="modalTitle"
    >
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Form id="edit-form" ref="formObj" :model="formObj" :rules="ruleValidate" :label-width="90">
          <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="请输入中文名" :maxlength="30" style="width: 100%" />
            </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="请输入英文名" :maxlength="40" style="width: 100%" />
            </el-tooltip>
          </Form-item>
          <Form-item label="国家二字码" prop="countryCode2">
            <el-input v-model="formObj.countryCode2" name="countryCode2" placeholder="请输入国家二字码" />
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { 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\s]+$/
      if (value === '') {
        callback(new Error('英文名不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('只能输入英文字母'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      modalTitle: '添加',
      formObj: {
        cn: '',
        code: '',
        countryCode2: 'CN',
        en: ''
      },
      ruleValidate: {
        cn: [{ required: true, validator: validateCn, trigger: 'blur' }],
        code: [{ required: true, validator: validateCode, trigger: 'blur' }],
        countryCode2: [
          { required: true, message: '国家二字码不能为空', trigger: 'blur' }
        ],
        en: [{ required: true, validator: validateEn, trigger: 'blur' }]
      },
      showModal: false,
      countryCode2List: [],
      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')
          this.$extend(data, { countryCode2: this.formObj.countryCode2 })
          this._save(data)
        } else {
          this.$message.error('表单验证失败!')
          this._hideLoading()
        }
      })
    },
    _save: async function(data) {
      if (this.$string(this.id).isEmpty()) {
        const result = await sysProvince.add(data)
        this._resultChange(result, '添加成功!')
      } else {
        const result = await sysProvince.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._hideLoading()
        if (this.$string(formObj).isEmpty()) {
          this.id = ''
          this.modalTitle = '添加省份'
        } else {
          this.id = formObj.id
          this.formObj = formObj
          this.modalTitle = '编辑省份'
        }
      })
    }
  }
}
</script>
