<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="showEditModal"
      :close-on-click-modal="false"
      width="700px"
      :title="modalTitle"
    >
      <div>
        <Form
          :id="formId"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="80"
        >
          <Form-item label="所属菜单" prop="menuName">
            <el-input
              v-model="formObj.menuName"
              readonly
              placeholder="请选择所属菜单"
              @click.native="_selectZtree"
            />
          </Form-item>
          <Form-item label="类型" prop="type">
            <el-input v-model="formObj.type" name="type" placeholder="区分同一个菜单下的不同表格（请输入英文），如：tab1" />
          </Form-item>
          <Form-item label="表格名称" prop="name">
            <el-input v-model="formObj.name" name="name" placeholder="请输入表格名称,如：area-table" clearable />
          </Form-item>
          <Form-item label="标题" prop="title">
            <el-input v-model="formObj.title" name="title" placeholder="请输入标题名称，如：地区表格-名称" />
          </Form-item>
          <Form-item label="编码" prop="code">
            <el-input v-model="formObj.code" name="code" placeholder="请输入编码，如：name" />
          </Form-item>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </el-dialog>
    <!--选择上级菜单tree-->
    <selectResourceTree ref="treeModal" @on-result-change="_treeData" />
  </div>
</template>
<script>
/**
 * 添加编辑表格列
 */
import { sysTableColumn } from '../../../api'
import selectResourceTree from '../resource/tree/selectResourceTree'

export default {
  components: { selectResourceTree },
  data() {
    const validateName = (rule, value, callback) => {
      // 验证只能输入英文和数字
      const reg = /[A-Za-z0-9]+$/
      if (value === '' || value === undefined) {
        callback(new Error('标题不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('只能输入英文和数字!'))
      } else {
        callback()
      }
    }
    const validateCode = (rule, value, callback) => {
      // 验证只能输入英文和数字
      const reg = /[A-Za-z0-9]+$/
      if (value === '' || value === undefined) {
        callback(new Error('编码不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('只能输入英文和数字!'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      formId: '',
      modalTitle: '添加',
      formObj: {
        name: '',
        code: '',
        menuName: '',
        title: '',
        type: ''
      },
      ruleValidate: {
        name: [{ required: true, validator: validateName, trigger: 'blur' }],
        title: [
          { required: true, message: '表格名称不能为空', trigger: 'blur' }
        ],
        code: [{ required: true, validator: validateCode, trigger: 'blur' }],
        type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
        menuName: [
          { required: true, message: '所属菜单不能为空', trigger: 'blur' }
        ]
      },
      showEditModal: false,
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ],
      menuId: ''
    }
  },
  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.showEditModal = false
        this.$message.success(msg)
        this.$emit('on-result-change')
      }
      this._hideLoading()
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize(this.formId)
          data.menuId = this.menuId
          this._save(data)
        } else {
          this.$message.error('表单验证失败')
          this._hideLoading()
        }
      })
    },
    // 添加、编辑保存
    _save: async function(data) {
      // 添加、编辑
      if (this.$string(this.id).isEmpty()) {
        const result = await sysTableColumn.add(data)
        this._resultChange(result, '添加成功')
      } else {
        const result = await sysTableColumn.edit({
          id: this.id,
          obj: data
        })
        this._resultChange(result, '编辑成功')
      }
    },
    _cancel() {
      this.showEditModal = false
    },
    _open(treeObj, formObj) {
      this.showEditModal = true
      this.$nextTick(() => {
        this.formId = 'edit-form' + this.$randomCode()
        this.$refs.formObj.resetFields()
        this._hideLoading()
        if (this.$string(formObj).isEmpty()) {
          this.modalTitle = '添加表格列'
          this.id = ''
          if (JSON.stringify(treeObj) !== '{}') {
            this.menuId = treeObj.id
            this.formObj.menuName = treeObj.name
          } else {
            this.menuId = ''
            this.formObj.menuName = ''
          }
        } else {
          this.modalTitle = '编辑表格列'
          this.id = formObj.id
          this.menuId = formObj.menuId
          const tempData = formObj
          this.formObj = {
            name: tempData.name,
            code: tempData.code,
            menuName: tempData.menuName,
            title: tempData.title,
            type: tempData.type ? tempData.type : ''
          }
        }
      })
    },
    // 复制
    _openCopy(treeObj, formObj) {
      this.showEditModal = true
      this.$nextTick(function() {
        this.formId = 'edit-form' + this.$randomCode()
        this.$refs.formObj.resetFields()
        this._hideLoading()
        this.modalTitle = '复制表格列'
        this.id = ''
        this.menuId = formObj.menuId
        const tempData = formObj
        this.formObj = {
          name: tempData.name,
          code: tempData.code,
          menuName: tempData.menuName,
          title: tempData.title,
          type: tempData.type ? tempData.type : ''
        }
      })
    },
    // 选择tree
    _selectZtree() {
      this.$refs.treeModal._open()
    },
    _treeData(result) {
      this.menuId = result.id
      this.formObj.menuName = result.name
    }
  }
}
</script>
