<template>
  <el-form :model="dictData" :rules="dictRule" ref="dictData" label-width="165px" style="padding-top: 20px">
    <el-form-item label="字典名称" prop="dictName">
      <el-input placeholder="请输入内容" v-model.trim="dictData.dictName" maxlength="20" show-word-limit style="width: 400px"></el-input>
    </el-form-item>
    <el-form-item label="key" prop="dictKey">
      <el-input placeholder="请输入内容" v-model.trim="dictData.dictKey" maxlength="50" show-word-limit style="width: 400px"></el-input>
    </el-form-item>
    <el-form-item label="字段描述">
      <el-input placeholder="请输入内容" type="textarea" v-model.trim="dictData.dictDesc" maxlength="50" rows="4" show-word-limit style="width: 400px"></el-input>
    </el-form-item>
    <el-form-item label="内容" prop="dictContent">
      <dm-editor :value="dictData.dictContent" width="575px" height="326px" @change="val => dictData.dictContent = val"></dm-editor>
    </el-form-item>
    <el-form-item style="margin-top: 50px">
      <el-button type="primary" :loading="loading" @click="onSave">{{ dictData.dictId ? '保存' : '确认新建' }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import fetch from '@/api/dictionary';

const { saveDict, dictDetail } = fetch;
export default {
  name: 'CreateDictionary',
  data() {
    return {
      bread: [ { name: '业务字典', path: '/dictionary-list' } ],
      loading: false,
      dictData: {
        dictName: '',
        dictKey: '',
        dictDesc: '',
        dictContent: '',
        dictId: ''
      },
      dictRule: {
        dictName: [ { required: true, message: '请输入字典名称', trigger: 'blur' } ],
        dictKey: [ { required: true, message: '请输入字典key', trigger: 'blur' } ],
        dictContent: [ { required: true, message: '请输入内容', trigger: 'blur' } ],
      }
    };
  },
  mounted() {
    const dictId = this.$route.query.dictId;
    if (dictId) {
      this.getDictDetail(dictId);
      this.bread.push({ name: '编辑字典' });;
    } else {
      this.bread.push({ name: '新建字典' });;
    }
    this.$emit('updateBread', this.bread);
  },
  methods: {
    // 编辑字典时获取字典数据
    getDictDetail(dictId) {
      dictDetail({ dictId }).then(res => {
        const { dictName, dictKey, dictDesc, dictContent, dictId } = res.result;
        Object.assign(this.dictData, { dictName, dictKey, dictDesc, dictContent, dictId });
      });
    },
    // 新建、编辑字典 保存
    onSave() {
      this.$refs.dictData.validate(vali => {
        if (!vali) return;
        const { dictName, dictKey, dictDesc, dictContent, dictId } = this.dictData;
        const params = { dictName, dictKey, dictDesc, dictContent };
        this.loading = true;
        if (dictId) {
          Object.assign(params, { dictId });
        }
        saveDict(params).then(res => {
          this.$message.success(dictId ? '保存成功！' : '新建成功！' );
          this.$router.go(-1);
        }).finally(() => this.loading = false);
      });
    }
  }
};
</script>
