<script setup lang="ts">
import { message } from 'ant-design-vue';
import { getBpmProcessDefinitionGet } from '@/api/modules/bpmDefinition/bpMliuchengdingyidexinxibiaokongzhiqi';
import { postBpmProcessInstanceCreate, postBpmProcessInstanceGetApprovalDetail } from '@/api/modules/bpmTask/guanlihoutailiuchengshili';
import registerComponent from '@/utils/registerComponent';
import { CandidateStrategy } from '../flow-create/flow-model/createComponents/flow/ts/enum';
import TimeLineComponent from '../flow-manage/components/timeLine.vue';

defineOptions({
  name: 'YewuProcessCreate',
});

const router = useRouter();
const processDefinitionId = ref<string>('');
const startUserSelectTasks = ref<any[]>([]); // 发起人需要选择审批人的用户任务列表
const timelineData = ref<any[]>([]); // 审批节点信息
const startUserSelectAssignees = ref<any>({}); // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref<any>({}); // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const isApproveResult = ref<boolean>(false);
const approveOptions = ref<any[]>([]);
const route = useRoute();
const processKey = ref<string>('');
const createPath = ref<string>('');
/** 加载流程实例 */
const BusinessFormComponent = shallowRef<any>(null); // 异步组件

// 预测流程节点的参数字符串，格式为 JSON.stringify({key:value})
const processVariablesStr = ref<string>('');
async function getApprovalDetail() {
  const res = await postBpmProcessInstanceGetApprovalDetail({
    processDefinitionId: processDefinitionId.value,
    activityId: 'StartUserNode',
    processVariablesStr: processVariablesStr.value,
  });
  if (res.success) {
    // 获取审批路径(当全部是条件路径（没有设置条件）的时候，发起人自己选择走哪条路径)
    if (res.data?.nextFlows && res.data.nextFlows.length > 0) {
      const flows = res.data.nextFlows;
      if (flows[0].optionName === 'approveResult') {
        isApproveResult.value = true;
        approveOptions.value = flows.map((item) => {
          return {
            label: item.flowName,
            value: item.flowId,
          };
        });
      }
      else {
        isApproveResult.value = false;
      }
    }
    // 获取审批节点，显示 Timeline 的数据
    timelineData.value = res.data?.activityNodes ?? [];

    // 获取发起人自选的任务
    startUserSelectTasks.value = timelineData.value.filter(
      (node: any) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy,
    );
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        if (
          tempStartUserSelectAssignees.value[node.id]
          && tempStartUserSelectAssignees.value[node.id].length > 0
        ) {
          startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id];
        }
        else {
          startUserSelectAssignees.value[node.id] = [];
        }
      }
    }
  }
  else {
    message.error('查询不到审批详情信息！');
  }
}

onMounted(async () => {
  processKey.value = (route.query.key as string) || '';
  createPath.value = (route.query.createPath as string) || '';
  BusinessFormComponent.value = registerComponent(createPath.value!);
  const response = await getBpmProcessDefinitionGet({ id: undefined, key: processKey.value });
  if (response.success) {
    const processDefinition = response.data;
    if (!processDefinition) {
      message.error('流程模型未配置，请检查！');
      return;
    }
    processDefinitionId.value = processDefinition.id;
    // startUserSelectTasks.value = processDefinition.startUserSelectTasks;
  }
  // 审批相关：加载最新的审批详情，主要用于节点预测
  await getApprovalDetail();
});

function updateFormData(newValue: any) {
  // 处理表单数据更新逻辑
  if (newValue && Object.keys(newValue).length > 0) {
    // 记录之前的节点审批人
    tempStartUserSelectAssignees.value = startUserSelectAssignees.value;
    startUserSelectAssignees.value = {};
    // 加载最新的审批详情,主要用于节点预测
    processVariablesStr.value = JSON.stringify(newValue);
    getApprovalDetail();
  }
}
/** 审批相关：选择发起人 */
function selectUserConfirm(id: string, userList: any[]) {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id);
}

async function submitForm(data: any) {
  // 1.2 审批相关：校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    for (const userTask of startUserSelectTasks.value) {
      if (
        Array.isArray(startUserSelectAssignees.value[userTask.id])
        && startUserSelectAssignees.value[userTask.id].length === 0
      ) {
        return message.warning(`请选择${userTask.name}的审批人`);
      }
    }
  }
  const params = {
    processDefinitionId: processDefinitionId.value,
    variables: data,
    startUserSelectAssignees: startUserSelectAssignees.value,
  };
  postBpmProcessInstanceCreate(params).then((res) => {
    // console.log('创建流程实例返回：', res);
    if (res.success) {
      message.success('提交申请成功');
      router.push({ name: 'myProcessList' });
    }
  });
}
</script>

<template>
  <div
    py-10px
    px-10px
    w-full
    h-full
  >
    <div size-full rd-4px bg="#fff" p-30px flex>
      <div v-if="BusinessFormComponent" flex-1>
        <BusinessFormComponent :is-approve-result="isApproveResult" :approve-options="approveOptions" @update-form-data="updateFormData" @submit="submitForm" />
      </div>
      <div v-else flex-1>
        <div text-20px>
          未找到表单
        </div>
      </div>
      <div class="w-40%" pl-40px pt-40px>
        <TimeLineComponent :activity-nodes="timelineData" @select-user-confirm="selectUserConfirm" />
      </div>
    </div>
  </div>
</template>
