<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <a-card :class="[$style.treewrap, $style.tree, { [$style.collapse]: fold }]">
        <!-- 左侧的树 -->
        <a-input-search
          v-model="searchValue"
          placeholder="请输入"
          allow-clear
          @change="onSearchChange"
        />
        <a-tree
          v-if="treeData.length > 0"
          :selected-keys="selectedKeys"
          :expanded-keys="expandedKeys"
          :default-expanded-keys="['parent']"
          :auto-expand-parent="autoExpandParent"
          show-icon
          :tree-data="treeData"
          :load-data="onLoadData"
          @select="treeSelect"
          @expand="onExpand"
        >
          <template v-slot:title="{ title }">
            <span v-if="title.indexOf(searchValue) > -1">
              {{ title.substr(0, title.indexOf(searchValue))
              }}<span :class="$style.active">{{ searchValue }}</span
              >{{ title.substr(title.indexOf(searchValue) + searchValue.length) }}</span
            ><span v-else>{{ title }}</span>
          </template>
        </a-tree>
        <a-button type="primary" :class="$style.fold" @click="foldClick">
          <a-icon :type="icontype" />
        </a-button>
      </a-card>
      <div :class="$style.rightcard">
        <a-card :class="$style.form">
          <!-- 右侧的表单 -->
          <sd-data-table-ex
            ref="rightTable"
            form-id="weAuditElement"
            page-id="workflow/auditelement/weAuditElement"
            data-url="api/framework/v1/audit-element/get-element-by-catId"
            :columns="columns"
            :actions="actions"
            :filter-expressions="expressions"
            :modal-props="{ class: $style.tableModal }"
            show-selection
            :search-fields="['elementContent']"
          >
            <template v-slot:form>
              <sd-form-item name="elementType"></sd-form-item>
              <sd-form-item name="elementContent"></sd-form-item>
              <sd-form-item name="status"></sd-form-item>
              <sd-form-item name="sortNum"></sd-form-item>
              <sd-form-item
                name="weAuditElementFlowEntityList"
                :label="null"
                :input-props="{
                  columns: [
                    { dataIndex: 'flowId', sdHidden: true },
                    { dataIndex: 'stepId', sdHidden: true },
                  ],
                }"
                @change="onChange"
              >
                <template v-slot:input-form="{ model: childModel }">
                  <sd-form-item name="flowName">
                    <sd-tree-picker
                      v-model="childModel.flowName"
                      single
                      title="选择流程"
                      :load-tree-data="loadFlowTreeData"
                      :search-tree-data="searchTreeData"
                      @change="(value) => getflow(value, childModel)"
                    />
                  </sd-form-item>
                  <sd-form-item name="stepName">
                    <sd-list-picker
                      v-model="childModel.stepName"
                      :load-list-data="loadListData"
                      :disabled-keys="disabledKeys"
                      option-label="name"
                      option-value="id"
                      @change="getstep"
                    ></sd-list-picker>
                  </sd-form-item>
                </template>
              </sd-form-item>
            </template>
          </sd-data-table-ex>
        </a-card>
      </div>
    </div>
    <a-modal v-model="importVisible" title="导入审核要素" :footer="null" :width="700">
      <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="导入文件">
          <a-upload-dragger :file-list="[]" :custom-request="(file) => uploadExcel(file)">
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text">
              点击或将文件拖拽到这里上传
            </p>
          </a-upload-dragger>
        </a-form-item>
        <a-form-item label="导入模板">
          <a-button type="link" @click="(e) => downloadReview()">点击下载</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import FlowService from '@/webflow/flow-service'
import { message } from 'ant-design-vue'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import download from '@/common/services/download'
import axios from '@/common/services/axios-instance'
import workbenchService from './workbench-service'
import components from './_import-components/sd-review-config-import'
const getSearchKey = (arr, str) => {
  let keys = []
  arr.forEach((a) => {
    if (a.children) keys = [...getSearchKey(a.children, str), ...keys]
    if (a.title.indexOf(str) > -1) keys.push(a.key)
  })
  return keys
}
const columns = [
  {
    key: 'sortNum',
    dataIndex: 'sortNum',
    title: '排序号',
    width: '150px',
  },
  {
    key: 'elementTypeName',
    dataIndex: 'elementTypeName',
    title: '分类名称',
  },
  {
    key: 'elementContent',
    dataIndex: 'elementContent',
    title: '审核要素',
    sdClickable: true,
  },
  {
    key: 'status',
    dataIndex: 'status',
    title: '状态',
    width: '150px',
    sdRender: TableColumnTypes.ex.switch,
  },
]
export default {
  name: 'SdReviewConfig',
  metaInfo: {
    title: '审核要素配置',
  },
  components,
  filters: {
    filterText(val) {
      const textArr = JSON.parse(val)
      return textArr.map((item) => item.name).join(',')
    },
  },
  data() {
    return {
      treeData: [{ title: '审核要素', key: 'parent', scopedSlots: { title: 'title' } }],
      importVisible: false,
      columns,
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.oa.create,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.oa.delete,
        },
        {
          label: '导入',
          id: 'import',
          permission: 'import',
          callback: () => {
            this.importVisible = true
          },
        },
        {
          label: '导出',
          id: 'export',
          type: TableActionTypes.batch,
          permission: 'export',
          callback: (keys, records) => {
            this.downloadReview(keys)
          },
        },
      ],
      options: [],
      selectFlow: {},
      stepName: [],
      selectedKeys: ['parent'],
      expandedKeys: ['parent'],
      selectNode: {},
      disabledKeys: [],
      icontype: 'left',
      searchValue: '',
      fold: false,
      autoExpandParent: false,
    }
  },
  computed: {
    expressions() {
      return [
        {
          dataType: 'str',
          name: 'selectId',
          op: 'eq',
          stringValue: this.selectNode?.id || '',
        },
        {
          dataType: 'str',
          name: 'selectType',
          op: 'eq',
          stringValue: this.selectNode?.props?.type || '',
        },
      ]
    },
  },
  created() {},
  methods: {
    downloadReview(ids) {
      const url = `api/framework/v1/audit-element/excel-export${ids ? '?ids=' + ids : ''}`
      const fname = '审核要素.xls'
      download(url, fname)
      this.$refs.rightTable.clearSelection()
    },
    searchTreeData(text) {
      const params = {
        listFlow: true,
        rootType: -1,
        name: text,
      }
      return FlowService.searchFlowTree(params).then((res) => {
        return res.data.map((item) => {
          return {
            id: item.id,
            name: item.text,
            checkable: item.leaf,
            isLeaf: item.leaf,
            expandable: item.expandable,
          }
        })
      })
    },
    uploadExcel(file) {
      const formData = new FormData()
      formData.append('file', file.file)
      axios
        .post('api/framework/v1/audit-element/excel-import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
        .then((res) => {
          if (res.data.length) {
            message.info({
              content: () => {
                return [
                  <div>
                    {res.data.map((r) => (
                      <div>{r}</div>
                    ))}
                  </div>,
                ]
              },
            })
          } else message.success('导入成功')
        })
        .finally(() => {
          this.importVisible = false
          this.$refs.rightTable.refresh()
        })
    },
    foldClick() {
      this.fold = !this.fold
      if (this.fold) {
        this.icontype = 'right'
      } else {
        this.icontype = 'left'
      }
    },
    treeSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys
      this.selectNode = info.node.dataRef
    },
    loadFlowTreeData(parentCatId = '') {
      if (!parentCatId) {
        return axios.get('api/framework/v1/audit-element/flow-selector/root-node').then((res) => {
          return res.data.map((item) => {
            return {
              id: item.id,
              name: item.text,
              checkable: item.leaf,
              isLeaf: item.leaf,
            }
          })
        })
      }
      // 获取流程树
      return workbenchService.getReviewTree(parentCatId).then((res) => {
        return res.data.map(function(item) {
          return {
            id: item.id,
            name: item.text,
            checkable: item.leaf,
            isLeaf: item.leaf,
          }
        })
      })
    },
    onLoadData(treeNode) {
      return new Promise((resolve) => {
        if (treeNode.dataRef.children) {
          resolve()
        }
        workbenchService.getReviewTree(treeNode.dataRef.id || '').then((res) => {
          if (res.data.length === 0) {
            treeNode.dataRef.isLeaf = true
          }

          treeNode.dataRef.children = res.data.map((item) => {
            item.title = item.text
            item.key = item.id
            item.isLeaf = item.leaf
            item.scopedSlots = { title: 'title' }
            return item
          })
          this.treeData = [...this.treeData]
          resolve()
        })
      })
    },
    onSearchChange(e) {
      if (this.searchValue) {
        this.expandedKeys = getSearchKey(this.treeData, this.searchValue)
        this.autoExpandParent = true
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    getflow(flow, model) {
      if (!flow.length) {
        model.stepName = []
        this.selectFlow = {}
        return
      }
      this.selectFlow.flowId = flow[0]?.id || ''
      this.selectFlow.flowName = flow[0].name || ''
      const oldFlowList = this.$refs.rightTable
        .getDetailModal()
        .getFieldValue('weAuditElementFlowEntityList')
      if (oldFlowList?.length) {
        const flowList = oldFlowList.reduce((res, item, index) => {
          res[item.flowId] = [...(res[item.flowId] || []), oldFlowList[index].stepId]
          return res
        }, {})
        this.disabledKeys = flowList[this.selectFlow.flowId]
      } else this.disabledKeys = []
    },
    loadListData() {
      return workbenchService.getFlowlink(this.selectFlow.flowId).then((res) => {
        return res.data
      })
    },
    getstep(step) {
      this.stepName = step.map((item) => {
        return {
          stepId: item.id,
          stepName: item.name,
        }
      })
    },
    onChange() {
      const oldFlowList = this.$refs.rightTable
        .getDetailModal()
        .getFieldValue('weAuditElementFlowEntityList')
      const newData = this.stepName.map((item) => {
        return {
          ...this.selectFlow,
          ...item,
        }
      })
      const isAdd = oldFlowList.length && oldFlowList[oldFlowList.length - 1].flowId
      if (!isAdd) {
        oldFlowList.pop()
        const newFlowList = [...oldFlowList, ...newData]
        this.$refs.rightTable
          .getDetailModal()
          .setFieldValue('weAuditElementFlowEntityList', newFlowList)
      }
    },
  },
}
</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%;
      :global(.ant-card) {
        min-height: 100%;
      }
    }
  }
}
.tree {
  :global(.ant-tree-title) {
    display: inline-block;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  :global(.ant-input-search) {
    margin: 8px 0;
    overflow: hidden;
  }
  .active {
    color: $primary-color;
  }
}
.treewrap {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 20%;
  min-height: 100%;
  margin-right: $padding-lg;
  transition: width 0.2s;
  .fold {
    position: absolute;
    top: calc(50% - 30px);
    right: -15px;
    z-index: 2;
    width: 15px;
    height: 75px;
    padding: 0;
    border-radius: 0 10px 10px 0;
  }
  :global(.ant-tree) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  :global(.ant-card-body) {
    background: $white;
  }
}
.collapse {
  width: 0;
  :global(.ant-card-body) {
    background: transparent;
    :global(.ant-empty) {
      display: none;
    }
  }
}
.table-modal {
  :global .ant-table-row {
    pointer-events: none;
    :global .ant-table-selection-column {
      &::before {
        display: none;
      }
      :global .ant-checkbox {
        pointer-events: auto;
      }
    }
  }
  :global .ant-form-item-children {
    :global .ant-space-item:nth-child(2) {
      // display: none;
    }
  }
}
</style>
