<template>
  <GlobalWindow
    :title="title"
    v-model:visible="visible"
    width="750px"
    :confirm-working="isWorking"
    @confirm="confirm"
  >
    <el-form :model="form" ref="form" :rules="rules">
      <el-form-item label="字典编码" prop="code" required>
        <el-input
          v-model="form.code"
          placeholder="请输入字典编码"
          v-trim
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="字典名称" prop="name" required>
        <el-input
          v-model="form.name"
          placeholder="请输入字典名称"
          v-trim
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="应用" prop="scopes" required>
        <DictSelect
          v-model="form.scopes"
          code="APP_IDS"
          placeholder="请选择字典应用"
          :multiple="true"
        />
        <FormItemTip>字典数据会在应用启动或访问时一次性加载到服务端和客户端，以方便代码读取。</FormItemTip>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注"
          :rows="5"
          show-word-limit
          v-trim
          maxlength="200"
        />
      </el-form-item>
    </el-form>
  </GlobalWindow>
</template>

<script>
import BaseOpera from '@/components/base/BaseOpera'
export default {
  name: 'OperaDictWindow',
  extends: BaseOpera,
  data () {
    const _this = this
    return {
      // 表单数据
      form: {
        id: null,
        code: '',
        name: '',
        scopes: [_this.$c('DEFAULT_DICT_SCOPE')],
        remark: ''
      },
      // 验证规则
      rules: {
        code: [
          { required: true, message: '请输入字典编码' }
        ],
        name: [
          { required: true, message: '请输入字典名称' }
        ]
      }
    }
  },
  methods: {
    /**
     * 打开窗口
     *
     * @param title 窗口标题
     * @param target 行对象（仅编辑需该参数）
     */
    open (title, target) {
      this.title = title
      this.visible = true
      // 新建
      if (target == null) {
        this.$nextTick(() => {
          this.$refs.form.resetFields()
          this.form[this.configData['field.id']] = null
        })
        return
      }
      // 编辑
      this.$nextTick(() => {
        for (const key in this.form) {
          this.form[key] = target[key]
        }
        // 将作用域调整为数组
        this.form.scopes = this.form.scopes == null || this.form.scopes === '' ?
          [] : this.form.scopes.split(',').filter(scope => scope.trim() !== '')
      })
    },
    /**
     * 获取新增编辑表单对象
     * @returns {*}
     * @private
     */
    __getForm () {
      const form = JSON.parse(JSON.stringify(this.form))
      // 前后补充逗号，方便模糊查询
      form.scopes = `,${form.scopes.join(',')},`
      return form
    }
  },
  async created () {
    this.config({
      api: await import('@/api/system/dict')
    })
  }
}
</script>
