<template>
  <el-dialog
    :title="`${id ? '编辑' : '新增'} - 法规文件目录`"
    :visible.sync="dialogVisible"
    custom-class="new-edition-dialog"
    width="50%"
    @closed="closed"
    @open="open"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="top"
      label-width="auto"
    >
      <el-row :gutter="24" style="flex-wrap:wrap" type="flex">
        <el-col :span="12">
          <el-form-item label="法规文件目录名称" prop="name">
            <el-input
              v-model="form.name"
              clearable
              placeholder="请输入法规文件目录名称"
              @input="handleInput"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法规文件目录编码" prop="code">
            <el-input
              v-model="form.code"
              clearable
              placeholder="请输入法规文件目录编码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="memo">
            <el-input
              v-model="form.memo"
              :autosize="{minRows: 2, maxRows: 4}"
              clearable
              placeholder="请输入备注"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :loading="saveLoading" type="primary" @click="handleSave">
        确 认
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import * as publicApi from '@/api/examDataMenu/examKnowledgeData'

import {getCodeRequest} from '@/api/systemInterface'

export default {
  name: 'TreeAddEditDialog',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    treeLevelData: {
      type: Object,
      default: () => ({})
    },
    type: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      rules: {
        name: [
          {required: true, message: '名称不能为空', trigger: ['blur', 'change']}
        ],
        code: [
          {required: true, message: '编码不能为空', trigger: ['blur', 'change']}
        ]
      },
      form: {
        code: ''
      },
      saveLoading: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    id() {
      return this.treeLevelData?.id || ''
    },
    parentId() {
      return this.treeLevelData?.parentId || ''
    }
  },
  methods: {
    // 打开弹层
    open() {
      if (this.id) {
        this.saveLoading = true
        this.getDetail(this.id)
      }
    },

    // 关闭弹层后
    closed() {
      const {rules} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {rules})

      this.$nextTick(_ => {
        this.$refs.form.$el.scrollTop = 0
        this.$refs.form.clearValidate()
      })
    },

    // 获取详情
    async getDetail(id) {
      try {
        this.form = await publicApi.treeDetails(id)
      } finally {
        this.saveLoading = false
      }
    },

    // 名称输入框事件
    handleInput(chinese = '') {
      if (chinese) {
        getCodeRequest({chinese, type: '0'}).then(
          res => (this.form.code = res.value)
        )
      } else {
        // 输入的值为空的时候，停止请求并清空编码
        getCodeRequest.cancel(_ => (this.form.code = ''))
      }
    },

    // 保存
    handleSave() {
      this.$refs.form.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          const myInterFace = this.id ? publicApi.treeEdit : publicApi.treeAdd

          try {
            let {state, message} = await myInterFace({
              ...this.form,
              type: this.type,
              parentId: this.parentId
            })

            if (state) {
              this.$emit('submit')
              message = this.id ? '编辑' : '新增'
              this.$message.success(`法规文件目录${message}成功`)
              this.dialogVisible = false
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
