<template>
  <div class="app-container">
    <div class="app-container">
      <el-dialog
        :title="title"
        :close-on-click-modal="false"
        :visible.sync="visible"
        top="4%"
      >
        <el-form
          ref="form"
          :model="formItem"
          :label-width="'100px'"
        >
          <el-form-item
            :label="$t('ec.user.tenant')"
            prop="tenantId"
            v-if="enableTenant===true"
          >
            <ec-tenant v-model="formItem.tenantId" />
          </el-form-item>
          <el-form-item
            :label="$t('ec.tree.parent')"
            prop="pid"
          >
            <ec-select-tree
              v-model="formItem.pid"
              check-strictly
              :title="$t('ec.tree.chooseParent')"
              url="api/v1/dict/ecipDict/data"
              :params="{excludeId: record.id}"
              @change="parentChange"
            />
          </el-form-item>
          <el-form-item
            label="type"
            prop="dictType"
            :rules="[
              {required: true, message:'type' + $t('ec.table.empty'), trigger:'blur'},
              { validator: validateType, trigger: 'blur' }
            ]"
          >
            <span v-if="!isRoot">{{ formItem.dictType }}</span>
            <el-input
              v-else
              v-model="formItem.dictType"
              type="text"
              placeholder="type"
            />
          </el-form-item>
          <el-form-item
            label="label"
            prop="vname"
            :rules="[
              {required: true, message:'label' + $t('ec.table.empty'), trigger:'blur'}
            ]"
          >
            <el-input
              v-model="formItem.vname"
              type="text"
              placeholder="label"
            />
          </el-form-item>
          <el-form-item
            v-if="!isRoot"
            label="value"
            prop="vkey"
            :rules="[
              {required: true, message:'value' + $t('ec.table.empty'), trigger:'blur'},
              { validator: validateVkey, trigger: 'blur' }
            ]"
          >
            <el-input
              v-model="formItem.vkey"
              type="text"
              placeholder="value"
            />
          </el-form-item>
          <el-form-item
            :label="$t('ec.dict.extra')"
            prop="extra"
          >
            <el-input
              v-model="formItem.extra"
              type="text"
              :placeholder="$t('ec.dict.extra')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('ec.table.sort')"
            prop="sortNum"
          >
            <el-input
              v-model="formItem.sortNum"
              type="text"
              :placeholder="$t('ec.table.sort')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('ec.table.enableStatus')"
            prop="valid"
            :rules="[
              {required: true, message: $t('ec.table.enableStatus') + $t('ec.table.empty'), trigger:'blur'}
            ]"
          >
            <ec-radio-group
              v-model="formItem.valid"
              dict-type="enableState"
            />
          </el-form-item>
          <el-form-item
            :label="$t('ec.table.remarks')"
            prop="remark"
          >
            <el-input
              v-model="formItem.remark"
              type="textarea"
              :autosize="{minRows: 3, maxRows: 5}"
            />
          </el-form-item>
        </el-form>

        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="visible = false">{{ $t('ec.table.close') }}</el-button>
          <el-button
            v-if="method !== 'view'"
            type="primary"
            :loading="confirmLoading"
            @click="save"
          >{{ $t('ec.table.confirm') }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import mixin from 'ecip-web/utils/common-mixin'
import {
  getById,
  save,
  update,
  checkVkey,
  checkDictType
} from 'ecip-web/api/vue/dict/ecipDictApi'
const enableTenant =
  window._CONFIG['enableTenant'] === undefined
    ? true
    : window._CONFIG['enableTenant']
export default {
  name: 'VueDictEcipDictForm',
  components: {},
  mixins: [...mixin],
  data() {
    return {
      enableTenant,
      record: {},
      visible: false,
      loading: false,
      confirmLoading: false,
      method: '',
      title: '',
      formItem: {
        tenantId: '',
        dictType: '',
        pid: '',
        vkey: '',
        vname: '',
        extra: '',
        valid: '1',
        sortNum: '',
        remark: ''
      }
    }
  },
  computed: {
    isRoot() {
      return (this.formItem && this.formItem.pid === '0') || !this.formItem.pid
    }
  },
  methods: {
    init(method, row, parent) {
      this.visible = true
      this.loading = false
      this.record = row
      this.method = method
      if (method === 'add') {
        this.title = this.$t('ec.table.add') + this.$t('ec.dict.dict')
      } else if (method === 'edit') {
        this.title = this.$t('ec.table.edit') + this.$t('ec.dict.dict')
      } else if (method === 'view') {
        this.title = this.$t('ec.table.view') + this.$t('ec.dict.dict')
      }
      this.$nextTick(async () => {
        // 清空初始化
        this.$refs.form.clearValidate()
        Object.assign(this.$data.formItem, this.$options.data().formItem)
        if (parent && parent.id) {
          this.formItem.pid = parent.id
          this.formItem.tenantId = parent.tenantId
          this.formItem.dictType = parent.dictType
        }
        if (method === 'edit' || method === 'view') {
          // 修改或者查看
          try {
            this.loading = true
            const { data } = await getById(row.id)
            this.formItem = Object.assign({}, this.formItem, data)
          } finally {
            this.loading = false
          }
        }
      })
    },
    async validateVkey(rule, value, callback) {
      const { data } = await checkVkey(
        (this.record && this.record.id) || '',
        this.formItem.pid,
        value
      )
      if (data.valid) {
        callback()
      } else {
        callback(
          new Error(this.$t('ec.table.code') + this.$t('ec.table.exist'))
        )
      }
    },
    async validateType(rule, value, callback) {
      //  新增子节点不校验、编辑子节点不校验
      if (
        (this.record && this.record.pid !== '0') ||
        this.formItem.pid !== '0'
      ) {
        callback()
        return
      }
      const { data } = await checkDictType(
        (this.record && this.record.id) || '',
        value
      )
      if (data.valid) {
        callback()
      } else {
        callback(new Error('type' + this.$t('ec.table.empty')))
      }
    },
    parentChange(parentId, parent) {
      if (!parent) {
        this.formItem.tenantId = ''
        this.formItem.dictType = ''
        return
      }
      this.formItem.tenantId = parent.tenantId
      this.formItem.dictType = parent.dictType
    },
    save() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.confirmLoading = true

            if (this.method === 'edit') {
              await update(this.record.id, this.formItem)
            } else {
              await save(this.formItem)
            }
            this.$message.success(this.$t('ec.message.saveSuccess'))
            this.$emit('refreshDataList')
            this.visible = false
          } finally {
            this.confirmLoading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
