<template>
  <el-alert v-if="currentStatus === -1" :title="ruleFormData.returnReason" type="warning" />
  <main class="safety-platform-container__main">
    <BasicForm
      ref="basicFormRef"
      :formData="ruleFormData"
      :formRules="isViewMode || isAuditMode ? undefined : formRules"
      :formConfig="computedFormConfig"
    >
      <template #itemId>
        <el-select
          v-model="ruleFormData.itemId"
          placeholder="请选择奖品名称"
          filterable
          clearable
          :disabled="isViewMode || isAuditMode"
        >
          <el-option v-for="item in inventoryList" :key="item.id" :label="item.stuffName" :value="item.id" />
        </el-select>
      </template>
      <template #department>
        <el-cascader
          ref="cascaderRef"
          v-model="ruleFormData.deptId"
          :options="deptTree"
          :props="cascaderDeptProp"
          :show-all-levels="false"
          placeholder="请选择部门"
          filterable
          :disabled="isViewMode || isAuditMode"
          @change="handleDeptChange"
        />
      </template>
      <template #recipient>
        <el-select
          v-model="ruleFormData.recipientUserId"
          placeholder="请选择领取人"
          filterable
          clearable
          :disabled="isViewMode || isAuditMode"
          @change="handleRecipientChange"
        >
          <el-option v-for="user in recipientUserList" :key="user.id" :label="user.realname" :value="user.id" />
        </el-select>
      </template>
      <template #approvalTemplateId>
        <el-select
          v-model="ruleFormData.approvalTemplateId"
          placeholder="请选择审批流程"
          filterable
          clearable
          :disabled="isViewMode || isAuditMode"
        >
          <el-option v-for="item in approvalList" :key="item.id" :label="item.templateName" :value="item.id" />
        </el-select>
      </template>
    </BasicForm>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <template v-if="isAuditMode">
      <el-button type="primary" @click="handleAuditPass">同意</el-button>
      <el-button type="danger" @click="handleAuditReject">拒绝</el-button>
    </template>
    <el-button v-else-if="!isViewMode" type="primary" @click="handleSubmit">
      {{ isCreateMode ? '提交' : '保存' }}
    </el-button>
  </footer>
  <BasicDialog v-if="!isViewMode && !isAuditMode" ref="basicDialogRef" title="提交审批" @refresh="closeApprovalDialog">
    <template #form>
      <div class="form">
        <el-form ref="approvalFormRef" :model="approvalForm">
          <!-- <el-form-item label="审批描述：" label-position="top">
            <el-input v-model="approvalForm.description" placeholder="请输入审批描述" type="textarea" />
          </el-form-item> -->
          <div class="form-item">
            <span>审批流程：</span>
            <template v-for="item in approvalNodeList" :key="item.id">
              <el-form-item
                :label="`第${item.approvalOrder}步：${item.nodeDescription}（${APPROVAL_TYPE_MAP[item.approvalType]}）`"
                label-position="top"
                :prop="item.approverType !== APPROVER_TYPE.FIX ? `approvers.${item.id}` : ''"
                :rules="{ required: true, message: '请选择审批人员', trigger: 'change' }"
              >
                <el-input
                  v-if="item.approverType === APPROVER_TYPE.FIX"
                  :model-value="item.approverInfoList.map((info) => info.approverName).join(',')"
                  disabled
                />
                <el-select
                  v-else
                  v-model="approvalForm.approvers[item.id]"
                  placeholder="请选择审批人员"
                  value-key="id"
                  filterable
                  remote
                  collapse-tags
                  collapse-tags-tooltip
                  :max-collapse-tags="2"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  multiple
                >
                  <el-option
                    v-for="option in userOptions"
                    :key="option.id"
                    :label="`${option.realname}（${option.username}）${option.deptName}`"
                    :value="option.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </div>
        </el-form>
      </div>
    </template>
    <template #footer>
      <el-button type="primary" @click="handleSubmitApproval">提交</el-button>
      <el-button @click="basicDialogRef?.closeDialog()">取消</el-button>
    </template>
  </BasicDialog>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref, reactive } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage, ElAlert } from 'element-plus';
  import BasicForm from '@/components/BasicForm.vue';
  import BasicDialog from '@/components/BasicDialog.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { RECEIPT_RECORD_FORM_CONFIG, RECEIPT_RECORD_FORM_DATA, RECEIPT_RECORD_FORM_RULES } from '../configs/form';
  import {
    saveClaimItemsLog,
    updateClaimItemsLog,
    queryClaimItemsLogDetail,
    querInventoryManageList,
    updateClaimItemsLogAgree,
    updateClaimItemsLogReject,
    submitReceiptRecordApprovalProcess,
  } from '@/api/receiptRecord';
  import type { InventoryItem } from '@/api/inventory';
  import { getAllDepartments } from '@/api/auth/dept';
  import type { DeptTree } from '@/types/dept/type';
  import { queryAvailableUserList } from '@/api/production-safety/responsibility-implementation';
  import type { UserLisItem } from '@/api/system/user-operate';
  import { getAllApproval } from '@/api/approval/approval';
  import type { ApprovalInstanceType } from '@/views/system/approval/types';
  import { useEmergencySuppliesHook } from '@/views/emergency/emergency-supplies/src/hook';
  import type { ApprovalNodeInstanceType } from '@/views/system/approval/types';
  import { getApprovalNodeInstanceList } from '@/api/approval/approval';
  import { APPROVAL_TYPE_MAP, APPROVER_TYPE } from '@/views/emergency/emergency-plan/src/constant';

  const router = useRouter();
  const route = useRoute();

  const operate = computed(() => (route.query.operate as string) || 'receiptRecord-create');
  const currentId = computed(() => Number(route.query.id));

  const isCreateMode = computed(() => operate.value === 'receiptRecord-create');
  const isEditMode = computed(() => operate.value === 'receiptRecord-edit');
  const isViewMode = computed(() => operate.value === 'receiptRecord-view');
  const isAuditMode = computed(() => operate.value === 'receiptRecord-audit');

  // 当前记录ID（用于提交审批）
  const receiptRecordId = ref<number>();

  // 部门树（复用添加应急预案的制定部门数据源）
  const cascaderRef = ref();
  const deptTree = ref<DeptTree[]>([]);
  const cascaderDeptProp = {
    checkStrictly: true,
    expandTrigger: 'hover' as const,
    value: 'id',
    label: 'deptName',
    emitPath: false,
  };
  const getDeptTreeData = async () => {
    try {
      const res = await getAllDepartments();
      deptTree.value = res?.[0]?.children ?? [];
    } catch (e) {
      console.error('获取部门树失败:', e);
    }
  };
  const handleDeptChange = () => {
    const nodes = cascaderRef.value?.getCheckedNodes();
    ruleFormData.department = nodes?.[0]?.label ?? '';
    // 部门变化时，重新获取该部门的用户列表
    if (ruleFormData.deptId) {
      getRecipientUserList(ruleFormData.department);
    } else {
      recipientUserList.value = [];
      ruleFormData.recipientUserId = null;
    }
  };
  const findDeptIdByName = (nodes: DeptTree[] | undefined, name: string): number | undefined => {
    if (!nodes?.length) return undefined;
    for (const n of nodes) {
      if (n.deptName === name) return n.id ?? undefined;
      const found = findDeptIdByName(n.children, name);
      if (found != null) return found;
    }
    return undefined;
  };

  // 领取人用户列表
  const recipientUserList = ref<UserLisItem[]>([]);
  const getRecipientUserList = async (deptId: number) => {
    try {
      const res = await queryAvailableUserList({
        pageNumber: 1,
        pageSize: 9999,
        queryParam: {
          deptId,
        },
      });
      if (res && res.records) {
        recipientUserList.value = res.records;
      } else {
        recipientUserList.value = [];
      }
    } catch (e) {
      console.error('获取用户列表失败:', e);
      recipientUserList.value = [];
    }
  };

  const handleRecipientChange = () => {
    const selectedUser = recipientUserList.value.find((user) => user.id === ruleFormData.recipientUserId);
    ruleFormData.recipient = selectedUser?.realname ?? '';
  };

  // 审批流程列表（复用应急预案的审批模板）
  const approvalList = ref<ApprovalInstanceType[]>([]);
  const getApprovalList = async () => {
    try {
      const res = await getAllApproval();
      approvalList.value = Array.isArray(res) ? res : [];
    } catch (e) {
      console.error('获取审批流程列表失败:', e);
      approvalList.value = [];
    }
  };

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData } = useFormConfigHook(
    RECEIPT_RECORD_FORM_CONFIG,
    RECEIPT_RECORD_FORM_DATA,
    RECEIPT_RECORD_FORM_RULES,
  );

  // 提交审批弹窗相关
  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const approvalFormRef = ref();
  const approvalForm = reactive({
    description: '',
    approvers: {} as Record<number, any[]>,
  });

  const approvalNodeList = ref<ApprovalNodeInstanceType[]>([]);

  const { userOptions, loading, remoteMethod } = useEmergencySuppliesHook();

  const getApprovalNode = async (id: number) => {
    const res = await getApprovalNodeInstanceList(id);
    approvalNodeList.value = res.approvalNodeInfoList || [];
  };

  const resetApprovalForm = () => {
    approvalFormRef.value?.resetFields();
    approvalForm.description = '';
  };

  const closeApprovalDialog = () => {
    resetApprovalForm();
    basicDialogRef.value?.closeDialog();
  };

  // 奖品库存列表
  const inventoryList = ref<InventoryItem[]>([]);

  // 当前记录状态（用于控制“审核不通过原因”字段显示）
  const currentStatus = ref<number | undefined>();

  // 查看 / 审核模式下，所有字段设为只读
  const viewFormConfig = ref(
    RECEIPT_RECORD_FORM_CONFIG.map((item) => ({
      ...item,
      componentProps: {
        ...item.componentProps,
        disabled: true,
      },
    })),
  );

  const computedFormConfig = computed(() => {
    // 新增时不展示“审核不通过原因”字段
    if (isCreateMode.value) {
      return ruleFormConfig.value.filter((item) => item.prop !== 'returnReason');
    }

    // 查看模式：仅在“审核不通过”时展示“审核不通过原因”字段
    if (isViewMode.value) {
      if (currentStatus.value === -1) {
        return viewFormConfig.value;
      }
      return viewFormConfig.value.filter((item) => item.prop !== 'returnReason');
    }

    // 编辑模式：仅在“审核不通过”时展示“审核不通过原因”字段
    if (isEditMode.value) {
      if (currentStatus.value === -1) {
        return ruleFormConfig.value;
      }
      return ruleFormConfig.value.filter((item) => item.prop !== 'returnReason');
    }

    // 审核模式：不展示“审核不通过原因”字段
    if (isAuditMode.value) {
      return viewFormConfig.value.filter((item) => item.prop !== 'returnReason');
    }

    return ruleFormConfig.value;
  });

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  // 获取奖品库存列表
  const getInventoryList = async () => {
    try {
      const res = await querInventoryManageList();
      if (res) {
        if (Array.isArray(res)) {
          inventoryList.value = res;
        } else if (res && typeof res === 'object' && 'data' in res && Array.isArray(res.data)) {
          inventoryList.value = res.data;
        } else {
          inventoryList.value = res as InventoryItem[];
        }
      }
    } catch (e) {
      console.error('获取奖品库存列表失败:', e);
    }
  };

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const res = await basicFormRef.value.validateForm();
    return res;
  };
  const ReceiptRecordData = ref({});
  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryClaimItemsLogDetail(currentId.value);
      if (res) {
        ReceiptRecordData.value = res;
        currentStatus.value = res.status;
        ruleFormData.itemId = res.stuffName;
        ruleFormData.outboundDate = res.outStoreTime ? res.outStoreTime.split('T')[0] : '';
        ruleFormData.outboundQuantity = res.claimQty;
        ruleFormData.receiptNumber = res.orderNumber;
        ruleFormData.department = res.deptName ?? '';
        ruleFormData.deptId = findDeptIdByName(deptTree.value, res.deptName ?? '') ?? null;
        ruleFormData.recipient = res.userName ?? '';
        ruleFormData.pimId = res.pimId;

        // 如果部门ID存在，先获取该部门的用户列表，然后根据用户名查找用户ID
        if (ruleFormData.deptId) {
          await getRecipientUserList(ruleFormData.deptId);
          const foundUser = recipientUserList.value.find((user) => user.realname === res.userName);
          ruleFormData.recipientUserId = foundUser?.id ?? null;
        } else {
          ruleFormData.recipientUserId = null;
        }
        // 后端如返回审批模板ID，则回显（字段为 templateId）
        ruleFormData.approvalTemplateId = res.templateId ?? null;
        // 审核不通过原因（只读展示，后端字段为 rejectReson），仅在审核不通过时展示内容
        ruleFormData.returnReason = res.status === -1 ? res.rejectReson ?? '' : '';
      }
      cloneRuleFormData();
    } catch (e) {
      console.error('获取奖品领取记录详情失败:', e);
      ElMessage.error(e?.message || e?.data || '获取详情失败');
    }
  };

  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;

    // 与应急预案保持一致的“添加/修改”提示文案
    const message = isCreateMode.value ? '添加' : '修改';

    try {
      const selectedInventory = inventoryList.value.find((item) => {
        return item.id === ruleFormData.itemId || item.id === ReceiptRecordData.value.pimId;
      });
      if (!selectedInventory) {
        ElMessage.error('请选择有效的奖品名称');
        return;
      }

      // const selectedUser = recipientUserList.value.find((user) => user.id === ruleFormData.recipientUserId);
      // console.log(selectedUser,'selectedUser')
      // if (!selectedUser) {
      //   ElMessage.error('请选择有效的领取人');
      //   return;
      // }

      const basePayload = {
        stuffName: selectedInventory.stuffName,
        pimId: selectedInventory.id,
        outStoreTime: ruleFormData.outboundDate ? new Date(ruleFormData.outboundDate).toISOString() : '',
        claimQty: ruleFormData.outboundQuantity,
        orderNumber: ruleFormData.receiptNumber,
        // deptName: ruleFormData.department,
        // deptId: ruleFormData.deptId ?? undefined,
        // userName: selectedUser.realname,
        // userId: selectedUser.id, // 领取人用户ID
        remark: '',
        // 审批流程ID在与后端交互时字段名为 templateId
        templateId: ruleFormData.approvalTemplateId ?? undefined,
      };

      if (isCreateMode.value) {
        const createRes = await saveClaimItemsLog(basePayload);
        // 兼容多种返回结构，优先使用数字ID
        receiptRecordId.value =
          typeof createRes === 'number'
            ? createRes
            : createRes && typeof createRes === 'object' && 'id' in createRes
            ? (createRes as any).id
            : undefined;
      } else if (isEditMode.value && currentId.value) {
        await updateClaimItemsLog({
          id: currentId.value,
          ...basePayload,
        });
        receiptRecordId.value = currentId.value;
      }
      ElMessage.success(`${message}成功`);
      if (ruleFormData.approvalTemplateId) {
        await getApprovalNode(ruleFormData.approvalTemplateId);
        basicDialogRef.value?.openDialog();
      }
    } catch (e) {
      console.error('保存奖品领取记录失败:', e);
      ElMessage.error(e?.message || e?.data || '保存失败，请重试');
    }
  };

  const handleSubmitApproval = () => {
    approvalFormRef.value?.validate(async (valid: boolean) => {
      if (!valid) return;
      if (!receiptRecordId.value) {
        ElMessage.error('缺少奖品领取记录ID，无法提交审批');
        return;
      }

      const approvalData = {
        planId: receiptRecordId.value,
        approvalDescription: approvalForm.description,
        approvalInfoList: approvalNodeList.value.map((node) => {
          let approverIdList: number[] = [];
          if (node.approverType === APPROVER_TYPE.FIX) {
            approverIdList = node.approverInfoList.map((info) => info.approverId);
          } else if (approvalForm.approvers[node.id]) {
            approverIdList = approvalForm.approvers[node.id];
          }
          return {
            approvalOrder: node.approvalOrder,
            approverIdList,
          };
        }),
      };

      try {
        await submitReceiptRecordApprovalProcess(approvalData);
        ElMessage.success('提交成功');
        closeApprovalDialog();
        router.back();
      } catch (e) {
        console.error('提交审批失败:', e);
        ElMessage.error(e?.message || e?.data || '提交审批失败，请重试');
      }
    });
  };

  const handleAuditPass = async () => {
    if (!currentId.value) return;
    try {
      await updateClaimItemsLogAgree(currentId.value);
      ElMessage.success('审核通过');
      router.back();
    } catch (e) {
      console.error('审核失败:', e);
      ElMessage.error(e?.message || e?.data || '审核失败，请重试');
    }
  };

  const handleAuditReject = async () => {
    if (!currentId.value) return;
    try {
      await updateClaimItemsLogReject(currentId.value);
      ElMessage.success('已审核不通过');
      router.back();
    } catch (e) {
      console.error('审核失败:', e);
      ElMessage.error(e?.message || e?.data || '审核失败，请重试');
    }
  };

  onMounted(async () => {
    cloneRuleFormData();
    await Promise.all([getDeptTreeData(), getInventoryList(), getApprovalList()]);
    if (isEditMode.value || isViewMode.value || isAuditMode.value) {
      await getDetail();
    }
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
</style>
