<template>
  <!-- 资料分类新增修改弹层 -->
  <super-dialog
    :title="`${id ? '修改' : '新增'}资料分类`"
    v-model="isShowDialog"
    width="28%"
    @open="open"
    @closed="closed"
    :modal="false"
  >
    <el-form
      :rules="treeRules"
      ref="treeForm"
      :model="treeForm"
      label-width="auto"
    >
      <el-form-item label="资料分类名称" prop="name">
        <el-input
          v-model="treeForm.name"
          @input="handleInput"
        ></el-input>
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input v-model="treeForm.code" readonly></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button size="small" @click="isShowDialog = false">取 消</el-button>
      <el-button size="small" type="primary" @click="subHandel">确 定</el-button>
    </template>
  </super-dialog>

</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import {
  treeAdd,
  treeEdit,
  treeDetails
} from '@/api/educationalTraining/policiesRegulations'
import req from '@/request'

export default {
  name: 'TreeDialog',
  props: {
    isShow: {
      default: false,
      type: Boolean
    },
    parentId: {
      default: '',
      type: String
    },
    id: {
      default: '',
      type: String
    }
  },
  components: {
    SuperDialog
  },
  data() {
    return {
      treeForm: {
        code: '',
        id: '',
        parentId: ''
      },
      treeRules: {
        name: [
          {
            required: true,
            message: '请输入资料分类名称',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入编码',
            trigger: 'blur'
          }
        ]
      },
      cancelTokenSource: null // 用于存储取消令牌
    }
  },
  computed: {
    isShowDialog: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      }
    }
  },
  created() {
  },
  methods: {
    // 打开弹层时触发
    open() {
      if (this.id) {
        this.getDetails(this.id)
      } else {
        this.treeForm = {
          ...this.treeForm,
          parentId: this.parentId
        }
      }
    },

    // 关闭弹层后触发
    closed() {
      this.treeForm = this.$options.data().treeForm
      this.$refs.treeForm.clearValidate()
      this.$emit('update:parentId', '')
      this.$emit('update:id', '')
    },

    // 获取详情
    async getDetails(id) {
      this.treeForm = await treeDetails(id)
    },

    // 资料分类名称输入框事件
    handleInput(value) {
      if (value.trim() === '') {
        // 输入为空时，尝试取消之前请求并清空结果
        if (this.cancelTokenSource) this.cancelTokenSource.cancel('因输入为空而取消')
        this.treeForm.code = ''
      } else {
        this.convertEncoding(value)
      }
    },

    // 转换编码
    async convertEncoding(chinese) {
      // 检查并取消之前的请求
      if (this.cancelTokenSource) {
        this.cancelTokenSource.cancel('取消之前的请求')
      }
      // 生成新的取消令牌
      this.cancelTokenSource = req.$http.CancelToken.source()

      try {
        // 发起新的请求
        const response = await req.$http({
          url: window.context.portal + `/base/tools/v1/getPinyin`,
          cancelToken: this.cancelTokenSource.token,
          params: {chinese, type: '0'}
        })
        this.treeForm.code = response.data?.value || ''
      } finally {
        this.cancelTokenSource = null // 清理取消令牌
      }
    },

    // 提交科目表单
    subHandel() {
      this.$refs['treeForm'].validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(`有${Object.keys(object).length}个字段未通过校验，请正确填写表单内容。`)
        } else {
          const myInterFace = this.id ? treeEdit : treeAdd
          const message = this.id ? '修改' : '新增'
          const {state} = await myInterFace({
            ...this.treeForm,
            type: '3'
          })
          if (state) {
            this.$message.success(`${message}资料分类成功`)
            this.$emit('catalogChange', 'treeDialog')
          } else {
            this.$message.error(`${message}资料分类失败`)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
