<template>
  <div :class="prefixCls" :style="{ width: `${props.width}px` }">
    <a-tabs v-model:activeKey="configActiveName">
      <a-tab-pane :tab="data.wfNodeName" key="1">
        <!-- 开始节点 -->
        <start-event-option ref="startRef" :element="data.currentWfNode" :schemeCode="props.schemeCode"
          :pageView="props.pageView" :pageType="props.pageType"
          :class="data.currentWfNode.type=='bpmn:StartEvent' ? '' : 'hidden'"></start-event-option>
        <!-- 审核节点 -->
        <user-task-option ref="taskRef" :element="data.currentWfNode" :schemeCode="props.schemeCode"
          :pageView="props.pageView" :pageType="props.pageType"
          :class="data.currentWfNode.type=='bpmn:Task' ? '' : 'hidden'">
        </user-task-option>
        <!-- 结束节点 -->
        <end-event-option ref="endRef" :element="data.currentWfNode" :schemeCode="props.schemeCode"
          :class="data.currentWfNode.type=='bpmn:EndEvent' ? '' : 'hidden'"></end-event-option>
        <!-- 子流程 -->
        <subprocess-option ref="subprocessRef" :element="data.currentWfNode" :schemeCode="props.schemeCode"
          :pageView="props.pageView" :pageType="props.pageType"
          :class="data.currentWfNode.type=='bpmn:SubProcess' ? '' : 'hidden'"></subprocess-option>
        <!-- 排他网关 -->
        <exclusive-gateway-option ref="exclusiveGatewayRef" :element="data.currentWfNode" :schemeCode="props.schemeCode"
          :pageView="props.pageView" :pageType="props.pageType"
          :class="data.currentWfNode.type=='bpmn:ExclusiveGateway' ? '' : 'hidden'">
        </exclusive-gateway-option>
        <!-- 并行网关 -->
        <parallel-gateway-option ref="parallelGatewayRef" :element="data.currentWfNode" :schemeCode="props.schemeCode"
          :pageView="props.pageView" :pageType="props.pageType"
          :class="data.currentWfNode.type=='bpmn:ParallelGateway' ? '' : 'hidden'">
        </parallel-gateway-option>
        <!-- 包容网关 -->
        <!-- "bpmn:InclusiveGateway" -->
        <inclusive-gateway-option ref="inclusiveGatewayRef" :element="data.currentWfNode" :schemeCode="props.schemeCode"
          :pageView="props.pageView" :pageType="props.pageType"
          :class="data.currentWfNode.type=='bpmn:InclusiveGateway' ? '' : 'hidden'">
        </inclusive-gateway-option>
        <!-- 线条 -->
        <myline-option ref="mylineRef" :element="data.currentWfNode" :schemeCode="props.schemeCode"
          :pageView="props.pageView" :pageType="props.pageType" :wfData="data.wfData" :flowRef="data.flowRef"
          :class="data.currentWfNode.type=='bpmn:SequenceFlow' ? '' : 'hidden'">
        </myline-option>
      </a-tab-pane>
      <a-tab-pane tab="流程属性" key="2">
        <shcemeinfo-config ref="shcemeinfoRef" :disabled="true" :pageType="props.pageType"></shcemeinfo-config>
      </a-tab-pane>
      <a-tab-pane key="3" tab="发起权限" force-render v-if="props.pageType!='detail'">
        <auth-config ref="authRef"></auth-config>
      </a-tab-pane>

    </a-tabs>
  </div>
</template>
<script lang="ts" setup>
  import { h, reactive, onMounted, defineProps, computed, defineEmits, provide, watch, ref, inject } from 'vue';
  import { SaveOutlined, ZoomOutOutlined, ZoomInOutlined, RotateLeftOutlined, RotateRightOutlined, ClearOutlined } from '@ant-design/icons-vue';
  import { Tabs } from 'ant-design-vue';
  import { PageWrapper } from '@/components/Page';
  import { useDesign } from '@/hooks/web/useDesign';
  import { lr_AESEncrypt } from '../utils.ts'
  const { prefixCls } = useDesign('process-property');
  import { useMessage } from '@/hooks/web/useMessage';
  const { createConfirm, createMessage } = useMessage();
  import { getDetail } from '@/api/sys/WFSchemeInfo'

  // 流程属性
  import shcemeinfoConfig from './shcemeInfo/index.vue'
  // 发起权限
  import authConfig from './auth/index.vue'
  // 开始节点
  import StartEventOption from './startEvent/index.vue'
  // 审核节点
  import userTaskOption from './userTask/index.vue'
  // 结束节点
  import endEventOption from './endEvent/index.vue'
  // 并行网关
  import parallelGatewayOption from './parallelGateway/index.vue'
  // 排他网关
  import exclusiveGatewayOption from './exclusiveGateway/index.vue'
  // 包容网关
  import inclusiveGatewayOption from './inclusiveGateway/index.vue'
  // 网关Xor
  import gatewayXorOption from './config/gatewayXor.vue'
  // 脚本任务
  import scriptTaskOption from './config/scriptTask.vue'
  // 子流程
  import subprocessOption from './subprocess/index.vue'
  // 线
  import mylineOption from './myline/index.vue'
  /**
   * 侧边栏
   * @Author MiyueFE
   * @Home https://github.com/miyuesc
   * @Date 2021年3月31日18:57:51
   */
  const props = defineProps({
    bpmnModeler: Object,
    prefix: {
      type: String,
      default: "camunda"
    },
    width: {
      type: Number,
      default: 520
    },
    element: Object,
    schemeCode: String,
    pageType: String,
    pageView: String,

  })

  const startRef = ref < any > ()
  const shcemeinfoRef = ref < any > ()
  const authRef = ref < any > ()
  const taskRef = ref < any > ()
  const endRef = ref < any > ()
  const subprocessRef = ref < any > ()
  const exclusiveGatewayRef = ref < any > ()
  const parallelGatewayRef = ref < any > ()
  const inclusiveGatewayRef = ref < any > ()
  const configActiveName = ref('2')
  const data = reactive({
    currentWfNode: undefined,
    wfNodeName: "",
    wfData: [],
    flowRef: {}
  })
  watch(
    () => props.element,
    (newVal, oldVal) => {
      console.log(newVal)
      var typeName = newVal.type.replace('bpmn:', '')
      if (newVal.type == "bpmn:Process") {
        data.currentWfNode = {
          type: newVal.type
        }
        configActiveName.value = '2'
      } else {
        data.currentWfNode = newVal
        configActiveName.value = '1'
        switch (typeName) {
          case 'StartEvent':
            data.wfNodeName = "开始节点"
            data.currentWfNode = {
              id: newVal.id,
              type: newVal.type
            }
            break;
          case 'EndEvent':
            data.wfNodeName = "结束节点"
            data.currentWfNode = {
              id: newVal.id,
              type: newVal.type
            }
            break;
          case 'Task':
            data.wfNodeName = "审核节点"
            data.currentWfNode = {
              id: newVal.id,
              type: newVal.type
            }
            break;
          case 'SubProcess':
            data.wfNodeName = "子流程"
            data.currentWfNode = {
              id: newVal.id,
              type: newVal.type
            }
            break;
          case 'ExclusiveGateway':
            data.wfNodeName = "排他网关"
            data.currentWfNode = {
              id: newVal.id,
              type: newVal.type
            }
            break;
          case 'ParallelGateway':
            data.wfNodeName = "并行网关"
            data.currentWfNode = {
              id: newVal.id,
              type: newVal.type
            }
            break;
          case 'InclusiveGateway':
            data.wfNodeName = "包含网关"
            data.currentWfNode = {
              id: newVal.id,
              type: newVal.type
            }
            break;
          case 'SequenceFlow':
            data.wfNodeName = "线条"
            data.currentWfNode = {
              id: newVal.id,
              type: newVal.type
            }
            // 获取线条两头的节点id
            data.flowRef = {
              from: newVal.businessObject.sourceRef.id,
              to: newVal.businessObject.targetRef.id,
            }
            // 获取排他网关和审核节点的数据，为选择流转条件使用
            getWfData()
            break;

          default:
            break;
        }
      }
    }
  )
  const detailInfo = reactive({
    schemeInfo: {},
    startInfor: {},
    endInfo: {},
    authInfo: {},
    subprocessInfo: {},
    taskInfo: {},
  })
  async function getDetailInfo() {
    let data = await getDetail({ code: props.schemeCode })
    let scheme = JSON.parse(data.scheme.content);
    let baseinfo = {
      id: data.schemeinfo.id,
      code: data.schemeinfo.code,
      name: data.schemeinfo.name,
      category: data.schemeinfo.category,
      enabledMark: data.schemeinfo.enabledMark,
      mark: data.schemeinfo.mark,
      isInApp: data.schemeinfo.isInApp,
      description: data.schemeinfo.description,
      icon: data.schemeinfo.icon,
      color: data.schemeinfo.color,
      schemeId: data.schemeinfo.schemeId,

      undoType: scheme.undoType,
      undoDbCode: scheme.undoDbCode,
      undoDbSQL: scheme.undoDbSQL,
      undoIOCName: scheme.undoIOCName,
      undoUrl: scheme.undoUrl,

      deleteType: scheme.deleteType,
      deleteDbCode: scheme.deleteDbCode,
      deleteDbSQL: scheme.deleteDbSQL,
      deleteIOCName: scheme.deleteIOCName,
      deleteUrl: scheme.deleteUrl,


      deleteDraftType: scheme.deleteDraftType,
      deleteDraftDbCode: scheme.deleteDraftDbCode,
      deleteDraftDbSQL: scheme.deleteDraftDbSQL,
      deleteDraftIOCName: scheme.deleteDraftIOCName,
      deleteDraftUrl: scheme.deleteDraftUrl
    };

    let wfData = scheme.wfData
    let auth = {
      authType: data.schemeinfo.authType,
      authData: data.schemeAuthList.map(t => {
        return {
          id: t.objId,
          name: t.objName,
          type: t.objType
        }
      })
    }
    shcemeinfoRef.value.setForm(baseinfo)
    authRef.value.setForm(auth)
  }

  function scriptTaskNodeInit(node) {
    node.executeType = '1'
    node.sqlDb = ''
    node.sqlStr = ''
    node.sqlStrRevoke = ''
    node.apiUrl = ''
    node.apiUrlRevoke = ''
    node.ioc = ''
    node.iocRevoke = ''

  }
  function mylineNodeInit(node) {
    const wfdata = this.handleGetWFData();
    const fromNode = wfdata.find(t => t.id == node.from)
    node.lineConditions = ''
    if (fromNode.type == 'userTask') {
      if (fromNode.btnlist.findIndex(t => t.code == 'agree' && !t.hidden) != -1) {
        node.lineConditions = 'agree' // 流转条件
      }
    }
  }
  async function getWfData() {
    let wfData = []
    // 排他网关exclusiveGatewayRef
    // 审核节点taskRef
    let taskFrom = await !(taskRef.value) ? {} : taskRef.value.getForm();
    let gatewayInclusiveFrom = await !(exclusiveGatewayRef.value) ? {} : exclusiveGatewayRef.value.getForm();
    if (gatewayInclusiveFrom != undefined) {
      wfData.push(gatewayInclusiveFrom)
    }
    if (taskFrom != undefined) {
      wfData.push(taskFrom)
    }
    // 3.流程节点信息
    wfData.forEach(node => {
      if (node.type == 'myline' && !node.isInit) {
        node.isInit = true
        node.lineConditions = ''
        const fromNode = this.wfData.find(t => t.id == node.from)
        if (fromNode.type == 'userTask') {
          if (fromNode.btnlist.findIndex(t => t.code == 'agree' && !t.hidden) != -1) {
            node.lineConditions = 'agree' // 流转条件
          }
        }
      }
    });
    data.wfData = wfData

  }
  async function validatePanel() {
    let res = await shcemeinfoRef.value.validateForm();
    return res
  }
  async function getPanel() {
    // 1.获取流程配置基础属性
    let baseinfo = await shcemeinfoRef.value.getForm();
    // 2.获取流程权限信息
    let auth = await authRef.value.getForm();
    if (startRef.value == undefined) {
      return createMessage.warn('请设置开始节点');
    }
    if (endRef.value == undefined) {
      return createMessage.warn('请设置结束节点');
    }
    let startFrom = await startRef.value.getForm();
    let endFrom = await endRef.value.getForm();
    if (endFrom.id == '') {
      return createMessage.warn('请设置结束节点');
    }
    let wfData = []
    wfData.push(startFrom)
    wfData.push(endFrom)
    // 审核节点
    let taskFrom = await !(taskRef.value) ? {} : taskRef.value.getForm();
    if (taskFrom != undefined) {
      if (taskFrom.id != '') {
        wfData.push(taskFrom)
      }
    }
    // 子流程
    let subprocessFrom = await !(subprocessRef.value) ? {} : subprocessRef.value.getForm();
    if (subprocessFrom != undefined) {
      if (subprocessFrom.id != '') {
        wfData.push(subprocessFrom)
      }
    }
    // 排他网关
    let gatewayInclusiveFrom = await !(exclusiveGatewayRef.value) ? {} : exclusiveGatewayRef.value.getForm();
    if (gatewayInclusiveFrom != undefined) {
      if (gatewayInclusiveFrom.id != '') {
        wfData.push(gatewayInclusiveFrom)
      }
    }
    // 并排网关
    let parallelGatewayFrom = await !(parallelGatewayRef.value) ? {} : parallelGatewayRef.value.getForm();
    if (parallelGatewayFrom != undefined) {
      if (parallelGatewayFrom.id != '') {
        wfData.push(parallelGatewayFrom)
      }
    }
    // 包含网关
    let inclusiveGatewayFrom = await !(inclusiveGatewayRef.value) ? {} : inclusiveGatewayRef.value.getForm();
    if (inclusiveGatewayFrom != undefined) {
      if(inclusiveGatewayFrom.id != ''){
        wfData.push(inclusiveGatewayFrom)
      }
    }
    console.log(wfData)
    // 3.流程节点信息
    wfData.forEach(node => {
      if (node.type == 'myline' && !node.isInit) {
        node.isInit = true
        node.lineConditions = ''
        const fromNode = wfData.find(t => t.id == node.from)
        if (fromNode.type == 'userTask') {
          if (fromNode.btnlist.findIndex(t => t.code == 'agree' && !t.hidden) != -1) {
            node.lineConditions = 'agree' // 流转条件
          }
        }
      }
    });

    let scheme = {
      wfData: wfData,

      undoType: baseinfo.undoType,
      undoDbCode: baseinfo.undoDbCode,
      undoDbSQL: baseinfo.undoDbSQL,
      undoIOCName: baseinfo.undoIOCName,
      undoUrl: baseinfo.undoUrl,

      deleteType: baseinfo.deleteType,
      deleteDbCode: baseinfo.deleteDbCode,
      deleteDbSQL: baseinfo.deleteDbSQL,
      deleteIOCName: baseinfo.deleteIOCName,
      deleteUrl: baseinfo.deleteUrl,


      deleteDraftType: baseinfo.deleteDraftType,
      deleteDraftDbCode: baseinfo.deleteDraftDbCode,
      deleteDraftDbSQL: baseinfo.deleteDraftDbSQL,
      deleteDraftIOCName: baseinfo.deleteDraftIOCName,
      deleteDraftUrl: baseinfo.deleteDraftUrl,

    };
    let dto = {
      schemeinfo: {
        id: baseinfo.id,
        code: baseinfo.code,
        name: baseinfo.name,
        category: baseinfo.category,
        enabledMark: baseinfo.enabledMark,
        mark: baseinfo.mark,
        isInApp: baseinfo.isInApp,
        authType: auth.authType,
        description: baseinfo.description,
        icon: baseinfo.icon,
        color: baseinfo.color,
        schemeId: baseinfo.schemeId,
      },
      schemeAuthList: auth.authType == 1 ? [] : auth.authData.map(t => {
        return {
          objId: t.id,
          objName: t.name,
          objType: t.type
        };
      }),
      scheme: {
        content: lr_AESEncrypt(JSON.stringify(scheme), "learun")
      }
    }
    console.log(dto)
    return dto
  }
  defineExpose({
    getPanel,
    validatePanel
  })
  onMounted(() => {
    if (props.schemeCode) {
      getDetailInfo()
    }
    if (props.pageType == 'detail') {
      var content = JSON.parse(props.pageView)
      shcemeinfoRef.value.setForm(content)
    }
  })

</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-process-property';

  .@{prefix-cls} {
    background-color: @component-background;
  }

  ::v-deep .ant-tabs {
    height: 100%;
    width: 100%;
    padding: 0 20px;

  }

  ::v-deep .ant-tabs-content-holder {
    overflow-y: auto;
  }

  .hidden {
    display: none;
  }
</style>