import { useBpmnStore } from '/@bpmn/store/bpmn';
import { BpmnNodeKey } from '/@/enums/workflowEnum';
import { formPermissionList } from '/@bpmn/config/formPermission';
import { InfoId, InfoItem, InfoType } from '/@/model/workflow/bpmnConfig';
import {
  ChildNodeConfig,
  ProcessConfig,
  SequenceFlowSourceConfig,
} from '/@/model/workflow/workflowConfig';
import { FormConfigItem } from '/@/model/workflow/formSetting';
import {
  processConfig,
  defaultProperties,
  propertiesByType,
  nodeNameByType,
} from './propertyConfig';
import { cloneDeep } from 'lodash-es';
import { useI18n } from '/@/hooks/web/useI18n';
const { t } = useI18n();
// 流程模板默认属性
export const getProcessConfig: ProcessConfig = processConfig;
// 根据节点类型获取节点默认属性
export const getDefaultProperties = function (type: InfoType) {
  return propertiesByType.has(type) ? propertiesByType.get(type) : defaultProperties;
};
// 根据节点类型获取节点名称
export const getNodeName = (type: InfoType) => {
  return nodeNameByType.has(type) ? nodeNameByType.get(type) : '';
};
// 根据节点类型获取节点名称加随机数
export const getLabelName = (type: InfoType) => {
  return getNodeName(type);
  // + 123;
};
// 初始化开始节点信息
export const initStartProperties = () => {
  const bpmnStore = useBpmnStore();
  initProperties(getStartNodeId, BpmnNodeKey.START, t('流程启动'), bpmnStore.processInfo.processId);
  initStartingNodeProperties(
    getUserStartTaskNodeID,
    BpmnNodeKey.USER,
    t('用户开始节点'),
    bpmnStore.processInfo.processId,
  );
  //
  initProperties(
    getStartNodeIdTouserTaskNodeID,
    BpmnNodeKey.SEQUENCEFLOW,
    t('流程线'),
    bpmnStore.processInfo.processId,
  );
};
// 修改流程属性
export const changeProcessProperties = async (processConfig: ProcessConfig) => {
  const bpmnStore = useBpmnStore();
  if (processConfig.defaultFormList.length > 0) {
    const returnArr = await formPermissionList(processConfig.defaultFormList);
    setDefaultFormList(returnArr);
  }
  bpmnStore.setProcessInfo(processConfig);
  bpmnStore.setInfoId(processConfig.processId);
};
// 是否可以初始化节点属性【没有相关节点信息】
export const CanInitializeProperties = (id: InfoId) => {
  return !hasProperties(id);
};
// 是否有节点信息缓存
export const hasProperties = (id: InfoId) => {
  const bpmnStore = useBpmnStore();
  return bpmnStore.hasProperties(id);
};
// 设置节点信息缓存
export const setProperties = (id: InfoId, element: InfoItem) => {
  const bpmnStore = useBpmnStore();
  bpmnStore.setProperties(id, element);
};
// 初始化节点信息缓存
export const initProperties = (id: InfoId, type: InfoType, name: string, parentId: string) => {
  const bpmnStore = useBpmnStore();
  const { defaultFormList, processInfo } = bpmnStore;
  const properties = cloneDeep(getDefaultProperties(type));
  properties.id = id;
  properties.name = name;
  properties.type = type;
  properties.parentId = parentId;
  if (type == BpmnNodeKey.START || type == BpmnNodeKey.USER) {
    properties.formConfigs = cloneDeep(defaultFormList);
  }
  if (type == BpmnNodeKey.USER) {
    properties.autoAgreeRule = processInfo.autoAgreeRule;
    properties.noHandler = processInfo.noHandler;
    properties.isPrevChooseNext = processInfo.isPrevChooseNext;
  }

  setProperties(id, properties);
};
// 初始化用户开始节点信息缓存
export const initStartingNodeProperties = (
  id: InfoId,
  type: InfoType,
  name: string,
  parentId: string,
) => {
  const bpmnStore = useBpmnStore();
  const { defaultFormList, processInfo } = bpmnStore;
  const properties = cloneDeep(getDefaultProperties(type));
  properties.isStartingNode = true;
  properties.id = id;
  properties.name = name;
  properties.type = type;
  properties.parentId = parentId;
  properties.formConfigs = cloneDeep(defaultFormList);
  properties.autoAgreeRule = processInfo.autoAgreeRule;
  properties.noHandler = processInfo.noHandler;
  properties.isPrevChooseNext = processInfo.isPrevChooseNext;
  setProperties(id, properties);
};
// 移除节点信息缓存
export const removeProperties = (id: InfoId) => {
  const bpmnStore = useBpmnStore();
  if (bpmnStore.hasProperties(id)) {
    bpmnStore.deleteProperties(id);
  }
};
// 修改节点parentId
export const changePropertiesByParentId = (id: InfoId, parentId: InfoId) => {
  const bpmnStore = useBpmnStore();
  if (bpmnStore.hasProperties(id)) {
    const properties = bpmnStore.getProperties(id);
    if (properties) {
      properties.parentId = parentId;
      setProperties(id, properties);
    }
  }
};
// 修改流程线的上一节点信息
export const changeSequenceFlowSourceConfig = (
  id: InfoId,
  sourceConfig: SequenceFlowSourceConfig,
) => {
  const bpmnStore = useBpmnStore();
  if (bpmnStore.hasProperties(id)) {
    const properties = bpmnStore.getProperties(id);
    if (properties) {
      properties.sourceConfig = sourceConfig;
      setProperties(id, properties);
    }
  }
};
//设置默认表单列表
export const setDefaultFormList = (list: Array<FormConfigItem>) => {
  const bpmnStore = useBpmnStore();
  bpmnStore.setDefaultFormList(list);
};
//根据默认表单设置，追加所有表单节点的表单配置
export const nodesAppendDefaultForm = (list: Array<FormConfigItem>) => {
  const bpmnStore = useBpmnStore();
  setDefaultFormList(cloneDeep(list));
  const tempMap = new Map();
  const hasItemKeys: Array<string> = [];
  list.forEach((item) => {
    tempMap.set(item.key, item);
    hasItemKeys.push(item.key);
  });
  const { info } = bpmnStore;
  for (const [key, value] of info) {
    if (value.type == BpmnNodeKey.USER) {
      const properties = bpmnStore.getProperties(key);
      if (properties) {
        const propertiesItemKeys: Array<string> = [];
        const formConfigs: Array<any> = [];
        properties.formConfigs.forEach((ele) => {
          if (hasItemKeys.includes(ele.key)) {
            const temp = tempMap.get(ele.key);
            formConfigs.push(temp);
          } else {
            formConfigs.push(ele);
          }
          propertiesItemKeys.push(ele.key);
        });
        list.forEach((item) => {
          if (!propertiesItemKeys.includes(item.key)) {
            formConfigs.push(item);
          }
        });
        properties.formConfigs = formConfigs;
        setProperties(key, properties);
      }
    }
  }
};
// 设置childNodes属性
export const setChildNodesProperties = (childNodes: ChildNodeConfig) => {
  const bpmnStore = useBpmnStore();
  if (childNodes.length > 0) {
    childNodes.forEach((element: InfoItem) => {
      if (element.id && !bpmnStore.hasProperties(element.id)) {
        setProperties(element.id, element);
      }
    });
  }
};

// 获取缓存所有节点信息
export const getBpmnJson = () => {
  const bpmnStore = useBpmnStore();
  const { info, processInfo } = bpmnStore;
  const childNodeConfig = [...info.values()];
  return { childNodeConfig, processConfig: processInfo };
};
export const getUserStartTaskNode = 'Start_User_Task';
export const getUserStartTaskNodeID = getUserStartTaskNode + '_Activity_1';
export const getStartNodeIdTouserTaskNodeID = 'Flow_Start_User';
export const getStartNodeId = 'Event_start_node';
export const getInitializeXml = (resourceId: string) => {
  const userTaskNodeID = getUserStartTaskNodeID;
  const StartNodeIdTouserTaskNodeID = getStartNodeIdTouserTaskNodeID;
  return `
  <?xml version="1.0" encoding="UTF-8"?>
  <bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:modeler="http://camunda.org/schema/modeler/1.0" id="Definitions_1u51epq" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="5.2.0" modeler:executionPlatform="Camunda Platform" modeler:executionPlatformVersion="7.17.0">
    <bpmn:process id="${resourceId}" name="${resourceId}" isExecutable="true">
      <bpmn:startEvent  id="${getStartNodeId}" name="流程启动">
        <bpmn:outgoing>${StartNodeIdTouserTaskNodeID}</bpmn:outgoing>
    </bpmn:startEvent>
    <bpmn:userTask id="${userTaskNodeID}" name="用户开始节点">
      <bpmn:incoming>${StartNodeIdTouserTaskNodeID}</bpmn:incoming>
    </bpmn:userTask>
      <bpmn:sequenceFlow id="${StartNodeIdTouserTaskNodeID}" name="流程线" sourceRef="${getStartNodeId}" targetRef="${userTaskNodeID}" />
 
    </bpmn:process>
    <bpmndi:BPMNDiagram id="BPMNDiagram_1">
      <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1m1pmsz">
        <bpmndi:BPMNShape id="${getStartNodeId}_di" bpmnElement="${getStartNodeId}">
          <dc:Bounds x="159" y="359" width="36" height="36" />
        </bpmndi:BPMNShape>
        <bpmndi:BPMNShape id="${userTaskNodeID}_di" bpmnElement="${userTaskNodeID}">
         <dc:Bounds x="370" y="210" width="100" height="80" />
         <bpmndi:BPMNLabel />
       </bpmndi:BPMNShape>
             <bpmndi:BPMNEdge id="${StartNodeIdTouserTaskNodeID}_di" bpmnElement="${StartNodeIdTouserTaskNodeID}">
        <di:waypoint x="195" y="377" />
        <di:waypoint x="283" y="377" />
        <di:waypoint x="283" y="250" />
        <di:waypoint x="370" y="250" />
        <bpmndi:BPMNLabel>
          <dc:Bounds x="281" y="311" width="34" height="14" />
        </bpmndi:BPMNLabel>
      </bpmndi:BPMNEdge>
      </bpmndi:BPMNPlane>
    </bpmndi:BPMNDiagram>
  </bpmn:definitions>

  `;

  // return `<?xml version="1.0" encoding="UTF-8"?>
  // <definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:flowable="http://flowable.org/bpmn" targetNamespace="http://www.flowable.org/processdef">
  //   <process  id="${resourceId}" name="${resourceId}" isExecutable="true">
  //   <startEvent id="${getStartNodeId}" name="开始节点" />
  //   </process>
  //   <bpmndi:BPMNDiagram id="BPMNDiagram_flow">
  //     <bpmndi:BPMNPlane id="BPMNPlane_flow" bpmnElement="process_drril0cw">
  //       <bpmndi:BPMNShape id="${getStartNodeId}_di" bpmnElement="${getStartNodeId}">
  //         <omgdc:Bounds x="-708" y="-208" width="36" height="36" />
  //         <bpmndi:BPMNLabel>
  //           <omgdc:Bounds x="-712" y="-165" width="44" height="14" />
  //         </bpmndi:BPMNLabel>
  //       </bpmndi:BPMNShape>
  //     </bpmndi:BPMNPlane>
  //   </bpmndi:BPMNDiagram>
  // </definitions>
  //   `;
};
