<!--
   模型创建
 * 文件: create.vue
 * 功能: 流程模型创建/编辑/复制/恢复视图，包含多步骤表单（基础信息、表单配置、流程设计与更多设置），
 *       支持保存、发布与恢复已发布模型为新版本。
 * 主要逻辑:
 * - 使用多步骤（Step 1-4）流程，`current` 控制当前步骤，`changeStep` 校验当前步骤表单后切换。
 * - 在组件挂载阶段通过 `route.params` 判断当前 `type`（create/copy/edit/recovery），根据 `id` 拉取相应模型或流程定义详情并初始化 `formData`。
 * - `formData` 保存模型的完整配置信息（基础信息、权限、表单关联、BPMN XML、版本设置等），并通过 `provide('modelData', formData)` 向子组件传递。
 * - 子组件 `CreateStep1/2/3/4` 分别负责不同步骤的数据录入与校验，父组件通过 ref 调用 `validateForm` / `validateStep4` 等方法。
 * - `saveModel` / `publishModel` / `recoveryModel` 分别处理保存、发布、恢复操作：
 *   - 保存时根据 `type` 调用 `postBpmModelCreate` 或 `postBpmModelUpdate`；
 *   - 发布时先保存（若需要），再调用 `postBpmModelDeploy` 发布流程定义；
 *   - 恢复模式会提示用户并从流程定义获取数据，允许修改后保存为新版本。
 * - 按钮和操作均在 Promise 返回后给出提示并导航返回（或刷新），当前实现以简单成功回调为主，建议补充错误处理与 loading 状态。
 * 注意事项:
 * - 复制模型时会对名称与 key 做后缀处理以避免冲突，并清空 `id` 以创建新模型；
 * - 初始化时会从本地缓存中尝试设置当前用户为模型管理员；
 * - 修改 `formData` 字段结构时需同步子组件与后端请求字段映射。
 -->
<script setup lang="ts">
import { message, Modal } from 'ant-design-vue';
import { useUserStore } from 'pubinfo';
import { useRoute } from 'vue-router';
import { getBpmProcessDefinitionGet } from '@/api/modules/bpmDefinition/bpMliuchengdingyidexinxibiaokongzhiqi';
import { getBpmModelGet, postBpmModelCreate, postBpmModelDeploy, postBpmModelUpdate } from '@/api/modules/bpmDefinition/guanlihoutailiuchengmoxing';
import { useElementsInfoStore } from './createComponents/flow/stores/elementsInfo.ts';
import { useSelectedInfoStore } from './createComponents/flow/stores/selectedInfo.ts';
import CreateStep1 from './createComponents/step1.vue';
import CreateStep2 from './createComponents/step2.vue';
import CreateStep3 from './createComponents/step3.vue';

import CreateStep4 from './createComponents/step4/index.vue';
import StepHeader from './createComponents/stepHeader.vue';

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

const current = ref<number>(1);
const route = useRoute();
const router = useRouter();
const type = ref<string>('create');
const baseInfoRef = ref<InstanceType<typeof CreateStep1>>();
const formInfoRef = ref<InstanceType<typeof CreateStep2>>();
const step4Ref = ref<InstanceType<typeof CreateStep4>>();

function changeStep(value: number) {
  // console.log('step changed', value);
  if (current.value === 1) {
    baseInfoRef.value?.validateForm().then(() => {
      current.value = value;
    });
  }
  else if (current.value === 2) {
    formInfoRef.value?.validateForm().then(() => {
      current.value = value;
    });
  }
  else if (current.value === 4) {
    step4Ref.value?.validateStep4().then(() => {
      current.value = value;
    });
  }
  else {
    current.value = value;
  }

  // console.log('current', current.value);
}
// 获取登入者信息
const formData: any = ref({
  id: undefined,
  name: '',
  key: '',
  category: undefined,
  icon: undefined,
  description: '',
  type: 10, // BPMN 设计器
  formType: 20, // 业务表单
  formId: '',
  formCustomCreatePath: '',
  formCustomViewPath: '',
  visible: true,
  startUserType: 0,
  startUserIds: [],
  startDeptIds: [],
  managerUserIds: [],
  bpmnXml: '',
  bpmnXmlBase64: '',
  // 允许撤销审批中的申请
  allowCancelRunningProcess: true,
  // 允许审批人撤回任务
  allowWithdrawTask: false,
  // 流程编码规则
  processIdRule: {
    enable: false,
    prefix: '',
    infix: '',
    postfix: '',
    length: 5,
  },
  // 同一审批人在流程中重复出现时的处理方式
  autoApprovalType: 0, // NONE 不自动通过
  // 标题设置 系统默认
  titleSetting: {
    enable: false,
    title: '',
  },
  // 摘要设置 系统默认
  summarySetting: {
    enable: false,
    summary: [],
  },
  // 流程前置通知
  processBeforeTriggerSetting: null,
  // 流程后置通知
  processAfterTriggerSetting: null,
  // 任务前置通知
  taskBeforeTriggerSetting: null,
  // 任务后置通知
  taskAfterTriggerSetting: null,
  // 自定义打印模板（该版本没有）
  printTemplateSetting: {
    enable: false,
  },
});

// 流程数据
// const processData = ref<any>();
// provide('processData', processData);

provide('modelData', formData);

const flowModelId = ref<string | undefined>(undefined);
function initFormData() {
  if (route.params.id) {
    // 编辑或复制
    flowModelId.value = route.params.id as string;
    type.value = route.params.type as string;
    if (type.value === 'recovery') {
      message.info('当前为流程模型恢复模式，可修改已发布流程模型的信息并保存为新版本', 8);
      // 获取流程定义详情
      getBpmProcessDefinitionGet({ id: flowModelId.value }).then((res) => {
        if (res.success && res.data) {
          res.data.type = res.data.modelType!;
          res.data.id = res.data.modelId!;

          formData.value = {
            ...res.data,
          };
          delete formData.value.modelType;
          delete formData.value.modelId;

          formData.value.formType = res.data.formType === null ? 10 : res.data.formType;
          formData.value.startUserType = formData.value.startUserIds?.length > 0 ? 1 : formData.value?.startDeptIds?.length > 0 ? 2 : 0;
        }
      });
    }
    else {
      // 获取模型详情
      getBpmModelGet({ id: flowModelId.value }).then((res) => {
        if (res.success && res.data) {
          formData.value = {
            ...res.data,
          };
          formData.value.formType = res.data.formType === null ? 10 : res.data.formType;
          formData.value.startUserType = formData.value.startUserIds?.length > 0 ? 1 : formData.value?.startDeptIds?.length > 0 ? 2 : 0;
          if (type.value === 'copy') {
            formData.value.id = undefined;
            if (formData.value.bpmnXml) {
              formData.value.bpmnXml = formData.value.bpmnXml.replaceAll(
                `id="diagram_${formData.value.key}"`,
                `id="diagram_${formData.value.key}-copy"`,
              ).replaceAll(
                `id="${formData.value.key}" name="${formData.value.name}"`,
                `id="${formData.value.key}-copy" name="${formData.value.name}副本"`,
              ).replaceAll(
                `id="${formData.value.key}_di" bpmnElement="${formData.value.key}"`,
                `id="${formData.value.key}-copy_di" bpmnElement="${formData.value.key}-copy"`,
              );
            }
            formData.value.name = `${formData.value.name}副本`;
            formData.value.key = `${formData.value.key}-copy`;

            const userStore = useUserStore();
            // console.log('create userInfo', userStore.user);
            const userInfo = userStore.user;
            if (userInfo) {
              const managerUserIds = [userInfo.userId];
              const managerUsers = [
                {
                  deptId: userInfo.orgId,
                  id: userInfo.userId,
                  nickname: userInfo.account,
                },
              ];
              formData.value.managerUserIds = managerUserIds;
              formData.value.managerUsers = managerUsers;
            }
          }
        // console.log('获取流程模型详情', formData.value);
        }
      });
    }
  }
  else {
    // 新建
    type.value = 'create';
    const userStore = useUserStore();
    // console.log('create userInfo', userStore.user);
    const userInfo = userStore.user;
    if (userInfo) {
      const managerUserIds = [userInfo.userId];
      const managerUsers = [
        {
          deptId: userInfo.orgId,
          id: userInfo.userId,
          nickname: userInfo.account,
        },
      ];
      formData.value.managerUserIds = managerUserIds;
      formData.value.managerUsers = managerUsers;
    }
  }
}

function saveModel() {
  // console.log('保存流程模型', formData.value);
  formData.value.bpmnXml = formData.value.bpmnXml.replaceAll(
    `id="diagram_${formData.value.key}"`,
    `id="diagram_${formData.value.key}-copy"`,
  ).replaceAll(
    `id="${formData.value.key}" name="${formData.value.name}"`,
    `id="${formData.value.key}-copy" name="${formData.value.name}副本"`,
  ).replaceAll(
    `id="${formData.value.key}_di" bpmnElement="${formData.value.key}"`,
    `id="${formData.value.key}-copy_di" bpmnElement="${formData.value.key}-copy"`,
  );
  formData.value.formType = formData.value.formType === 10 ? undefined : formData.value.formType;
  if (type.value === 'create' || type.value === 'copy') {
    postBpmModelCreate(formData.value).then((res) => {
    // 保存成功后的一些操作
      if (res.success) {
        formData.value.id = res.data;
        console.warn('流程模型保存成功，ID：', res.data);
        const messageText = type.value === 'copy' ? '复制' : '新建';
        message.success(`${messageText}成功，可点击【发布】按钮，进行发布模型`);
        router.back();
      }
    });
  }
  if (type.value === 'edit') {
    postBpmModelUpdate(formData.value).then((res) => {
      // 保存成功后的一些操作
      if (res.success) {
        console.warn('流程模型保存成功');
        message.success('修改成功，可点击【发布】按钮，进行发布模型');
        router.back();
      }
    });
  }
}

function recoveryModel() {
  formData.value.formType = formData.value.formType === 10 ? undefined : formData.value.formType;
  postBpmModelUpdate(formData.value).then((res) => {
    // 保存成功后的一些操作
    if (res.success) {
      console.warn('流程模型保存成功');
      message.success('恢复成功，可点击【发布】按钮，进行发布模型');
      router.back();
    }
  });
}
async function publishModel() {
  Modal.confirm({
    title: '发布确认',
    content: '是否确认发布该流程？',
    onOk: async () => {
      formData.value.bpmnXml = formData.value.bpmnXml.replaceAll(
        `id="diagram_${formData.value.key}"`,
        `id="diagram_${formData.value.key}-copy"`,
      ).replaceAll(
        `id="${formData.value.key}" name="${formData.value.name}"`,
        `id="${formData.value.key}-copy" name="${formData.value.name}副本"`,
      ).replaceAll(
        `id="${formData.value.key}_di" bpmnElement="${formData.value.key}"`,
        `id="${formData.value.key}-copy_di" bpmnElement="${formData.value.key}-copy"`,
      );
      formData.value.formType = formData.value.formType === 10 ? undefined : formData.value.formType;
      const quest = type.value === 'create' || type.value === 'copy'
        ? postBpmModelCreate
        : postBpmModelUpdate;
      const res = await quest(formData.value);
      // 保存成功后的一些操作
      if (res.success) {
        if (type.value === 'create' || type.value === 'copy') {
          formData.value.id = res.data;
          console.warn('流程模型保存成功，ID：', res.data);
          type.value = 'edit';
        }
        else {
          console.warn('流程模型保存成功');
        }
      }
      postBpmModelDeploy({ id: formData.value.id }).then((deployRes) => {
        if (deployRes.success) {
          message.success('发布成功');
          router.back();
        }
      });
    },
    onCancel() {},
  });
}

onMounted(() => {
  // 清理Store数据 防止之前的操作产生脏数据
  useSelectedInfoStore().setSelectId('');
  useSelectedInfoStore().setSelectType('');
  useElementsInfoStore().clearElements();

  initFormData();
});
</script>

<template>
  <div
    py-10px
    px-10px
    w-full
    h-full
  >
    <div w-full h-full bg="#ffffff" rounded-8px flex flex-col>
      <div class="w-50% h-50px mx-auto pt-12px">
        <!-- <a-steps v-model:current="current" :items="steps" @change="changeStep" /> -->
        <StepHeader :current="current" @change="changeStep" />
      </div>
      <div flex-1 overflow-y-auto>
        <div v-if="current === 1" class="w-60% mx-auto mt-20px">
          <CreateStep1 ref="baseInfoRef" v-model="formData" />
        </div>
        <div v-if="current === 2" class="w-60% mx-auto mt-20px">
          <CreateStep2 ref="formInfoRef" v-model="formData" />
        </div>
        <CreateStep3 v-if="current === 3" v-model="formData" />
        <div v-if="current === 4" class="w-60% mx-auto  mt-20px">
          <CreateStep4 ref="step4Ref" v-model="formData" />
        </div>
      </div>
      <div w-full h-60px flex items-center justify-end border-t border-t-solid border-t-1px border-t-gray-200 px-20px>
        <a-space>
          <a-button @click="router.back()">
            取消
          </a-button>
          <a-button v-if="type !== 'recovery'" type="primary" @click="publishModel">
            发布
          </a-button>
          <a-button v-if="type !== 'recovery'" type="primary" @click="saveModel">
            保存
          </a-button>
          <a-button v-if="type === 'recovery'" type="primary" @click="recoveryModel">
            恢复
          </a-button>
        </a-space>
      </div>
    </div>
  </div>
</template>
