<template>
  <div :class="$style.wrap">
    <SdCategoryTree
      ref="categoryTree"
      :class="$style.tree"
      :load-tree-data="loadTreeData"
      :delete-category-function="deleteCategory"
      @createCategory="createCategory"
      @editCategory="editCategory"
      @treeSelect="treeSelect"
    />
    <a-modal
      v-model="visible"
      :title="cateModalTitle"
      destroy-on-close
      :width="600"
      :mask-closable="false"
      :confirm-loading="confirmLoading"
      @ok="saveCategory"
      @cancel="() => (visible = false)"
    >
      <sd-form ref="form" :init-values="cateValues">
        <sd-form-item name="id" :input-props="{ addonBefore: idPrefix }" />
        <sd-form-item name="name" />
        <a-form-model-item
          label="上级分类"
          :rules="[
            {
              required: true,
              message: '不能为空',
              trigger: ['change', 'blur'],
            },
          ]"
          prop="parent"
        >
          <sd-tree-picker
            v-model="parentSel"
            single
            :load-tree-data="loadTreePickerData"
            @change="parentChange"
          />
        </a-form-model-item>
        <sd-form-item name="orderNum" />
        <sd-form-item name="parent" hidden :input-props="{ defaultValue: parent && parent.id }" />
      </sd-form>
    </a-modal>
  </div>
</template>

<script>
import cloneDeep from 'lodash.clonedeep'
import { message } from 'ant-design-vue'
import SdCategoryTree from '@/application-manage/components/sd-category-tree.vue'
import flowService from './flow-service'
import SdFlowDesignMixin from './sd-flow-design-mixin.vue'
import components from './_import-components/sd-flow-category-tree-import'

export default {
  name: 'SdFlowCategoryTree',
  components: {
    ...components,
    SdCategoryTree,
  },
  mixins: [SdFlowDesignMixin],
  data() {
    return {
      visible: false,
      cateModalTitle: '',
      confirmLoading: false,
      cateData: [
        {
          name: 'id',
          caption: '分类ID',
          dataType: 'string',
          required: true,
          attr: {
            regex: '^[A-Za-z]\\w*$',
            regexMessage: '以字母开头，输入字母、数字或下划线！',
            maxLength: 20,
          },
        },
        {
          name: 'name',
          caption: '分类名称',
          dataType: 'string',
          required: true,
          attr: {},
        },
        {
          name: 'parent',
          caption: '上级分类',
          dataType: 'string',
          required: true,
        },
        {
          name: 'orderNum',
          caption: '排序号',
          dataType: 'number',
          required: false,
        },
      ],
      currentCate: null,
      parentSel: [],
      parent: null,
    }
  },
  computed: {
    cateValues() {
      const initValues = cloneDeep(this.cateData)
      if (this.currentCate) {
        initValues.map((item) => {
          item.value = this.currentCate[item.name]
          // 编辑时，id不可修改
          if (item.name === 'id') {
            item.readonly = true
            item.attr = {}
          }
          return item
        })
      } else {
        initValues.map((item) => {
          if (item.name === 'id') {
            // id中必须包含字母和数字
            item.attr.defaultValue = 'C' + this.times
          }
          return item
        })
      }
      return initValues
    },
  },
  methods: {
    treeSelect(node) {
      this.$emit('treeSelect', node)
    },
    createCategory(parent) {
      // 分类id带着前缀'C'，需删除，避免选择上级分类时分类不能默认选中
      this.parent = { id: parent.id.slice(1), name: parent.text }
      this.parentSel = [{ ...this.parent }]
      this.currentCate = null
      this.cateModalTitle = '新建分类'
      this.updateTimes()
      this.visible = true
    },
    editCategory(id, parent) {
      this.parent = { id: parent.id.slice(1), name: parent.text }
      this.parentSel = [{ ...this.parent }]
      flowService.getFlowCateInfo({ categoryId: id.slice(1) }).then((res) => {
        this.currentCate = res.data
        this.cateModalTitle = '修改分类'
        this.visible = true
      })
    },
    saveCategory() {
      this.$refs.form.validateFields().then((flag) => {
        if (flag) {
          let p
          const formData = {}
          this.$refs.form.getBackendValues().forEach((item) => {
            formData[item.name] = item.value
          })
          if (this.currentCate) {
            // 编辑分类
            p = flowService.editFlowCate(formData)
          } else {
            // 新建分类
            // id添加前缀
            formData.id = this.idPrefix + formData.id
            p = flowService.createFlowCate(formData)
          }
          this.confirmLoading = true
          p.then((res) => {
            if (res.status === 200) {
              this.visible = false
              this.$refs.categoryTree.refresh()
            } else {
              message.error(res.data?.errors || '保存失败')
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    deleteCategory(id) {
      return this.deleteRows(() => flowService.deleteFlowCate({ id: id.slice(1) }))
    },
    loadTreePickerData(parentCatId) {
      // 选择流程分类
      const pId = parentCatId ? 'C' + parentCatId : ''
      return this.loadTreeData(pId).then((treeData) =>
        treeData.map((d) => ({
          id: d.id.slice(1), // 分类选择时，id去掉前缀'C'
          name: d.text,
          // 当前是流程分类编辑，选择上级分类时不能选择自己
          checkable: this.currentCate ? d.id.slice(1) !== this.currentCate.id : true,
          // 当前是流程分类编辑，选择上级分类时，本分类的子分类无需展示
          isLeaf: this.currentCate && d.id.slice(1) === this.currentCate.id ? true : d.leaf,
        }))
      )
    },
    parentChange(data) {
      this.$refs.form.setFieldValue('parent', data[0]?.id || '')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap {
  display: flex;
  flex-direction: column;
  width: 20%;
  margin-right: $padding-lg;
  .tree {
    width: 100%;
  }
}
</style>
