<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <mtx-process-catalog-tree
        ref="mtxProcessCatalogTree"
        show-line
        top-node-text="内控流程库"
        :is-select-dep="true"
        :draggable="true"
        :history="this.$route.query.history ? true : false"
        :hisv="this.$route.query.history ? this.$route.query.versionId : null"
        :hisorg="this.$route.query.history ? this.$route.query.orgId : null"
        :hisorgn="this.$route.query.history ? this.$route.query.orgName : null"
        @treeSelect="treeSelect"
        @depChanged="depChanged"
      ></mtx-process-catalog-tree>

      <div :class="$style.rightcard">
        <a-card>
          <sd-data-table-ex
            :key="key"
            ref="dataTable"
            :editnode="editnode"
            form-id="icMtxProcess"
            page-id="ic/process/icMtxProcess"
            :columns="columns1"
            :actions="actions"
            :search-fields="['prcName']"
            :filter-expressions="expressions"
            :show-selection="(item) => item.editAndDeleteAuth !== 0"
            :custom-delete-fun="deleteRows"
            @recordSaved="onRecordSaved"
            @formBtnClick="formBtnClick"
          >
            <template slot="prcName" slot-scope="text, record">
              <a
                v-if="record.editAndDeleteAuth !== 0"
                @click="
                  () => {
                    $refs.dataTable.showDetailModal(record.id, 'ic/process/icMtxProcess')
                  }
                "
                >{{ text }}</a
              >
              <span v-else>{{ text }}</span>
            </template>

            <!-- 详情表单 -->
            <template
              v-slot:form="{ model, fields, pageId }"
              v-sd-watermark="waterMark"
              @saved="onSaved"
            >
              <!-- 一般字段直接写name即可 -->

              <a-form-model-item
                prop="prcCode"
                label="流程分类编号"
                :rules="[
                  { validator: validator },
                  {
                    required: true,
                    trigger: ['change', 'blur'],
                  },
                ]"
              >
                <a-input v-model.trim="model.prcCode" />
              </a-form-model-item>
              <!-- <sd-form-item name="catalogCode" /> -->

              <sd-form-item name="prcName" />

              <sd-form-item name="prcDesc">
                <a-textarea v-model="model.prcDesc" :rows="3" />
              </sd-form-item>

              <sd-form-item name="isEnd" />

              <sd-form-item name="attachment"></sd-form-item>
              <!-- <sd-form-item name="attachment">
                <template v-slot:read-and-edit>
                  <sd-attachment
                    v-model="model.attachment"
                    :group-id="JSON.parse(fields.attachment.value).value"
                  />
                </template>
              </sd-form-item> -->
              <sd-form-item name="sortNum" />

              <sd-form-item
                :hidden="true"
                name="parentId"
                :input-props="{ defaultValue: parentId }"
              />

              <sd-form-item
                :hidden="true"
                name="auditOrgId"
                :input-props="{ defaultValue: auditOrgId }"
              />

              <sd-form-item
                :hidden="true"
                name="prcPath"
                :input-props="{ defaultValue: prcPath }"
              />
              <sd-form-item
                :hidden="true"
                name="mtxVersionId"
                :input-props="{ defaultValue: versionId }"
              />
            </template>
          </sd-data-table-ex>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { Modal, message } from 'ant-design-vue'
import TableColumnTypes from '@/common/services/table-column-types'
import systemManage from '@/system-manage/system-manage'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'
import TableActionTypes from '@/common/services/table-action-types'
import mtxProcessCatalogTree from './mtx-process-catalog-tree'
import MtxProcessService from './mtx-process-service'
import components from './_import-components/mtx-process-catalog-import'

export default {
  name: 'MtxProcessCatalog',
  metaInfo: {
    title: '内控流程分类配置',
  },
  components: {
    ...components,
    mtxProcessCatalogTree,
  },
  data() {
    return {
      editnode: true, // 列表是否可以新建
      key: 0,
      waterMark: systemManage.getFormWaterMark(),
      treeData: [],
      columns1: [
        {
          dataIndex: 'id',
          sdHidden: true,
        },
        {
          dataIndex: 'parentId',
          sdHidden: true,
        },
        {
          title: '排序号',
          dataIndex: 'sortNum',
          defaultSortOrder: 'ascend',
          width: '100px',
        },
        {
          title: '分类编号',
          dataIndex: 'prcCode',
        },
        {
          title: '分类名称',
          dataIndex: 'prcName',
          scopedSlots: { customRender: 'prcName' },
        },

        {
          title: '创建时间',
          dataIndex: 'creationTime',
          sorter: true,
          sdRender: TableColumnTypes.date,
        },
        {
          title: '是否末级分类',
          dataIndex: 'isEnd',
        },
      ],
      actions: [
        {
          label: '新建',
          type: 'primary',
          callback: this.create,
          // permission: 'iamAuditMatters-create',
          permission: null,
        },
        {
          label: '删除',
          id: 'delete',
          // permission: 'iamAuditMatters-delete',
          permission: null,
          type: 'delete',
          callback: this.deleteRows,
        },
      ],
      expressions: [
        {
          dataType: 'long',
          name: 'parentId',
          op: 'eq',
          longValue: null,
        },
        {
          dataType: 'long',
          name: 'auditOrgId',
          op: 'eq',
          longValue: null,
        },
        {
          dataType: 'long',
          name: 'mtxVersionId',
          op: 'eq',
          longValue: null,
        },
      ],
      parentId: -1,
      auditOrgId: null,
      parentName: '业务类型',
      prcPath: null,
      isEnd: null,
      versionId: null,
    }
  },
  mounted() {
    this.versionId = this.$route.query.versionId
  },
  methods: {
    treeSelect(selectedKeys, info) {
      this.prcPath = null
      // 父级id
      if (info != null && info.selectedNodes[0]) {
        this.parentId = Number(info.selectedNodes[0].data.props.id)
        this.parentName = info.selectedNodes[0].data.props.text // 父级名称
        //  this.orgId = Number(info.selectedNodes[0].data.props.id)
        this.editnode = info.selectedNodes[0].data.props.edit
        if (info.selectedNodes[0].data.props.props) {
          this.isEnd = info.selectedNodes[0].data.props.props.isEnd
        }

        // 判断父节点不为根节点
        // if (this.parentId !== this.$refs.mtxProcessCatalogTree.depvalue) {
        if (this.parentId !== -1) {
          if (info.selectedNodes[0].data.props.props.catalogPath) {
            this.prcPath = info.selectedNodes[0].data.props.props.catalogPath + ',' + this.parentId
          } else {
            this.prcPath = this.parentId
          }
        }
      } else {
        if (selectedKeys.id) {
          this.parentId = Number(selectedKeys.id)
          this.parentName = selectedKeys.text // 父级名称
        } else {
          this.parentId = -1
        }
      }
      // 如果是末级，则隐藏新建按钮
      this.expressions.forEach((item) => {
        if (item.name === 'parentId') {
          item.longValue = this.parentId
        }
        if (item.name === 'auditOrgId') {
          item.longValue = this.$refs.mtxProcessCatalogTree.depvalue
        }
        if (item.name === 'mtxVersionId') {
          item.longValue = this.$refs.mtxProcessCatalogTree.versionId
        }
      })
      this.expressions = [...this.expressions]
      this.auditOrgId = this.$refs.mtxProcessCatalogTree.depvalue
    },

    // 部门下拉框选择事件
    depChanged(value, info) {
      this.orgId = this.$refs.mtxProcessCatalogTree.depvalue
    },
    // 新建保存回调刷新树
    onRecordSaved() {
      this.$refs.mtxProcessCatalogTree.refreshNode(this.parentId)
    },
    // 删除回调
    onRecordsDeleted() {
      message.success('删除成功')
      this.$refs.mtxProcessCatalogTree.refreshNode(this.parentId)
    },
    formBtnClick(evt, btn, { form, recordId }) {
      if (btn.buttonId === 'save') {
        // 如果为末节点需要判断是否有子和子措施
        // 判断是否有下级
        if (form.$refs.form.getFieldValue('isEnd') === '1') {
          evt.preventDefault()
          MtxProcessService.CheckCategory([recordId]).then((res) => {
            if (!res) {
              Modal.info({
                content: '当前分类存在子类，无法变更为末级节点',
              })
              return false
            } else {
              form.$refs.form.save().then((res) => {
                message.success('保存成功')
                form.hide()
                this.$refs.mtxProcessCatalogTree.refreshNode(this.parentId)
                // this.$refs.dataTable.refreshNode(this.parentId)
                this.refresh()
              })
            }
          })
        }
      }
    },
    validator(rule, value, callback) {
      let id = -1
      if (this.$refs.dataTable.recordId) {
        id = this.$refs.dataTable.recordId
      }
      value = encodeURIComponent(value)
      const url =
        `api/xcoa-mobile/v1/icmtxprocess/check-category-code?catalogCode=${value}&parentId=${this.parentId}&id=` +
        id
      debounce(() => {
        axios.get(url).then((res) => {
          if (res.data) {
            callback()
          } else {
            callback('已存在分类编码，不可以重复')
          }
        })
      }, 500)()
    },

    deleteRows() {
      const ids = this.$refs.dataTable.getSelectedRowKeys()
      if (ids.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }

      // 判断是否有下级
      MtxProcessService.deleteCheckCategory(ids).then((res) => {
        if (!res) {
          return new Promise((resolve) => {
            Modal.confirm({
              title: '您确定删除这项内容吗？',
              content: '该层级下有数据，是否全部删除？',
              okText: '删除',
              okType: 'danger',
              cancelText: '取消',
              onOk: () => {
                this.deleteCategory(ids, resolve)
              },
              onCancel: () => {
                resolve()
              },
            })
          })
        } else {
          this.deleteCategory(ids, null)
        }
      })
    },

    create() {
      if (this.parentId === 0) {
        message.error('请选择上级节点！')
      } else {
        if (this.isEnd !== '1') {
          this.$refs.dataTable.showDetailModal(null, 'ic/process/icMtxProcess')
        } else {
          message.error('末级分类下不可再新建分类')
        }
      }
    },
    deleteCategory(ids, resolve) {
      MtxProcessService.deleteCategory(ids)
        .then(() => {
          this.$refs.dataTable.clearSelection()
          this.onRecordsDeleted()
          this.refresh()
        })
        .finally(resolve)
    },

    refresh() {
      this.$refs.dataTable.refresh()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
</style>
