import cloneDeep from 'lodash.clonedeep'
import { Modal, message } from 'ant-design-vue'
import FlowService from '@/webflow/flow-service'

// 从审批意见记录中获取所有环节名称（含子流程）
function getNodesStepName(nodes) {
  let arrName = []
  nodes.forEach((node) => {
    arrName.push(node.stepName)
    if (node.subFlowLogInfo?.[0]) {
      arrName = arrName.concat(getNodesStepName(node.subFlowLogInfo))
    }
  })
  // 去重
  const set = new Set(arrName)
  return Array.from(set)
}
// 审批意见记录按钮环节名称过滤
function filterOpinionsByName(logs, names) {
  for (let i = logs.length - 1; i > -1; i--) {
    const log = logs[i]
    // 有子节点，先检查子节点
    if (log.subFlowLogInfo?.[0]) {
      log.subFlowLogInfo = filterOpinionsByName(log.subFlowLogInfo, names)
      // 子节点为空，删除属性
      if (log.subFlowLogInfo.length === 0) {
        delete log.subFlowLogInfo
      }
    }
    // 当前环节不匹配 且 没有子节点
    if (names.findIndex((n) => n === log.stepName) === -1 && !log.subFlowLogInfo?.[0]) {
      logs.splice(i, 1)
    }
  }
  return logs
}

// 审批意见
const opinionColumns = [
  {
    title: '处理人',
    dataIndex: 'operator',
    scopedSlots: { customRender: 'operator' },
  },
  {
    title: '意见信息',
    scopedSlots: { customRender: 'opinion' },
    width: '35%',
  },

  {
    title: '处理环节',
    dataIndex: 'stepName',
  },
  {
    title: '处理时间',
    dataIndex: 'finishDate',
    scopedSlots: { customRender: 'finishDate' },
    sorter: (a, b) => a.finishDate - b.finishDate,
    width: '20%',
  },
]
const SdOpinionLogMixins = {
  props: {
    dataSource: {
      type: Array,
      default: undefined,
    },
    filterSteps: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      optionRecode: null, // 意见信息
      showOption: false,
      loading: true,
      editRowKey: '',
      selectedSteps: [],
      logExpandedRowKeys: [],
    }
  },
  inject: {
    webflow: { default: () => {} },
  },
  computed: {
    showColumns() {
      const addColumns = {
        title: '',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
        align: 'left',
      }
      // 判断是否已经存在action字段
      // @ts-ignore
      const columnsFlag = opinionColumns.some(function(item, index) {
        return item.dataIndex === 'action'
      })
      if (!columnsFlag) {
        opinionColumns.splice(3, 0, addColumns)
      }
      return opinionColumns
    },
    _dataSource() {
      let myresult = cloneDeep(this.dataSource || this.webflow.opinionInfo)
      // 设置各项唯一key 和自动展开项 合并  subFlowActiveLogInfos 到 subFlowLogInfo
      myresult = this.setLogDispIndex(myresult, 0)
      // 处理人员会签记录  本流程不显示，子流程提升一级显示
      myresult = this.resetLoginfo(myresult)
      return myresult
    },
    dataView() {
      if (this.selectedSteps.length > 0) {
        const stepNames = this.selectedSteps.map((item) => item.name)
        return filterOpinionsByName(cloneDeep(this._dataSource), stepNames)
      }
      return this._dataSource
    },
    hasChildren() {
      // @ts-ignore
      return (this.dataView || []).findIndex((item) => item.subFlowLogInfo?.length) !== -1
    },
    stepOptions() {
      return (getNodesStepName(this._dataSource) || []).map((name, i) => ({
        id: i.toString(),
        name,
        title: name,
      }))
    },
  },
  watch: {
    _dataSource(newVal) {
      this.setDefaultExpandNode(newVal)
    },
  },
  mounted() {
    this.webflow.getLog('process').then(() => {
      this.loading = false
      this.setDefaultExpandNode(this._dataSource)
    })
  },
  methods: {
    getRowKey(record, index) {
      return `${record.instId}_${index}`
    },
    // 删除一条会签意见
    deleteSign(recode) {
      const opinionType = recode.actionId === 'handover' ? 1 : 0
      Modal.confirm({
        title: '您确定删除这项内容吗？',
        content: '删除这条数据后，将无法恢复到初始状态，请确认？',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          FlowService.delAttOpinion(recode.props.opinionId, opinionType)
            .then((res) => {
              if (res) {
                this.webflow.updateFlow()
              }
            })
            .catch((error) => {
              message.error({ content: '审批记录删除失败：' + error })
            })
          setTimeout(() => {}, 500)
        },
      })
    },
    // 处理人员会签记录  本流程不显示，子流程提升一级显示(一步签)
    resetLoginfo(loginfo) {
      const needUplist = []
      // @ts-ignore
      loginfo.forEach((element, index) => {
        if (element.subFlowLogInfo) {
          // 人员签(isFromUserCountersign=true，处理中的直接在当前记录中，处理完成的在子流程的流转记录中) 且 只有1条流转记录（流程结束的记录已经被过滤掉了）
          const isPsnHQ =
            element.subFlowLogInfo.length === 1 &&
            (element.operatorAttrs?.isFromUserCountersign === 'true' ||
              element.subFlowLogInfo[0].operatorAttrs?.isFromUserCountersign === 'true')
          if (isPsnHQ) {
            // 重置排序号、处理环节名称
            Object.assign(element.subFlowLogInfo[0], {
              dispindex: element.dispindex,
              stepName: element.stepName,
              actionName: element.actionName,
            })
            needUplist.push(element.subFlowLogInfo[0])
            element.subFlowLogInfo = null
            // 此条主记录不再显示
            element.delete = 1
          } else {
            element.subFlowLogInfo = this.resetLoginfo(element.subFlowLogInfo)
          }
        }
      })
      loginfo = loginfo.concat(needUplist).filter((item) => {
        return item.delete !== 1
      })
      loginfo = loginfo.sort((a, b) => {
        const value1 = a.dispindex.split('-')
        const value2 = b.dispindex.split('-')
        return Number(value1[value1.length - 1]) - Number(value2[value2.length - 1])
      })
      return loginfo
    },
    setLogDispIndex(loginfo, preindex) {
      loginfo.forEach((element, index) => {
        element.dispindex = preindex + '-' + index
        if (element.subFlowActiveLogInfos && element.subFlowActiveLogInfos.length) {
          if (!element.subFlowLogInfo) {
            element.subFlowLogInfo = []
          }
          element.subFlowLogInfo = element.subFlowLogInfo.concat(element.subFlowActiveLogInfos)
          element.subFlowActiveLogInfos = null
        }
        if (element.subFlowLogInfo) {
          if (element.subFlowLogInfo.length > 0) {
            element.subFlowLogInfo = this.setLogDispIndex(element.subFlowLogInfo, element.dispindex)
          } else {
            element.subFlowLogInfo = null
          }
        }
      })
      return loginfo
    },
    // 设置默认展开的节点
    setDefaultExpandNode(logInfos) {
      logInfos.forEach((item) => {
        // 有子节点
        if (item.subFlowLogInfo?.[0]) {
          if (this.logExpandedRowKeys.indexOf(item.dispindex) === -1) {
            this.logExpandedRowKeys.push(item.dispindex)
          }
          this.setDefaultExpandNode(item.subFlowLogInfo)
        }
      })
    },
    // @ts-ignore
    openModal(text, recode, index) {
      const opinionParams = {
        opinionType: recode.actionId === 'handover' ? 1 : 0,
        opinionId: recode.props.opinionId,
      }
      this.editRowKey = this.getRowKey(recode, index)
      if (!recode.processLogAttachments || recode.processLogAttachments.length === 0) {
        // 当前对象添加附件的groupId
        FlowService.getAttOpinion(opinionParams).then((res) => {
          const randomNum = this.generate()
          recode.processLogAttachments = [
            {
              groupCode:
                res.data.content.attrs !== null ? res.data.content.attrs.attachment : randomNum,
            },
          ]
          recode = { ...recode }
          this.optionRecode = recode
          this.showOption = true
        })
      } else {
        this.optionRecode = recode
        this.showOption = true
      }
    },
    // 生产16位随机数,以1开头的
    generate() {
      for (var j = 0; j < 10; j++) {
        var randStr = ''
        // 此处的12为生成12位数字，可随即更改
        for (var i = 0; i < 15; i++) {
          var randItem = Math.floor(Math.random() * 10)
          randStr += randItem
        }
        var value = 1 + randStr // 此处的1是要求必须已1开头，如果不需要可以去掉并在for循环中填入您要的位数
        return value
      }
    },
    // 修改审批意见（更新意见附件）：刷新附件列表
    attachmentChange() {
      this.$refs[`${this.editRowKey}_attach`]?.updateFileList()
    },
    // 提交成功后回调
    signStatusVerdict(data) {
      if (data) {
        this.webflow.updateFlow()
      }
      this.$nextTick(() => {
        this.showOption = data.isOptionShow
      })
    },
    optionCancle(data) {
      this.showOption = data
    },
  },
}
export default SdOpinionLogMixins
