<script setup lang="ts" name="Setting">
import { ElLoading, ElMessage } from 'element-plus'
import { defineExpose, nextTick, onMounted, ref } from 'vue'
import useWorkFlowStore from '@/store/modules/workFlow'
import errorDialog from '@/components/dialog/errorDialog.vue'
import approverDrawer from '@/components/drawer/approverDrawer.vue'
import copyerDrawer from '@/components/drawer/copyerDrawer.vue'
import conditionDrawer from '@/components/drawer/conditionDrawer.vue'
import { addProcess, editProcess, getDirectorLevel, getProcessDetail } from '@/api/system/process'
import userStore from '@/store/modules/user'
import type { ITipList, IworkFlowDef } from '@/views/system/process/process'
const props = defineProps({
  allowEditNode: {
    type: Boolean,
    default: true,
  },
  getRowData: {
    type: Object,
    default: () => {},
  },
  selectFormId: String,
  isAddProcess: {
    type: Boolean,
    default: false,
  },
})
const emits = defineEmits(['createProcessSuccess', 'notice'])
const processConfig = ref({}) as any

const user = userStore()
const workFlowStore = useWorkFlowStore()
const tipList = ref<ITipList[]>([]) // 统计空节点的数组
const tipVisible = ref(false) // 控制提示空节点对话框显隐
const nowVal = ref(100)
const nodeConfig = ref({})
const workFlowDef = ref<IworkFlowDef>({
  name: '审批流程',
})
const flowPermission = ref([])
const directorMaxLevel = ref(0)

// 初始化--请求流程图详细信息
const initDetail = async (formid: string) => {
  const res = await getProcessDetail(formid)
  return res.data
}
onMounted(async () => {
  let max = 0 // 审批主管最大层级

  // 获取此用户的审批主管的最大层级
  getDirectorLevel(user.id).then((res) => {
    max = res.data.level
  })
  window.sessionStorage.setItem('maxLevel', `${max}`)
  nextTick(async () => {
    let data
    console.log('=====', props.selectFormId)
    if (!props.isAddProcess && props.selectFormId) { // 非新建流程--调流程详情接口
      console.log('获取流程详情')
      data = await initDetail(props.selectFormId)
    }
    else { // 新建流程
      data = {
        tableId: 1,
        workFlowDef: {
          name: '审批流程',
        },
        directorMaxLevel: max,
        flowPermission: [],
        nodeConfig: {
          nodeName: '发起人',
          type: 0,
          priorityLevel: '',
          settype: '',
          selectMode: '',
          selectRange: '',
          directorLevel: '',
          examineMode: '',
          noHanderAction: '',
          examineEndDirectorLevel: '',
          ccSelfSelectFlag: '',
          conditionList: [],
          nodeUserList: [],
          conditionNodes: [],
        },
      }
    }
    processConfig.value = data // 流程设置
    const {
      nodeConfig: nodes, // 节点设置
      flowPermission: flows, // 发起人
      workFlowDef: works, // 流程基本信息
      tableId,
    } = data
    nodeConfig.value = nodes // 节点配置
    flowPermission.value = flows // 发起人
    directorMaxLevel.value = max // 用户主管最大层级数
    workFlowDef.value = works // 流程基本信息
    console.log('9090909090909090', workFlowDef.value.decisionItem)

    window.sessionStorage.setItem('decisionItem', `${workFlowDef.value.decisionItem}`)
    window.sessionStorage.setItem('noticeStarter', `${workFlowDef.value.noticeStarter}`)
    console.log('在这里获得了这条数据的可选决策项和是否通知发起人')
    emits('notice') // 通知可选决策项和是否通知发起人已获得数据
    workFlowStore.setTableId(tableId)
  })
})

// 统计空节点（红色感叹号）
const reErr = ({ childNode }: any) => {
  if (childNode) {
    const { type, error, nodeName, conditionNodes } = childNode
    if (type == 1 || type == 2) {
      if (error) {
        tipList.value.push({
          name: nodeName,
          type: ['', '审核人', '抄送人'][type],
        })
      }
      reErr(childNode)
    }
    else if (type == 3) {
      reErr(childNode)
    }
    else if (type == 4) {
      reErr(childNode)
      for (let i = 0; i < conditionNodes.length; i++) {
        if (conditionNodes[i].error) {
          tipList.value.push({ name: conditionNodes[i].nodeName, type: '条件' })
        }
        reErr(conditionNodes[i])
      }
    }
  }
  else {
    childNode = null
  }
}

// 保存流程图
const saveSet = async (type: string, getRowData: any) => {
  if (type === 'edit') { // 编辑
    console.log('000000000', getRowData)

    processConfig.value.formId = props.getRowData.formId // 已有formid
    processConfig.value.formName = getRowData.business // 表单名称、关联业务
    processConfig.value.formDesc = getRowData.formDesc // 描述
    processConfig.value.formContent = getRowData.formDesc // 描述
    processConfig.value.workFlowDef.name = getRowData.name // 流程名称
    processConfig.value.workFlowDef.flowKey = props.getRowData.flowKey
    processConfig.value.workFlowDef.directorId = props.getRowData.directorId
  }
  else { // 新建
    processConfig.value.formId = props.getRowData.formID
    processConfig.value.formName = props.getRowData.business
    processConfig.value.formDesc = props.getRowData.desc
    processConfig.value.formContent = props.getRowData.desc
    processConfig.value.workFlowDef.directorId = user.id
    processConfig.value.workFlowDef.name = props.getRowData.name // 流程名称
  }
  const decisionItem = window.sessionStorage.getItem('decisionItem')
  const noticeStarter = window.sessionStorage.getItem('noticeStarter')
  if (decisionItem) {
    processConfig.value.workFlowDef.decisionItem = parseInt(decisionItem) // 可选决策项
  }
  if (noticeStarter) {
    processConfig.value.workFlowDef.noticeStarter = parseInt(noticeStarter) // 审批结果通知发起人
  }

  // workFlowStore.setIsTried(true)
  tipList.value = []
  reErr(processConfig.value.nodeConfig) // 统计空节点
  if (tipList.value.length != 0) { // 存在空节点
    let approverCount = 0
    let conditonCount = 0
    tipList.value.forEach((item: { type: string }) => {
      if (item.type === '审核人') {
        approverCount += 1
      }
      else if (item.type === '条件') {
        conditonCount += 1
      }
    })
    workFlowStore.conditonErrorCount = conditonCount // 存入store
    workFlowStore.approverErrorCount = approverCount // 存入store
    tipVisible.value = true // 显示空节点提示框
    return
  }

  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })

  if (!props.isAddProcess) {
    processConfig.value.flowPermission = flowPermission.value // 编辑时不允许改发起人
    const res = await editProcess(processConfig.value)
    if (res.code == 200) {
      ElMessage.success('编辑流程成功')
    }
  }
  else {
    processConfig.value.flowPermission = { // 新建时发起人是此时的用户
      name: user.name, // 用户名
      targetId: user.id, // 用户id
      type: 1, // 成员
    }

    addProcess(processConfig.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success('创建流程成功')
        emits('createProcessSuccess') // 返回列表页
      }
    }).catch(() => { // 流程异常情况: 所填写的formID已经存在
      // emits('createProcessSuccess') // 返回列表页
    })
  }
  loading.close()
}
defineExpose({
  saveSet, initDetail,
})

const zoomSize = (type: number) => {
  if (type == 1) {
    if (nowVal.value == 50) {
      return
    }
    nowVal.value -= 10
  }
  else {
    if (nowVal.value == 300) {
      return
    }
    nowVal.value += 10
  }
}

// 改变空节点错误对话框显隐
const changeTipVisible = (val: boolean) => {
  tipVisible.value = false
}
</script>

<template>
  <div class="workFlow-setting">
    <div class="fd-nav-content">
      <section class="dingflow-design">
        <!-- <div class="zoom">
          <div class="zoom-out" :class="nowVal === 50 && 'disabled'" @click="zoomSize(1)" />
          <span>{{ nowVal }}%</span>
          <div class="zoom-in" :class="nowVal === 300 && 'disabled'" @click="zoomSize(2)" />
        </div> -->
        <!-- 可编辑 -->
        <div v-if="allowEditNode" class="box-scale" :style="`transform: scale(${nowVal / 100});`">
          <node-wrap v-if="props.allowEditNode" v-model:nodeConfig="nodeConfig" v-model:flowPermission="flowPermission" />
          <div class="end-node">
            <p>结束</p>
          </div>
        </div>
        <!-- 不可编辑 -->
        <div v-if="!allowEditNode" class="box-scale" :style="`transform: scale(${nowVal / 100});`">
          <node-wrap-ban :node-config="nodeConfig" :flow-permission="flowPermission" />
          <div class="end-node">
            <p>结束</p>
          </div>
        </div>
      </section>
    </div>
    <error-dialog v-model:visible="tipVisible" :list="tipList" @changeTipVisible="changeTipVisible" />
    <approver-drawer :director-max-level="directorMaxLevel" />
    <copyer-drawer />
    <condition-drawer />
  </div>
</template>

<style lang="scss" scoped>
.workFlow-setting {
  margin-top: 10px;

  .close-button {
    display: flex;
    justify-content: flex-end;
    margin: 20px;
  }

  .box-scale {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  // .end-node-circle {
  .end-node {
    justify-content: center;
    flex-direction: column;
    align-content: center;

    p {
      width: 280px;
      height: 40px;
      line-height: 40px;
      color: #fff;
      text-align: center;
      background-color: #8cafff;
      border-radius: 4px;
      font-size: 14px;
      margin: 0;
    }
  }
}

// }
</style>

<style>
@import "../css/workflow.css";

.error-modal-list {
  width: 455px;
}
</style>
