<template>
  <div :class="prefixCls" style="width: 30%">
    <a-tabs v-model:activeKey="configActiveName">
      <a-tab-pane :tab="data.wfNodeName" key="1">
        <!-- 开始节点 -->
        <start-event-option
          ref="startRef"
          :element="data.currentWfNode"
          :pageType="props.pageType"
          :schemeCode="props.schemeCode"
          :class="data.currentWfNode.type == 'bpmn:StartEvent' ? '' : 'hidden'"
        />
        <!-- 审核节点 -->
        <user-task-option
          ref="taskRef"
          :element="data.currentWfNode"
          :pageType="props.pageType"
          :class="data.currentWfNode.type == 'bpmn:Task' ? '' : 'hidden'"
        />
        <!-- 结束节点 -->
        <end-event-option
          ref="endRef"
          :element="data.currentWfNode"
          :pageType="props.pageType"
          :class="data.currentWfNode.type == 'bpmn:EndEvent' ? '' : 'hidden'"
        />
        <!-- 子流程 -->
        <subprocess-option
          ref="subprocessRef"
          :element="data.currentWfNode"
          :pageType="props.pageType"
          :class="data.currentWfNode.type == 'bpmn:SubProcess' ? '' : 'hidden'"
        />
        <!-- 排他网关 -->
        <exclusive-gateway-option
          ref="exclusiveGatewayRef"
          :element="data.currentWfNode"
          :pageType="props.pageType"
          :class="data.currentWfNode.type == 'bpmn:ExclusiveGateway' ? '' : 'hidden'"
        />
        <!-- 并行网关 -->
        <parallel-gateway-option
          ref="parallelGatewayRef"
          :element="data.currentWfNode"
          :pageType="props.pageType"
          :class="data.currentWfNode.type == 'bpmn:ParallelGateway' ? '' : 'hidden'"
        />
        <!-- 包容网关 -->
        <!-- "bpmn:InclusiveGateway" -->
        <inclusive-gateway-option
          ref="inclusiveGatewayRef"
          :element="data.currentWfNode"
          :pageType="props.pageType"
          :class="data.currentWfNode.type == 'bpmn:InclusiveGateway' ? '' : 'hidden'"
        />
        <!-- 线条 -->
        <myline-option
          ref="mylineRef"
          :element="data.currentWfNode"
          :pageType="props.pageType"
          :class="data.currentWfNode.type == 'bpmn:SequenceFlow' ? '' : 'hidden'"
        />
        <!-- 脚本节点 -->
        <script-option
          ref="scriptRef"
          :element="data.currentWfNode"
          :pageType="props.pageType"
          :class="data.currentWfNode.type == 'bpmn:ScriptTask' ? '' : 'hidden'"
        />
      </a-tab-pane>
      <a-tab-pane tab="流程属性" key="2">
        <shcemeinfo-config ref="shcemeinfoRef" :disabled="true" :pageType="props.pageType" />
      </a-tab-pane>
      <a-tab-pane key="3" tab="发起权限" force-render v-if="props.pageType != 'detail'">
        <auth-config ref="authRef" />
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, onMounted, defineProps, watch, ref } from 'vue';
  import { useDesign } from '@/hooks/web/useDesign';
  import { lr_AESEncrypt } from '../utils';
  import { useMessage } from '@/hooks/web/useMessage';
  import { getDetail } from '@/api/sys/WFSchemeInfo';
  // 流程属性
  // 发起权限
  // 开始节点
  // 审核节点
  // 结束节点
  // 并行网关
  // 排他网关
  // 包容网关
  // 子流程
  // 线
  import {
    shcemeinfoConfig,
    authConfig,
    StartEventOption,
    userTaskOption,
    endEventOption,
    parallelGatewayOption,
    exclusiveGatewayOption,
    inclusiveGatewayOption,
    subprocessOption,
    mylineOption,
    scriptOption,
  } from './page';
  import { flowStore } from '@/store/modules/flow';

  const flowWfDataStore = flowStore();
  const { prefixCls } = useDesign('process-property');
  const { createMessage } = useMessage();
  const props = defineProps({
    bpmnModeler: Object,
    prefix: {
      type: String,
      default: 'camunda',
    },
    width: {
      type: Number,
      default: 520,
    },
    element: Object,
    schemeCode: String,
    pageType: String,
    pageView: String,
  });
  watch(
    () => props.pageView,
    (newVal) => {
      var content = JSON.parse(newVal);
      shcemeinfoRef.value.setForm(content);
      flowWfDataStore.setWfDataAll(content.wfData);
    },
  );
  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');
  interface dataType {
    currentWfNode: any;
    wfNodeName: string;
    wfData: any;
    activeTab: string;
    elementId: string;
    elementType: string;
    elementBusinessObject: any; // 元素 businessObject 镜像，提供给需要做判断的组件使用
    conditionFormVisible: boolean; // 流转条件设置
    formVisible: boolean; // 表单配置
  }
  const data: dataType = reactive({
    currentWfNode: undefined,
    wfNodeName: '',
    wfData: [],
    activeTab: 'base',
    elementId: '',
    elementType: '',
    elementBusinessObject: {}, // 元素 businessObject 镜像，提供给需要做判断的组件使用
    conditionFormVisible: false, // 流转条件设置
    formVisible: false, // 表单配置
  });
  function initModels() {
    setTimeout(() => {
      getActiveElement();
    }, 10);
  }
  function getActiveElement() {
    // 初始第一个选中元素 bpmn:Process
    initFormOnChanged(null);
    props.bpmnModeler.on('import.done', (e) => {
      initFormOnChanged(null);
    });
    // 监听选择事件，修改当前激活的元素以及表单
    props.bpmnModeler.on('selection.changed', ({ newSelection }) => {
      initFormOnChanged(newSelection[0] || null);
    });
    props.bpmnModeler.on('element.changed', ({ element }) => {
      // 保证 修改 "默认流转路径" 类似需要修改多个元素的事件发生的时候，更新表单的元素与原选中元素不一致。
      if (element && element.id === data.elementId) {
        initFormOnChanged(element);
      }
    });
  }
  // 初始化数据
  function initFormOnChanged(element) {
    if (element == null) {
      configActiveName.value = '2';
      data.wfNodeName = '';
      data.currentWfNode = {
        type: '',
      };
      return;
    }
    if (element.type == 'bpmn:Process') {
      data.currentWfNode = {
        type: element.type,
      };
      configActiveName.value = '2';
    } else {
      data.currentWfNode = element;
      configActiveName.value = '1';
      setNodeData(element.type, element);
    }
  }
  // 设置节点初始数据
  function setNodeData(name, element) {
    switch (name) {
      case 'bpmn:StartEvent':
        data.wfNodeName = '开始节点';
        data.currentWfNode = {
          id: element.id,
          type: element.type,
          isNextAuditor: false,
          isCustmerTitle: false,
          formRelations: [],
          formType: '1',
          formCode: '',
          formVerison: undefined,
          formRelationId: undefined,
          formUrl: '',
          formAppUrl: '',
          authFields: [],
          messageType: '',
          isInit: true,
          formTitle: '',
          issueCode: '',
          mapConfig:{},
        };
        break;
      case 'bpmn:EndEvent':
        data.wfNodeName = '结束节点';
        data.currentWfNode = {
          id: element.id,
          type: element.type,
        };
        break;
      case 'bpmn:Task':
        data.wfNodeName = '审核节点';
        data.currentWfNode = {
          id: element.id,
          type: element.type,
          isAddSign: false,
          isTransfer: false,
          isBatchAudit: false,
          IsSingleTask: false,
          autoAgree: '',
          noAuditor: '1',
          rejectType: '1',
          messageType: '',
          auditUsers: [],
          lookUsers: [],
          formRelations: [],
          formType: '1',
          formCode: '',
          formTitle: '',
          formVerison: undefined,
          formRelationId: undefined,
          formUrl: '',
          formAppUrl: '',
          authFields: [],
          name: '审核节点',
          btnlist: [
            {
              code: 'agree',
              name: '同意',
              hidden: false,
              isNextAuditor: false,
              isSign: false,
              isSys: true,
            },
            {
              code: 'disagree',
              name: '驳回',
              hidden: false,
              isNextAuditor: false,
              isSign: false,
              isSys: true,
            },
          ],
          isCountersign: false,
          isCountersignAll: false,
          countersignAgian: '1',
          countersignType: '1',
          countersignAllType: 100,
          isOvertimeMessage: false,
          overtimeMessageType: '',
          overtimeMessageStart: 1,
          overtimeMessageInterval: 1,
          overtimeGo: 12,
          isInherit: true,
          isInit: true,
          issueCode: '',
        };
        break;
      case 'bpmn:SubProcess':
        data.wfNodeName = '子流程';
        data.currentWfNode = {
          id: element.id,
          type: element.type,
          isAsync: false,
          wfschemeId: '',
          wfVersionId: '',
          isInit: true,
        };
        break;
      case 'bpmn:ExclusiveGateway':
        data.wfNodeName = '排他网关';
        data.currentWfNode = {
          id: element.id,
          type: element.type,
          conditions: [],
          isInit: true,
        };
        break;
      case 'bpmn:ParallelGateway':
        data.wfNodeName = '并行网关';
        data.currentWfNode = {
          id: element.id,
          type: element.type,
          isInit: true,
        };
        break;
      case 'bpmn:InclusiveGateway':
        data.wfNodeName = '包含网关';
        data.currentWfNode = {
          id: element.id,
          type: element.type,
          conditions: [],
          isInit: true,
        };
        break;
      case 'bpmn:SequenceFlow':
        data.wfNodeName = '线条';
        data.currentWfNode = {
          id: element.id,
          type: element.type,
          lineConditions: '',
          from: element.businessObject.sourceRef.id,
          isInit: true,
          to: element.businessObject.targetRef.id,
        };
        break;
      case 'bpmn:ScriptTask':
        data.wfNodeName = '脚本节点';
        data.currentWfNode = {
          id: element.id,
          type: element.type,
          isInit: true,
          executeType: '1',
          sqlDb: '',
          sqlStr: '',
          sqlStrRevoke: '',
          apiUrl: '',
          apiUrlRevoke: '',
          ioc: '',
          iocRevoke: '',
        };
        break;
      default:
        break;
    }
    // 更改flowStore的数据
    flowWfDataStore.setWfDataNode(data.currentWfNode);
  }

  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;
    flowWfDataStore.setWfDataAll(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);
  }

  async function validatePanel() {
    let res = await shcemeinfoRef.value.validateForm();
    if (!res) {
      configActiveName.value = '2';
    }
    return res;
  }
  async function getPanel() {
    // 1.获取流程配置基础属性
    let baseinfo = await shcemeinfoRef.value.getForm();
    // 2.获取流程权限信息
    let auth = await authRef.value.getForm();
    let wfData = flowWfDataStore.getWfData;
    var startIndex = (wfData || []).findIndex(
      (element: { type?: string }) => element.type == 'bpmn:StartEvent',
    );
    if (startIndex == -1) {
      return createMessage.warn('请设置开始节点');
    }
    var endIndex = (wfData || []).findIndex(
      (element: { type?: string }) => element.type == 'bpmn:EndEvent',
    );
    if (endIndex == -1) {
      return createMessage.warn('请设置结束节点');
    }
    wfData.forEach(
      (node: {
        type?: string;
        lineConditions?: string;
        from?: string;
        messageType?: any;
        overtimeMessageType?: any;
      }) => {
        if (node.type == 'bpmn:SequenceFlow') {
          if (node.lineConditions == '') {
            const fromNode:
              | {
                  type?: string;
                  btnlist?: any;
                }
              | any = wfData.find((t: { id: string }) => t.id === node.from);
            if (fromNode.type == 'bpmn:Task') {
              if (fromNode.btnlist.findIndex((t) => t.code == 'agree' && !t.hidden) != -1) {
                node.lineConditions = 'agree'; // 流转条件
              }
            }
          }
        }
        if (node.type == 'bpmn:StartEvent') {
          if (node.messageType instanceof Array) {
            if (node.messageType.length == 1) {
              node.messageType = node.messageType[0];
            } else {
              node.messageType = node.messageType.join(',');
            }
          }
        }
        if (node.type == 'bpmn:Task') {
          if (node.overtimeMessageType instanceof Array) {
            if (node.overtimeMessageType.length == 1) {
              node.overtimeMessageType = node.overtimeMessageType[0];
            } else {
              node.overtimeMessageType = node.overtimeMessageType.join(',');
            }
          }
          if (node.messageType instanceof Array) {
            if (node.messageType.length == 1) {
              node.messageType = node.messageType[0];
            } else {
              node.messageType = node.messageType.join(',');
            }
          }
        }
      },
    );

    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), 'hc'),
      },
      // scheme:scheme
    };
    console.log(dto);
    return dto;
  }
  defineExpose({
    getPanel,
    validatePanel,
  });
  onMounted(() => {
    initModels();
    if (props.schemeCode) {
      getDetailInfo();
    }
    if (props.pageType == 'detail') {
      var content = JSON.parse(props.pageView);
      shcemeinfoRef.value.setForm(content);
      flowWfDataStore.setWfDataAll(content.wfData);
    }
  });
</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;
    padding-right: 10px;
  }

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