<template>
  <div class="project-budget-container" v-loading="loading">
    <!-- 审批按钮组件 -->
    <approvalButton
      @submitForm="handleSave"
      @approvalVerifyOpen="approvalVerifyOpen"
      @handleApprovalRecord="handleApprovalRecord"
      :buttonLoading="buttonLoading"
      :id="searchForm.budgetId"
      :status="searchForm.flowStatus"
      :pageType="routeParams.type"
      :mode="false"
    />
    <!-- 顶部表单区域 -->
    <el-card class="mb-6">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="项目号">
              <el-input
                v-model="searchForm.projectCode"
                :placeholder="isTopFormReadonly ? '' : '请选择项目'"
                :disabled="isTopFormReadonly"
                :readonly="!isTopFormReadonly"
                :suffix-icon="isTopFormReadonly ? undefined : 'Search'"
                @click="onProjectCodeInputClick"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目名称">
              <el-input v-model="searchForm.projectName" placeholder="请选择项目后自动填充" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="版本号">
              <el-input v-model="searchForm.budgetVersion" disabled> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请说明">
              <el-input v-model="searchForm.remark" type="textarea" placeholder="请输入申请说明" :disabled="isTopFormReadonly" />
            </el-form-item>
          </el-col>

          <!--          <el-col :span="12" class="text-right">-->
          <!--            <el-button type="primary" @click="exportBudget" size="default">-->
          <!--              <el-icon><Download /></el-icon>-->
          <!--              导出-->
          <!--            </el-button>-->
          <!--          </el-col>-->
        </el-row>
      </el-form>
    </el-card>

    <!-- 中间标签页区域 -->
    <!-- 研发项目预算 -->
    <el-card class="mb-6" v-if="isRdBudgetCategory(searchForm.projectCategory)">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="预算编制标准说明" name="budgetDefinition">
          <RdBudgetDefinition ref="rdBudgetDefinitionRef" :projectId="searchForm.projectId" />
        </el-tab-pane>
        <el-tab-pane label="表1-预算汇总" name="budgetTable">
          <RdBudgetTable
            ref="rdBudgetTableRef"
            :projectId="searchForm.projectId"
            :costData="costData"
            :projectInfo="projectInfo"
            :userList="userList"
          />
        </el-tab-pane>
        <el-tab-pane label="表2-材料费" name="materialCost">
          <RdMaterialCost ref="rdMaterialCostRef" :projectId="searchForm.projectId" />
        </el-tab-pane>
        <el-tab-pane label="表3-人工费" name="laborService">
          <RdLaborService ref="rdLaborServiceRef" :projectId="searchForm.projectId" />
        </el-tab-pane>
        <el-tab-pane label="表4-差旅费" name="travelMeetingExchange">
          <RdTravelMeetingExchange ref="rdTravelMeetingExchangeRef" :projectId="searchForm.projectId" />
        </el-tab-pane>
        <el-tab-pane label="表5-测试化验加工费" name="testingCost">
          <RdTestingCost ref="rdTestingCostRef" :projectId="searchForm.projectId" />
        </el-tab-pane>
        <el-tab-pane label="表6-咨询费、设计费" name="techCost">
          <RdTechCost ref="rdTechCostRef" :projectId="searchForm.projectId" />
        </el-tab-pane>
        <el-tab-pane label="表7-其他费用" name="otherCost">
          <RdOtherCost ref="rdOtherCostRef" :projectId="searchForm.projectId" />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 市场项目预算 -->
    <el-card
      class="mb-6"
      shadow="never"
      v-if="isMarketBudgetCategory(searchForm.projectCategory)"
    >
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="预算表" name="budget">
          <BudgetTable ref="budgetTableRef" :projectInfo="projectInfo" :userList="userList" />
        </el-tab-pane>
        <el-tab-pane label="材料费" name="material">
          <MaterialCost ref="materialCostRef" :budgetId="budgetId" />
        </el-tab-pane>
        <el-tab-pane label="人工费" name="labor">
          <LaborCost ref="laborCostRef" />
        </el-tab-pane>
        <el-tab-pane label="安装费" name="installation">
          <InstallationCost ref="installationCostRef" />
        </el-tab-pane>
        <el-tab-pane label="差旅费" name="travel">
          <TravelCost ref="travelCostRef" />
        </el-tab-pane>
        <el-tab-pane label="其他" name="other">
          <OtherCost ref="otherCostRef" />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 项目选择弹窗 -->
    <el-dialog v-model="projectSelectDialogVisible" title="选择项目" width="880px">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
              <el-form-item label="项目号" prop="projectCode">
                <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="项目名称" prop="projectName">
                <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="项目状态" prop="projectStatus">
                <el-select v-model="queryParams.projectStatus" placeholder="请选择项目状态" clearable>
                  <el-option v-for="dict in project_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </transition>

      <el-table :data="projectList" border @row-click="selectProject" style="width: 100%" v-loading="projectLoading" highlight-current-row>
        <el-table-column prop="projectCode" label="项目号" width="150" />
        <el-table-column prop="projectName" label="项目名称" min-width="180" />
        <el-table-column prop="businessDirection" label="业务方向" width="120">
          <template #default="scope">
            <dict-tag :options="business_direction" :value="scope.row.businessDirection" />
          </template>
        </el-table-column>
        <el-table-column prop="projectCategory" label="项目类别" width="160">
          <template #default="scope">
            <dict-tag :options="project_category" :value="scope.row.projectCategory" />
          </template>
        </el-table-column>
        <el-table-column prop="projectStatus" label="项目状态" width="100">
          <template #default="scope">
            <dict-tag :options="project_status" :value="scope.row.projectStatus" />
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-4 flex justify-between items-center">
        <pagination
          v-show="projectTotal > 0"
          :total="projectTotal"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getProjectList"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="projectSelectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmProjectSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提交审批组件 -->
    <submitVerify ref="submitVerifyRef" @submit-callback="submitCallback" />
    <!-- 审批记录 -->
    <approvalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup lang="ts" name="BudgetInfoEdit">
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import {
  listProjectInfo,
  addErpBudgetInfo,
  updateErpBudgetInfo,
  changeErpBudgetInfo,
  getErpBudgetInfo,
  getRdBudgetDefinitionList
} from '@/api/oa/erp/budgetInfo';
import { ProjectInfoVO, ProjectInfoQuery } from '@/api/oa/erp/projectInfo/types';
import { getUserList } from '@/api/system/user';

import { deepEqualArrays } from '@/utils/objHandle';
import { cloneDeep } from 'lodash-es';
import { ProjectCategoryEnum } from '@/enums/OAEnum';

const router = useRouter();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { business_direction, project_status, project_category } = toRefs<any>(
  proxy?.useDict('business_direction', 'project_status', 'project_category')
);

//研发项目tab
import RdBudgetDefinition from './rd/BudgetDefinition.vue';
import RdBudgetTable from './rd/BudgetTable.vue';
import RdMaterialCost from './rd/MaterialCost.vue';
import RdTravelMeetingExchange from './rd/TravelMeetingExchange.vue';
import RdLaborService from './rd/LaborService.vue';
import RdTechCost from './rd/TechCost.vue';
import RdTestingCost from './rd/TestingCost.vue';
import RdOtherCost from './rd/OtherCost.vue';

//市场项目tab
import BudgetTable from './market/BudgetTable.vue';
import MaterialCost from './market/MaterialCost.vue';
import LaborCost from './market/LaborCost.vue';
import InstallationCost from './market/InstallationCost.vue';
import TravelCost from './market/TravelCost.vue';
import OtherCost from './market/OtherCost.vue';

const loading = ref(true);

// 定义成本数据类型
interface CostData {
  equipmentCost: number;
  materialCost: number;
  travelCost: number;
  meetingCost: number;
  internationalExchangeCost: number;
  consultingDevelopmentCost: number;
  laborCost: number;
  serviceCost: number;
  literatureCost: number;
  testingCost: number;
  otherCost: number;
}

// 研发项目预算tab组件引用
const rdBudgetDefinitionRef = ref();
const rdBudgetTableRef = ref();
const rdMaterialCostRef = ref();
const rdTravelMeetingExchangeRef = ref();
const rdLaborServiceRef = ref();
const rdTechCostRef = ref();
const rdTestingCostRef = ref();
const rdOtherCostRef = ref();

// 市场项目预算tab组件引用
const budgetTableRef = ref();
const materialCostRef = ref();
const laborCostRef = ref();
const installationCostRef = ref();
const travelCostRef = ref();
const otherCostRef = ref();

const oriBudgetMaterialCostList = ref<budgetMaterialCostVO[]>([]);
const oriBudgetLaborCostList = ref<budgetLaborCostVO[]>([]);
const oriBudgetInstallCostList = ref<budgetInstallCostVO[]>([]);
const oriBudgetTravelCostList = ref<budgetTravelCostVO[]>([]);
const oriBudgetOtherCostList = ref<budgetOtherCostVO[]>([]);

const oriRdBudgetMaterialCostList = ref<rdBudgetMaterialCostVO[]>([]);
const oriRdBudgetLaborCostList = ref<rdBudgetLaborCostVO[]>([]); //人工费
const oriRdBudgetTravelCostList = ref<rdBudgetTravelCostVO[]>([]); //差旅费-差旅费
const oriRdBudgetTransportationCostList = ref<rdBudgetTravelCostVO[]>([]); //差旅费-交通费
const oriRdBudgetTestingCostList = ref<rdBudgetTestingCostVO[]>([]); //测试化验加工费
const oriRdBudgetTechConsultCostList = ref<rdBudgetTechCostVO[]>([]); //新产品设计费
const oriRdBudgetExpertMeetingCostList = ref<rdBudgetTechCostVO[]>([]); //专家咨询会议形式
const oriRdBudgetExpertCommCostList = ref<rdBudgetTechCostVO[]>([]); //专家咨询通讯形式
const oriRdBudgetOtherCostList = ref<rdBudgetOtherCostVO[]>([]); //其他费用

/** 研发 / 预投（与字典 project_category、OAEnum 一致） */
function isRdBudgetCategory(category: string | number | undefined | null): boolean {
  const c = category === undefined || category === null ? '' : String(category);
  return c === ProjectCategoryEnum.RD || c === ProjectCategoryEnum.PRE_INVEST;
}

/** 销售实施、物流、备件（与列表页 index 及 OAEnum 一致；含类别 0，避免选「实施」项目后无表单） */
function isMarketBudgetCategory(category: string | number | undefined | null): boolean {
  const c = category === undefined || category === null ? '' : String(category);
  return (
    c === ProjectCategoryEnum.SALE_IMPLEMENT ||
    c === ProjectCategoryEnum.SALE_LOGISTICS ||
    c === ProjectCategoryEnum.SALE_SPARE
  );
}

const BUSINESS_STATUS = reactive({
  DRAFT: '1', //暂存
  WAITING: '2', //审批中
  AVAILABLE: '3' //可用
});

const TECH_TYPE = reactive({
  TECH_CONSULT: '1', //新产品设计费
  EXPERT_MEETING: '2', //专家咨询-会议形式
  EXPERT_COMM: '3' //专家咨询-通讯形式
});

const TRIP_TYPE = {
  TRAVEL: '1', //差旅费
  TRANSPORTATION: '2' //交通费
};

// 响应式数据
// 将activeTab从computed改为ref，使其可变
const activeTab = ref('budget');
const buttonLoading = ref(false);

const searchForm = reactive({
  budgetId: undefined,
  projectId: '',
  projectName: '',
  projectCode: '',
  projectCategory: '',
  flowStatus: '',
  budgetVersion: 1,
  remark: ''
});

// 监听项目类别变化，更新默认标签页
watch(
  () => searchForm.projectCategory,
  (newCategory) => {
    if (isRdBudgetCategory(newCategory as string)) {
      activeTab.value = 'budgetTable';
    } else if (isMarketBudgetCategory(newCategory as string)) {
      activeTab.value = 'budget';
    }
  }
);

// 项目信息
const projectInfo = reactive<Partial<ProjectInfoVO>>({
  projectId: undefined,
  projectName: '',
  projectCode: '',
  projectCategory: '',
  managerId: undefined,
  amount: undefined
});

// 研发预算成本数据
const costData = reactive<CostData>({
  equipmentCost: 0,
  materialCost: 0,
  travelCost: 0,
  meetingCost: 0,
  internationalExchangeCost: 0,
  consultingDevelopmentCost: 0,
  laborCost: 0,
  serviceCost: 0,
  literatureCost: 0,
  testingCost: 0,
  otherCost: 0
});

const userList = ref<UserVO[]>([]);
/** 查询用户列表 */
const getUsers = async () => {
  const res = await getUserList({});
  userList.value = res.data;
};

// 项目选择弹窗相关
const projectSelectDialogVisible = ref(false);
const selectedProject = ref<ProjectInfoVO | null>(null);
const projectList = ref<ProjectInfoVO[]>([]);
const projectTotal = ref(0);
const projectLoading = ref(true);
const data = reactive<{ queryParams: ProjectInfoQuery }>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractFlag: undefined,
    projectCode: undefined,
    projectName: undefined,
    businessDirection: undefined,
    projectCategory: undefined,
    spareFlag: undefined,
    projectTypeId: undefined,
    paymentMethod: undefined,
    deptId: undefined,
    managerId: undefined,
    chargeId: undefined,
    deputyId: undefined,
    peopleId: undefined,
    amount: undefined,
    projectStatus: undefined,
    flowStatus: undefined,
    sortOrder: undefined,
    contractId: undefined,
    activeFlag: undefined,
    params: {}
  }
});

const { queryParams } = toRefs(data);

const queryFormRef = ref<ElFormInstance>();

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getProjectList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 查询项目信息列表 */
const getProjectList = async () => {
  projectLoading.value = true;
  const res = await listProjectInfo(queryParams.value);
  projectList.value = res.rows;
  projectTotal.value = res.total;
  projectLoading.value = false;
};

// 标签页切换处理
const handleTabClick = (tab: any) => {
  activeTab.value = tab.paneName;
  if ((budgetId.value && routeParams.value.type === 'update') || !budgetId.value) {
    if (isRdBudgetCategory(searchForm.projectCategory)) {
      updateRdBudgetTable();
    } else if (isMarketBudgetCategory(searchForm.projectCategory)) {
      updateBudgetTable();
    }
  }
};

// 显示项目选择弹窗
const showProjectSelectDialog = () => {
  projectSelectDialogVisible.value = true;
  selectedProject.value = undefined;
  getProjectList();
};

// 选择项目
const selectProject = (row: ProjectInfoVO) => {
  selectedProject.value = row;
};

// 确认项目选择
const confirmProjectSelection = () => {
  if (!selectedProject.value) {
    ElMessage.warning('请选择一个项目');
    return;
  }

  // 更新项目信息
  searchForm.projectId = selectedProject.value.projectId;
  searchForm.projectName = selectedProject.value.projectName;
  searchForm.projectCode = selectedProject.value.projectCode;
  searchForm.projectCategory = selectedProject.value.projectCategory;

  projectInfo.projectId = selectedProject.value.projectId;
  projectInfo.projectName = selectedProject.value.projectName;
  projectInfo.projectCode = selectedProject.value.projectCode;
  projectInfo.projectCategory = selectedProject.value.projectCategory;
  projectInfo.managerId = selectedProject.value.managerId;
  projectInfo.amount = selectedProject.value.amount;

  projectSelectDialogVisible.value = false;
  // ElMessage.success('项目选择成功');

  // 重置所有成本数据
  Object.keys(costData).forEach((key) => {
    costData[key as keyof CostData] = 0;
  });
};

// 更新市场项目预算预算表数据
const updateBudgetTable = async () => {
  if (!budgetTableRef.value) return;

  // 获取各tab页的合计数据
  const materialTotal = materialCostRef.value?.getTotalAmount() || { budgetAmount: 0, reducedAmount: 0 };
  const laborTotal = laborCostRef.value?.getTotalAmount() || { budgetAmount: 0, reducedAmount: 0 };
  const installationTotal = installationCostRef.value?.getTotalAmount() || { budgetAmount: 0, reducedAmount: 0 };
  const travelTotal = travelCostRef.value?.getTotalAmount() || { budgetAmount: 0, reducedAmount: 0 };
  const otherTotal = otherCostRef.value?.getTotalAmount() || { budgetAmount: 0, reducedAmount: 0 };

  // 更新预算表,目前是按单位是万元传值，后续如果根据单位是元，则在此判断更新传的值
  budgetTableRef.value.updateBudgetDetailData('材料费', materialTotal.budgetAmount, materialTotal.reducedAmount);
  budgetTableRef.value.updateBudgetDetailData('人工费', laborTotal.budgetAmount, laborTotal.reducedAmount);
  budgetTableRef.value.updateBudgetDetailData('安装费', installationTotal.budgetAmount, installationTotal.reducedAmount);
  budgetTableRef.value.updateBudgetDetailData('差旅费', travelTotal.budgetAmount, travelTotal.reducedAmount);
  budgetTableRef.value.updateBudgetDetailData('其他费用', otherTotal.budgetAmount, otherTotal.reducedAmount);
};

// 更新研发项目预算预算表数据
const updateRdBudgetTable = async () => {
  // 获取各tab页的合计数据
  const materialTotal = rdMaterialCostRef.value?.getTotalAmount() || 0;
  const laborAmount = rdLaborServiceRef.value?.getLaborAmount();
  const laborTotal = laborAmount.laborTotal || 0;

  const techCost = rdTechCostRef.value?.getTechAmount() || 0;
  const expertConsultTotal = techCost.expertConsultTotal || 0;
  const techConsultTotal = techCost.techConsultTotal || 0;

  const travelMeetingExchangeAmount = rdTravelMeetingExchangeRef.value?.getTravelAmount();
  const travelTotal = travelMeetingExchangeAmount.travelSubtotalTotal || 0;
  const testingCost = rdTestingCostRef.value?.getTestingAmount() || 0;
  const testingTotal = testingCost.testingTotal || 0;
  const otherCost = rdOtherCostRef.value?.getOtherCost() || 0;
  const otherTotal = otherCost.otherTotal || 0;

  // 更新预算表,目前是按单位是万元传值，后续如果根据单位是元，则在此判断更新传的值
  rdBudgetTableRef.value.updateRdBudgetDetailData('材料费', materialTotal);
  rdBudgetTableRef.value.updateRdBudgetDetailData('人工费', laborTotal);
  rdBudgetTableRef.value.updateRdBudgetDetailData('差旅费', travelTotal);
  rdBudgetTableRef.value.updateRdBudgetDetailData('测试化验加工费', testingTotal);
  rdBudgetTableRef.value.updateRdBudgetDetailData('专家咨询费用', expertConsultTotal);
  rdBudgetTableRef.value.updateRdBudgetDetailData('新产品设计费', techConsultTotal);
  rdBudgetTableRef.value.updateRdBudgetDetailData('其他费用', otherTotal);
};

// 提取用户查找逻辑
const findUserName = (userList: any[], userId: number): string => {
  const user = userList?.find((item) => item.userId === userId);
  return user?.nickName || '';
};

// 提取数据比较和赋值逻辑
const assignIfChanged = (targetArray: any[], sourceArray: any[], originalArray: any[]): any[] => {
  return !deepEqualArrays(originalArray, sourceArray) ? sourceArray || [] : [];
};

const handleSave = async (status: string, mode: boolean) => {
  if (!searchForm.projectId) {
    ElMessage.warning('请先选择项目');
    return;
  }

  try {
    buttonLoading.value = true;

    const isRdProject = isRdBudgetCategory(searchForm.projectCategory);
    const isMarketProject = isMarketBudgetCategory(searchForm.projectCategory);

    let budgetForm: budgetInfoForm = {};

    if (isRdProject) {
      budgetForm = await processRdBudgetForm(status);
    } else if (isMarketProject) {
      budgetForm = await processMarketBudgetForm(status);
    } else {
      ElMessage.warning('不支持的预算类型');
      return;
    }
    budgetForm.budgetVersion = searchForm.budgetVersion;
    budgetForm.remark = searchForm.remark;

    // 统一保存逻辑
    if (budgetForm.budgetId) {
      await updateErpBudgetInfo(budgetForm);
    } else {
      if (routeParams.value.changeFlag === '1') {
        await changeErpBudgetInfo(budgetForm);
      } else {
        budgetForm.budgetVersion = 1;
        await addErpBudgetInfo(budgetForm);
      }
    }

    ElMessage.success('操作成功');
    handleSaveSuccess();
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  } finally {
    buttonLoading.value = false;
  }
};

// 处理研发预算表单
const processRdBudgetForm = async (status: string): Promise<budgetInfoForm> => {
  await updateRdBudgetTable();

  const budgetDetailData = rdBudgetTableRef.value?.budgetDetailData || [];
  const rdBudgetInfoForm = rdBudgetTableRef.value?.rdBudgetInfoForm || {};
  rdBudgetInfoForm.budgetCost = rdBudgetTableRef.value?.totalAmount;

  // 合并表单数据
  const budgetForm = {
    ...rdBudgetInfoForm,
    // 设置状态
    budgetStatus: getBudgetStatus(status),
    flowStatus: getFlowStatus(status),
    // 设置负责人信息
    managerName: findUserName(userList.value, rdBudgetInfoForm.managerId),
    productManagerName: findUserName(userList.value, rdBudgetInfoForm.productManagerId),
    approveUserName: findUserName(userList.value, rdBudgetInfoForm.approveUserId),
    // 预算详情
    erpBudgetDetailList: budgetDetailData,
    // 初始化所有成本列表
    ...initializeRdCostLists()
  };

  // 处理各项成本数据
  processRdCostData(budgetForm);

  // 如果有预算ID，设置要删除的列表
  if (budgetForm.budgetId) {
    setRdToDeletedLists(budgetForm);
  }

  return budgetForm;
};

// 处理市场预算表单
const processMarketBudgetForm = async (status: string): Promise<budgetInfoForm> => {
  await updateBudgetTable();

  const budgetDetailData = budgetTableRef.value?.budgetDetailData || [];
  const budgetFormData = budgetTableRef.value?.budgetForm || {};

  const budgetForm = {
    ...budgetFormData,
    budgetStatus: getBudgetStatus(status),
    flowStatus: getFlowStatus(status),
    managerName: findUserName(userList.value, budgetFormData.managerId),
    productManagerName: findUserName(userList.value, budgetFormData.productManagerId),
    erpBudgetDetailList: budgetDetailData,
    // 初始化市场预算成本列表
    ...initializeMarketCostLists()
  };

  // 处理市场预算成本数据
  processMarketCostData(budgetForm);

  // 如果有预算ID，设置要删除的列表
  if (budgetForm.budgetId) {
    setMarketToDeletedLists(budgetForm);
  }

  return budgetForm;
};

// 辅助函数
const getBudgetStatus = (status: string): string => {
  return status === 'draft' ? BUSINESS_STATUS.DRAFT : BUSINESS_STATUS.WAITING;
};

const getFlowStatus = (status: string): string => {
  return status === 'draft' ? 'draft' : 'waiting';
};

const initializeRdCostLists = () => ({
  erpRdBudgetMaterialCostList: [],
  erpRdBudgetLaborCostList: [],
  erpRdBudgetTravelCostList: [],
  erpRdBudgetTestingCostList: [],
  erpRdBudgetTechCostList: [],
  erpRdBudgetOtherCostList: []
});

const initializeMarketCostLists = () => ({
  erpBudgetMaterialCostList: [],
  erpBudgetLaborCostList: [],
  erpBudgetInstallCostList: [],
  erpBudgetTravelCostList: [],
  erpBudgetOtherCostList: []
});

// 处理研发成本数据
const processRdCostData = (budgetForm: budgetInfoForm) => {
  // 设备成本
  console.log(oriRdBudgetMaterialCostList.value);
  // 材料成本
  if (assignIfChanged([], rdMaterialCostRef.value?.materialData, oriRdBudgetMaterialCostList.value).length) {
    budgetForm.erpRdBudgetMaterialCostList = rdMaterialCostRef.value?.materialData || [];
  }

  // 人工成本
  if (assignIfChanged([], rdLaborServiceRef.value?.laborList, oriRdBudgetLaborCostList.value).length) {
    budgetForm.erpRdBudgetLaborCostList = rdLaborServiceRef.value?.laborList || [];
  }

  // 差旅费成本
  budgetForm.erpRdBudgetTravelCostList = [
    ...assignIfChanged([], rdTravelMeetingExchangeRef.value?.travelList, oriRdBudgetTravelCostList.value),
    ...assignIfChanged([], rdTravelMeetingExchangeRef.value?.transportationList, oriRdBudgetTransportationCostList.value)
  ];

  // 测试化验加工成本
  if (assignIfChanged([], rdTestingCostRef.value?.testData, oriRdBudgetTestingCostList.value).length) {
    budgetForm.erpRdBudgetTestingCostList = rdTestingCostRef.value?.testData || [];
  }

  // 咨询费、设计费
  budgetForm.erpRdBudgetTechCostList = [
    ...assignIfChanged([], rdTechCostRef.value?.techConsultList, oriRdBudgetTechConsultCostList.value),
    ...assignIfChanged([], rdTechCostRef.value?.expertMeetingList, oriRdBudgetExpertMeetingCostList.value),
    ...assignIfChanged([], rdTechCostRef.value?.expertCommList, oriRdBudgetExpertCommCostList.value)
  ];

  // 其他成本
  if (assignIfChanged([], rdOtherCostRef.value?.otherCostList, oriRdBudgetOtherCostList.value).length) {
    budgetForm.erpRdBudgetOtherCostList = rdOtherCostRef.value?.otherCostList || [];
  }
};

// 设置研发删除列表
const setRdToDeletedLists = (budgetForm: budgetInfoForm) => {
  const refs = {
    material: rdMaterialCostRef.value,
    travelMeetingExchange: rdTravelMeetingExchangeRef.value,
    laborService: rdLaborServiceRef.value,
    testing: rdTestingCostRef.value,
    tech: rdTechCostRef.value,
    other: rdOtherCostRef.value
  };

  budgetForm.toDeletedRdMaterialCostIdList = refs.material?.toDeletedMaterialCostIdList;
  budgetForm.toDeletedRdLaborCostIdList = refs.laborService?.toDeletedLaborCostIdList;
  budgetForm.toDeletedRdTravelCostIdList = refs.travelMeetingExchange?.toDeletedTravelCostIdList;
  budgetForm.toDeletedRdTestingCostIdList = refs.testing?.toDeletedTestCostIdList;
  budgetForm.toDeletedRdTechCostIdList = refs.tech?.toDeletedTechCostIdList;
  budgetForm.toDeletedRdOtherCostIdList = refs.other?.toDeletedOtherCostIdList;
};

// 处理市场成本数据
const processMarketCostData = (budgetForm: budgetInfoForm) => {
  const assignCostData = (targetKey: keyof budgetInfoForm, sourceData: any[], originalData: any[]) => {
    if (!deepEqualArrays(originalData, sourceData)) {
      budgetForm[targetKey] = sourceData || [];
    }
  };

  assignCostData('erpBudgetMaterialCostList', materialCostRef.value?.budgetMaterialCostList, oriBudgetMaterialCostList.value);
  assignCostData('erpBudgetLaborCostList', laborCostRef.value?.budgetLaborCostList, oriBudgetLaborCostList.value);
  assignCostData('erpBudgetInstallCostList', installationCostRef.value?.installCostList, oriBudgetInstallCostList.value);
  assignCostData('erpBudgetTravelCostList', travelCostRef.value?.travelCostList, oriBudgetTravelCostList.value);
  assignCostData('erpBudgetOtherCostList', otherCostRef.value?.otherCostList, oriBudgetOtherCostList.value);
};

// 设置市场删除列表
const setMarketToDeletedLists = (budgetForm: budgetInfoForm) => {
  budgetForm.toDeletedMaterialCostIdList = materialCostRef.value?.toDeletedMaterialCostIdList;
  budgetForm.toDeletedLaborCostIdList = laborCostRef.value?.toDeletedLaborCostIdList;
  budgetForm.toDeletedInstallCostIdList = installationCostRef.value?.toDeletedInstallCostIdList;
  budgetForm.toDeletedTravelCostIdList = travelCostRef.value?.toDeletedTravelCostIdList;
  budgetForm.toDeletedOtherCostIdList = otherCostRef.value?.toDeletedOtherCostIdList;
};

// 保存成功处理
const handleSaveSuccess = () => {
  const obj = {
    path: '/budget/erp/budgetInfo',
    query: {
      t: Date.now(),
      pageNum: routeParams.value.pageNum
    }
  };
  proxy?.$tab.closeOpenPage(obj);
};

// 关闭页面
const handleClose = () => {
  // 可以添加确认对话框
  // 这里简单实现返回上一页
  window.history.back();
};

const route = useRoute();
const budgetId = ref();

/** 查看、审批：顶部基础信息只读（与 route.query.type 一致） */
const isTopFormReadonly = computed(() => {
  const t = route.query.type as string | undefined;
  return t === 'view' || t === 'approval';
});

const onProjectCodeInputClick = () => {
  if (isTopFormReadonly.value) return;
  showProjectSelectDialog();
};

// 初始化
// 定义不同类型的主键字段映射
const PRIMARY_KEY_MAP = {
  // 研发预算相关
  erpRdBudgetMaterialCostList: 'materialCostId',
  erpRdBudgetTravelCostList: 'travelCostId',
  erpRdBudgetTechCostList: 'techCostId',
  erpRdBudgetLaborCostList: 'laborCostId',
  erpRdBudgetTestingCostList: 'testingCostId',
  erpRdBudgetOtherCostList: 'otherCostId',

  // 市场预算相关
  erpBudgetMaterialCostList: 'materialCostId',
  erpBudgetLaborCostList: 'laborCostId',
  erpBudgetInstallCostList: 'installCostId',
  erpBudgetTravelCostList: 'travelCostId',
  erpBudgetOtherCostList: 'otherCostId',

  // 预算明细
  erpBudgetDetailList: 'budgetDetailId',
  erpBudgetInfo: 'budgetId',

  // 默认主键
  default: 'id'
} as const;

// 定义需要删除的通用字段
const COMMON_FIELDS_TO_REMOVE = ['budgetId', 'createDept', 'createBy', 'createTime', 'updateBy', 'updateTime', 'delFlag'];

onMounted(() => {
  nextTick(async () => {
    await loadBudgetData();
  });
});

async function loadBudgetData() {
  routeParams.value = route.query;
  budgetId.value = routeParams.value.id as string | number;

  await getUsers();

  if (!budgetId.value || !['update', 'view', 'approval'].includes(routeParams.value.type as string)) {
    await handleAddMode();
  } else {
    await handleLoadMode();
  }
  loading.value = false;
}

async function handleAddMode() {
  const raw = routeParams.value.projectCategory;
  searchForm.projectCategory = raw === undefined || raw === null || raw === '' ? '' : String(raw);
  queryParams.value.projectCategory = searchForm.projectCategory || undefined;
  if (isRdBudgetCategory(searchForm.projectCategory)) {
    const rdBudgetDefinitionListData = await getRdBudgetDefinitionList();
    if (rdBudgetDefinitionRef.value.budgetDefinitionData) {
      rdBudgetDefinitionRef.value.budgetDefinitionData = rdBudgetDefinitionListData.data;
    }
  }
}

async function handleLoadMode() {
  proxy?.$modal.loading('正在加载数据，请稍后...');

  try {
    const res = await getErpBudgetInfo(budgetId.value);
    Object.assign(searchForm, res.data);
    if (routeParams.value.changeFlag === '1') {
      searchForm.flowStatus = 'draft';
      searchForm.budgetVersion = (searchForm.budgetVersion || 0) + 1;
    }

    if (isRdBudgetCategory(searchForm.projectCategory)) {
      await handleRdOrPreProductionData(res.data);
    } else if (isMarketBudgetCategory(searchForm.projectCategory)) {
      await handleMarketCategoryData(res.data);
    }
  } finally {
    proxy?.$modal.closeLoading();
  }
}

async function handleRdOrPreProductionData(data: any) {
  const isChangeType = routeParams.value.changeFlag === '1';

  // 只有在非变更类型时才初始化原始数据
  if (!isChangeType) {
    initOriginalRdData(data);
  }

  const groupedTechData = groupByField(data.erpRdBudgetTechCostList, 'techType');
  const groupedTravelData = groupByField(data.erpRdBudgetTravelCostList, 'tripType');
  // 获取并处理分类数据
  const categorizedData = {
    rdBudgetTravelCostList: handleChangeTypeIds(groupedTravelData[TRIP_TYPE.TRAVEL] || [], 'erpRdBudgetTravelCostList', isChangeType),
    rdBudgetTransportationCostList: handleChangeTypeIds(groupedTravelData[TRIP_TYPE.TRANSPORTATION] || [], 'erpRdBudgetTravelCostList', isChangeType),
    rdBudgetTechConsultCostList: handleChangeTypeIds(groupedTechData[TECH_TYPE.TECH_CONSULT] || [], 'erpRdBudgetTechCostList', isChangeType),
    rdBudgetExpertMeetingCostList: handleChangeTypeIds(groupedTechData[TECH_TYPE.EXPERT_MEETING] || [], 'erpRdBudgetTechCostList', isChangeType),
    rdBudgetExpertCommCostList: handleChangeTypeIds(groupedTechData[TECH_TYPE.EXPERT_COMM] || [], 'erpRdBudgetTechCostList', isChangeType)
  };

  await nextTick();

  assignRdDataToComponents(data, categorizedData, isChangeType);
}

async function handleMarketCategoryData(data: any) {
  const isChangeType = routeParams.value.changeFlag === '1';

  // 只有在非变更类型时才初始化原始数据
  if (!isChangeType) {
    initOriginalMarketData(data);
  }

  // 处理所有列表数据
  const processedLists = {
    materialCostList: handleChangeTypeIds(data.erpBudgetMaterialCostList, 'erpBudgetMaterialCostList', isChangeType),
    laborCostList: handleChangeTypeIds(data.erpBudgetLaborCostList, 'erpBudgetLaborCostList', isChangeType),
    installCostList: handleChangeTypeIds(data.erpBudgetInstallCostList, 'erpBudgetInstallCostList', isChangeType),
    travelCostList: handleChangeTypeIds(data.erpBudgetTravelCostList, 'erpBudgetTravelCostList', isChangeType),
    otherCostList: handleChangeTypeIds(data.erpBudgetOtherCostList, 'erpBudgetOtherCostList', isChangeType),
    detailList: handleChangeTypeIds(data.erpBudgetDetailList, 'erpBudgetDetailList', isChangeType)
  };

  await nextTick();

  assignMarketDataToComponents(data, processedLists, isChangeType);
}

// 根据字段名获取主键字段
function getPrimaryKeyField(listName: string): string {
  return PRIMARY_KEY_MAP[listName] || PRIMARY_KEY_MAP.default;
}

// 处理变更类型的数据：清空主键ID和相关字段
function handleChangeTypeIds(data: any[], listName: string, isChangeType: boolean): any[] {
  if (!isChangeType || !data || data.length === 0) {
    return data || [];
  }

  const primaryKey = getPrimaryKeyField(listName);

  return data.map((item) => {
    return processFormDataForChange(item, primaryKey);
  });
}

// 处理表单数据的变更逻辑
function processFormDataForChange(data: any, primaryKey: string): any {
  const processedData = { ...data };

  // 删除主键字段
  if (primaryKey in processedData) {
    delete processedData[primaryKey];
  }

  // 删除通用字段
  COMMON_FIELDS_TO_REMOVE.forEach((field) => {
    if (field in processedData) {
      delete processedData[field];
    }
  });

  // 删除所有以"Id"结尾的字段（通常是外键）
  // Object.keys(newItem).forEach((key) => {
  //   if (key.endsWith('Id') && key !== primaryKey) {
  //     delete newItem[key];
  //   }
  // });

  return processedData;
}

function groupByField(array: any[], field: string): Record<string, any[]> {
  if (!array) return {};

  return array.reduce((acc, item) => {
    const key = item[field];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(item);
    return acc;
  }, {});
}

function initOriginalRdData(data: any) {
  // 只保存原始数据，不处理变更逻辑
  oriRdBudgetMaterialCostList.value = deepClone(data.erpRdBudgetMaterialCostList);
  oriRdBudgetLaborCostList.value = deepClone(data.erpRdBudgetLaborCostList);
  oriRdBudgetTestingCostList.value = deepClone(data.erpRdBudgetTestingCostList);
  oriRdBudgetOtherCostList.value = deepClone(data.erpRdBudgetOtherCostList);

  // 处理差旅费分组后的数据
  if (data.erpRdBudgetTravelCostList) {
    const groupedTravelData = groupByField(data.erpRdBudgetTravelCostList, 'tripType');
    oriRdBudgetTravelCostList.value = deepClone(groupedTravelData[TRIP_TYPE.TRAVEL] || []);
    oriRdBudgetTransportationCostList.value = deepClone(groupedTravelData[TRIP_TYPE.TRANSPORTATION] || []);
  }

  // 处理咨询费分组后的数据
  if (data.erpRdBudgetTechCostList) {
    const groupedTechData = groupByField(data.erpRdBudgetTechCostList, 'techType');
    oriRdBudgetTechConsultCostList.value = deepClone(groupedTechData[TECH_TYPE.TECH_CONSULT] || []);
    oriRdBudgetExpertMeetingCostList.value = deepClone(groupedTechData[TECH_TYPE.EXPERT_MEETING] || []);
    oriRdBudgetExpertCommCostList.value = deepClone(groupedTechData[TECH_TYPE.EXPERT_COMM] || []);
  }
}

function initOriginalMarketData(data: any) {
  // 只保存原始数据，不处理变更逻辑
  oriBudgetMaterialCostList.value = deepClone(data.erpBudgetMaterialCostList);
  oriBudgetLaborCostList.value = deepClone(data.erpBudgetLaborCostList);
  oriBudgetInstallCostList.value = deepClone(data.erpBudgetInstallCostList);
  oriBudgetTravelCostList.value = deepClone(data.erpBudgetTravelCostList);
  oriBudgetOtherCostList.value = deepClone(data.erpBudgetOtherCostList);
}

// 研发数据赋值到组件
function assignRdDataToComponents(data: any, categorizedData: any, isChangeType: boolean) {
  if (!rdBudgetTableRef.value) return;

  // 处理基础表单数据 - 如果是变更类型，清空预算ID
  const formData = isChangeType ? processFormDataForChange(data, 'budgetId') : data;
  Object.assign(rdBudgetTableRef.value.rdBudgetInfoForm, formData);

  // 预算编制标准说明数据
  if (rdBudgetDefinitionRef.value.budgetDefinitionData) {
    rdBudgetDefinitionRef.value.budgetDefinitionData = data.budgetDefinitionDTOList;
  }

  // 处理预算明细数据
  const budgetDetailList = isChangeType
    ? handleChangeTypeIds(data.erpBudgetDetailList, 'erpBudgetDetailList', true)
    : deepClone(data.erpBudgetDetailList || []);

  // 预算明细数据
  if (rdBudgetTableRef.value.budgetDetailData) {
    rdBudgetTableRef.value.budgetDetailData = budgetDetailList;
  }

  // 材料费数据
  const materialData = isChangeType
    ? handleChangeTypeIds(data.erpRdBudgetMaterialCostList, 'erpRdBudgetMaterialCostList', true)
    : oriRdBudgetMaterialCostList.value;

  if (rdMaterialCostRef.value?.materialData) {
    rdMaterialCostRef.value.materialData = deepClone(materialData);
  }

  // 人工费
  const laborData = isChangeType
    ? handleChangeTypeIds(data.erpRdBudgetLaborCostList, 'erpRdBudgetLaborCostList', true)
    : oriRdBudgetLaborCostList.value;
  if (rdLaborServiceRef.value) {
    // 人工费
    if (rdLaborServiceRef.value.laborList) {
      rdLaborServiceRef.value.laborList = deepClone(laborData);
    }
  }

  // 差旅费数据
  if (rdTravelMeetingExchangeRef.value) {
    // 差旅费
    if (rdTravelMeetingExchangeRef.value.travelList) {
      rdTravelMeetingExchangeRef.value.travelList = deepClone(categorizedData.rdBudgetTravelCostList);
    }

    // 交通费
    if (rdTravelMeetingExchangeRef.value.transportationList) {
      rdTravelMeetingExchangeRef.value.transportationList = deepClone(categorizedData.rdBudgetTransportationCostList);
    }
  }

  // 测试/化验/加工费数据
  const testingData = isChangeType
    ? handleChangeTypeIds(data.erpRdBudgetTestingCostList, 'erpRdBudgetTestingCostList', true)
    : oriRdBudgetTestingCostList.value;

  if (rdTestingCostRef.value?.testData) {
    rdTestingCostRef.value.testData = deepClone(testingData);
  }

  // 咨询费、设计费
  if (rdTechCostRef.value) {
    // 技术咨询费
    if (rdTechCostRef.value.techConsultList) {
      rdTechCostRef.value.techConsultList = deepClone(categorizedData.rdBudgetTechConsultCostList);
    }

    // 专家咨询会议形式
    if (rdTechCostRef.value.expertMeetingList) {
      rdTechCostRef.value.expertMeetingList = deepClone(categorizedData.rdBudgetExpertMeetingCostList);
    }

    // 专家咨询通讯形式
    if (rdTechCostRef.value.expertCommList) {
      rdTechCostRef.value.expertCommList = deepClone(categorizedData.rdBudgetExpertCommCostList);
    }
  }

  // 其他费用数据
  const otherData = isChangeType
    ? handleChangeTypeIds(data.erpRdBudgetOtherCostList, 'erpRdBudgetOtherCostList', true)
    : oriRdBudgetOtherCostList.value;

  if (rdOtherCostRef.value?.otherCostList) {
    rdOtherCostRef.value.otherCostList = deepClone(otherData);
  }
}

// 修改 assignMarketDataToComponents 函数，增加 isChangeType 参数
function assignMarketDataToComponents(data: any, processedLists: any, isChangeType: boolean) {
  if (!budgetTableRef.value) return;

  // 基础表单数据
  const formData = isChangeType ? processFormDataForChange(data, 'budgetId') : data;
  Object.assign(budgetTableRef.value.budgetForm, formData);

  // 预算明细数据
  if (budgetTableRef.value.budgetDetailData) {
    budgetTableRef.value.budgetDetailData = deepClone(processedLists.detailList);
  }

  // 材料费数据
  if (materialCostRef.value?.budgetMaterialCostList) {
    materialCostRef.value.budgetMaterialCostList = deepClone(processedLists.materialCostList);
  }

  // 人工费数据
  if (laborCostRef.value?.budgetLaborCostList) {
    laborCostRef.value.budgetLaborCostList = deepClone(processedLists.laborCostList);
  }

  // 安装费数据
  if (installationCostRef.value?.installCostList) {
    installationCostRef.value.installCostList = deepClone(processedLists.installCostList);
  }

  // 差旅费数据
  if (travelCostRef.value?.travelCostList) {
    travelCostRef.value.travelCostList = deepClone(processedLists.travelCostList);
  }

  // 其他费用数据
  if (otherCostRef.value?.otherCostList) {
    otherCostRef.value.otherCostList = deepClone(processedLists.otherCostList);
  }
}

function deepClone<T>(obj: T): T {
  return cloneDeep(obj);
}

import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import ApprovalButton from '@/components/Process/approvalButton.vue';
import { budgetMaterialCostVO } from '@/api/oa/erp/budgetInfo/market/budgetMaterialCost/types';
import { budgetLaborCostVO } from '@/api/oa/erp/budgetInfo/market/budgetLaborCost/types';
import { budgetInstallCostVO } from '@/api/oa/erp/budgetInfo/market/budgetInstallCost/types';
import { budgetTravelCostVO } from '@/api/oa/erp/budgetInfo/market/budgetTravelCost/types';
import { budgetOtherCostVO } from '@/api/oa/erp/budgetInfo/market/budgetOtherCost/types';
import { budgetInfoForm } from '@/api/oa/erp/budgetInfo/types';
import { rdBudgetMaterialCostVO } from '@/api/oa/erp/budgetInfo/rd/rdBudgetMaterialCost/types';
import { rdBudgetTravelCostVO } from '@/api/oa/erp/budgetInfo/rd/rdBudgetTravelCost/types';
import { rdBudgetTechCostVO } from '@/api/oa/erp/budgetInfo/rd/rdBudgetTechCost/types';
import { rdBudgetLaborCostVO } from '@/api/oa/erp/budgetInfo/rd/rdBudgetLaborCost/types';
import { rdBudgetTestingCostVO } from '@/api/oa/erp/budgetInfo/rd/rdBudgetTestingCost/types';
import { rdBudgetOtherCostVO } from '@/api/oa/erp/budgetInfo/rd/rdBudgetOtherCost/types';
import { UserVO } from '@/api/system/user/types';
// 路由参数
const routeParams = ref<Record<string, any>>({});

// 审批相关组件引用
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
// 审批
const approvalVerifyOpen = async () => {
  await submitVerifyRef.value.openDialog(routeParams.value.taskId);
};

// 审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(searchForm.budgetId);
};

// 提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(proxy.$route);
  router.go(-1);
};
</script>

<style scoped>
.project-budget-container {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.justify-end {
  justify-content: flex-end;
}

.gap-2 {
  gap: 8px;
}

.gap-4 {
  gap: 16px;
}

.mb-6 {
  margin-top: 12px;
  margin-bottom: 6px;
}
</style>
