<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <BreadcrumbBack />
      <span class="breadcrumb-title">{{ '编辑审批流程' }}</span>
    </header>
    <main class="safety-platform-container__main">
      <div class="approval-node-container">
        <div class="approval-node-container__title">流程模板信息</div>
        <BasicForm
          style="height: auto"
          ref="basicFormRef"
          :formData="ruleFormData"
          :formRules="formRules"
          :formConfig="ruleFormConfig"
        >
        </BasicForm>
        <div class="approval-node-container__button">
          <el-button type="primary" @click="handleEditApproval">保存</el-button>
        </div>
        <div class="approval-node-container__title">审批流程设置</div>
        <div class="approval-node-container__button">
          <el-button type="primary" @click="handleCreateApprovalNode" :icon="Plus">添加审批节点</el-button>
        </div>
        <div style="flex-grow: 1">
          <BasicTable :tableConfig="tableConfig" :tableData="tableData">
            <template #approverType="scope">
              <span> {{ APPROVER_TYPE_MAP[scope.row.approverType] }}</span>
            </template>
            <template #approvalType="scope">
              <span> {{ APPROVAL_TYPE_MAP[scope.row.approvalType] }}</span>
            </template>
            <template #action="scope">
              <ActionButton text="编辑节点" @click="handleEditApprovalNode(scope.row)" />
              <ActionButton
                v-if="scope.row.approverType === 0"
                text="选择审批人"
                @click="handleOpenAppoverSelect(scope.row)"
              />
              <ActionButton
                v-if="tableData.length > 1"
                text="删除节点"
                :popconfirm="{
                  title: '确定要删除?',
                }"
                @confirm="handleDeleteNode(scope.row.id)"
              />
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
    <ApproverSelectDialog ref="approverSelectDialogRef" @submit="handleApproverSelect" />
    <ApprovalNodeCreateDialog
      ref="approvalNodeCreateDialogRef"
      :is-create="isCreatForm"
      :init-data="initFormData"
      :order-list="approvalOrderList"
      @success="getTableData"
    />
  </div>
</template>

<script lang="ts" setup>
  import { useRoute } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import { computed, onMounted, ref } from 'vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import BasicForm from '@/components/BasicForm.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import { ApprovalNodeInstanceRuleForm, ApprovalInstanceRuleForm, ApprovalNodeInstanceType } from './types';
  import { APPROVAL_FORM_CONFIG, APPROVAL_FORM_DATA, APPROVAL_FORM_RULES } from './config/form';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { APPROVAL_NODE_TABLE_COLUMNS, NODE_TABLE_OPTIONS } from './config/table';
  import { APPROVER_TYPE_MAP, APPROVAL_TYPE_MAP } from './constants';
  import ApproverSelectDialog from './components/ApproverSelectDialog.vue';
  import ApprovalNodeCreateDialog from './components/ApprovalNodeCreateDialog.vue';
  import {
    getApprovalNodeInstanceList,
    updateApprovalInstance,
    updateApprvoerInfo,
    delApprovalNodeInstance,
  } from '@/api/approval/approval';
  import { queryUserInfoByIds } from '@/api/system/person-group';
  import { PersonGroupItem } from '@/types/person-group/type';

  const route = useRoute();

  const id = route.query.id;
  const curNodeId = ref();
  const approvalInstance = ref<ApprovalInstanceRuleForm>();

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<ApprovalInstanceRuleForm>(APPROVAL_FORM_CONFIG, APPROVAL_FORM_DATA, APPROVAL_FORM_RULES);

  const approvalOrderList = computed(() => {
    return tableData.value.map((item) => item.approvalOrder);
  });

  const approvalOrderMax = computed(() => {
    return Math.max(...approvalOrderList.value);
  });

  function initForm(initData: ApprovalInstanceRuleForm) {
    ruleFormData.id = initData.id;
    ruleFormData.templateName = initData.templateName;
    ruleFormData.description = initData.description;
  }

  const { tableConfig } = useTableConfig(APPROVAL_NODE_TABLE_COLUMNS, NODE_TABLE_OPTIONS, false);
  const tableData = ref<ApprovalNodeInstanceType[]>([]);

  async function getTableData() {
    tableConfig.loading = true;
    approvalInstance.value = await getApprovalNodeInstanceList(Number(id));
    tableData.value = approvalInstance.value.approvalNodeInfoList!;
    tableData.value.forEach((item) => {
      item.approverNameList = item.approverInfoList.map((item) => item.approverName).join(',');
    });
    tableConfig.loading = false;
  }

  onMounted(async () => {
    await getTableData();
    initForm(approvalInstance.value!);
    cloneRuleFormData();
    beforeRouteLeave();
  });

  const handleEditApproval = async () => {
    const validate = await basicFormRef.value?.validateForm();
    if (!validate) return;
    // 提交表单接口
    try {
      await updateApprovalInstance(ruleFormData);
      ElMessage.success('提交成功');
      cloneRuleFormData();
    } catch (e) {
      console.log(e);
    } finally {
    }
  };

  const approvalNodeCreateDialogRef = ref();
  const isCreatForm = ref(true);
  const initFormData = ref<ApprovalNodeInstanceRuleForm>();
  const handleCreateApprovalNode = () => {
    if (approvalInstance.value?.isApplied) {
      ElMessage.error('请完成当前审批中流程后修改节点');
      return;
    }
    isCreatForm.value = true;
    initFormData.value = {
      approvalTemplateId: Number(id),
      nodeDescription: '',
      approvalType: 0,
      approverType: 1,
      approvalOrder: approvalOrderMax.value + 1,
    };
    approvalNodeCreateDialogRef.value.openDialog();
  };
  const handleEditApprovalNode = (row: ApprovalNodeInstanceType) => {
    if (approvalInstance.value?.isApplied) {
      ElMessage.error('请完成当前审批中流程后修改节点');
      return;
    }
    isCreatForm.value = false;
    initFormData.value = { ...row, approvalTemplateId: Number(id) };
    approvalNodeCreateDialogRef.value.openDialog();
  };

  const approverSelectDialogRef = ref();
  const handleOpenAppoverSelect = async (node: ApprovalNodeInstanceType) => {
    if (approvalInstance.value?.isApplied) {
      ElMessage.error('请完成当前审批中流程后修改节点');
      return;
    }
    if (approverSelectDialogRef.value) {
      if (node.approverInfoList.length > 0) {
        const res = await queryUserInfoByIds(node.approverInfoList.map((x) => x.approverId));
        approverSelectDialogRef.value.setSelectedUser(res);
      }
      curNodeId.value = node.id;
      approverSelectDialogRef.value.openDialog();
    }
  };

  const handleApproverSelect = async (list: PersonGroupItem[]) => {
    if (approvalInstance.value?.isApplied) {
      ElMessage.error('请完成当前审批中流程后修改节点');
      return;
    }
    try {
      await updateApprvoerInfo({
        id: curNodeId.value,
        approvalTemplateId: Number(id),
        approverList: '[' + list.map((item) => item.id).join(',') + ']',
      });
      approverSelectDialogRef.value.closeDialog();
      getTableData();
      curNodeId.value = undefined;
    } catch (e) {
      console.log(e);
    }
  };

  const handleDeleteNode = async (id: number) => {
    if (approvalInstance.value?.isApplied) {
      ElMessage.error('请完成当前审批中流程后修改节点');
      return;
    }
    try {
      tableConfig.loading = true;
      await delApprovalNodeInstance(id);
      getTableData();
    } catch (e) {
      console.log(e);
    }
  };
</script>

<style lang="scss" scoped>
  @use '@/styles/page-details-layout.scss' as *;
  .safety-platform-container__header {
    flex-direction: row !important;
    justify-content: flex-start !important;
    gap: 8px !important;
  }
  .approval-node-container {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  .approval-node-container__title {
    margin: 5px 0 10px;
  }
  .approval-node-container__button {
    text-align: start;
    margin: 10px 0 20px;
  }
</style>
