<template>
  <div class="p-2">
    <el-card shadow="never" style="margin-top: 0" class="mb-2">
      <!-- 审批按钮组件 -->
      <approvalButton
        @submitForm="submitForm"
        @approvalVerifyOpen="approvalVerifyOpen"
        @handleApprovalRecord="handleApprovalRecord"
        :buttonLoading="buttonLoading"
        :id="form.afterSalesId"
        :status="form.flowStatus"
        :pageType="routeParams.type"
        :mode="false"
      />
    </el-card>

    <!--  主表信息卡片 -->
    <el-card shadow="never" class="card-with-upload">
      <template #header>
        <span class="card-title">{{ form.afterSalesId ? '修改项目售后' : '添加项目售后' }}</span>
      </template>

      <el-form
        ref="afterSalesFormRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        :disabled="routeParams.type === 'view' || routeParams.type === 'approval'"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="售后主题" prop="afterSalesSubject">
              <el-input v-model="form.afterSalesSubject" placeholder="请输入售后主题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售后编号" prop="afterSalesCode">
              <el-input v-model="form.afterSalesCode" placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="项目号" prop="projectCode">
              <el-input v-model="form.projectCode" placeholder="请选择项目" readonly :disabled="isReadOnly" @click="openProjectSelect">
                <template #suffix>
                  <el-icon style="cursor: pointer" @click.stop="openProjectSelect" :class="{ 'is-disabled': isReadOnly }">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="选择项目后自动填充" disabled />
              <input type="hidden" :value="form.projectId" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId">
              <el-input v-model="form.customerName" placeholder="选择合同后自动填充" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同号" prop="contractId">
              <el-select
                v-model="form.contractId"
                placeholder="请选择合同"
                filterable
                clearable
                style="width: 100%"
                @change="handleContractChange"
                :disabled="!form.projectId"
              >
                <el-option
                  v-for="item in contractList"
                  :key="item.contractId"
                  :label="(item.contractCode || '无编号') + ' - ' + item.contractName"
                  :value="item.contractId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售后日期" prop="afterSalesDate">
              <el-date-picker v-model="form.afterSalesDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售后类型" prop="afterSalesType">
              <el-select v-model="form.afterSalesType" placeholder="选择售后类型" style="width: 100%">
                <el-option v-for="dict in after_sales_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户干系人" prop="stakeholderId">
              <el-select v-model="form.stakeholderId" multiple placeholder="请选择客户干系人" filterable style="width: 100%">
                <el-option v-for="item in contactOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售后处理人" prop="handlerId">
              <el-select v-model="form.handlerId" multiple filterable placeholder="请选择处理人" style="width: 100%">
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 问题描述和附件使用 flexbox 并排 -->
        <div class="problem-attachment-row">
          <div class="problem-col">
            <el-form-item label="问题描述" prop="problemDescription">
              <el-input
                v-model="form.problemDescription"
                type="textarea"
                :rows="3"
                maxlength="300"
                show-word-limit
                placeholder="请输入详细的问题描述"
              />
            </el-form-item>
          </div>
          <div class="attachment-col"></div>
        </div>
      </el-form>
      <!-- 附件区域放在表单外部，使用负 margin 拉到与问题描述同行 -->
      <div class="file-upload-row">
        <el-form label-width="120px">
          <el-form-item label="售后问题附件">
            <file-upload
              v-model="form.ossId"
              :limit="5"
              :fileSize="20"
              :fileType="['rar', 'zip', 'doc', 'docx', 'pdf']"
              :isShowTip="true"
              :disabled="isReadOnly"
            />
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- ========== 售后处理结果 ========== -->
    <el-card shadow="never" class="mb-2">
      <template #header>
        <span class="card-title">售后处理结果</span>
      </template>

      <el-row :gutter="20">
        <!-- ========== 左侧列  ========== -->
        <el-col :span="12">
          <el-form-item label="售后总工时" prop="totalWorkHours">
            <el-input-number v-model="form.totalWorkHours" :min="0" style="width: 100%" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="售后总成本" prop="totalCost">
            <el-input-number v-model="form.totalCost" :min="0" :precision="2" style="width: 100%" placeholder="" disabled>
              <template #suffix>元</template>
            </el-input-number>
          </el-form-item>

          <el-form-item label="解决状态" prop="solveStatus">
            <el-radio-group v-model="form.solveStatus">
              <el-radio v-for="dict in solve_status" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <!-- ========== 右侧列 ========== -->
        <el-col :span="12">
          <el-form-item label="完成日期" prop="completionDate">
            <el-date-picker v-model="form.completionDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
          </el-form-item>

          <el-form-item label="处理结果" prop="processingResult">
            <el-input v-model="form.processingResult" type="textarea" :rows="3" placeholder="处理结果描述" maxlength="300" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 子表 人员费用 -->
    <el-card shadow="never" class="mt-2">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <span class="card-title">人员费用成本</span>
          </el-col>
          <el-col :span="1.5" v-if="routeParams.type !== 'view' && routeParams.type !== 'approval'">
            <el-button type="primary" plain icon="Plus" size="small" @click="handleAddLabor">新增</el-button>
          </el-col>
          <el-col :span="1.5" v-if="routeParams.type !== 'view' && routeParams.type !== 'approval'">
            <el-button type="danger" plain icon="Delete" size="small" @click="handleDeleteLabor">删除</el-button>
          </el-col>
        </el-row>
      </template>
      <el-table :data="form.laborCostsList" border show-summary :summary-method="getLaborSummaries" @selection-change="handleLaborSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="人员姓名" prop="laborName">
          <template #default="scope">
            <el-select
              v-model="scope.row.laborId"
              filterable
              style="width: 100%"
              :disabled="routeParams.type === 'view' || routeParams.type === 'approval'"
              @change="(val) => handleLaborChange(val, scope.row)"
            >
              <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="费用科目" prop="expenseItem">
          <template #default="scope">
            <el-input v-model="scope.row.expenseItem" placeholder="" :disabled="routeParams.type === 'view' || routeParams.type === 'approval'" />
          </template>
        </el-table-column>
        <el-table-column label="成本" prop="cost" align="center">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.cost"
              :min="0"
              :precision="2"
              controls-position="right"
              style="width: 100%"
              :disabled="routeParams.type === 'view' || routeParams.type === 'approval'"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark">
          <template #default="scope">
            <el-input v-model="scope.row.remark" :disabled="routeParams.type === 'view' || routeParams.type === 'approval'" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 子表 ：消耗材料 -->
    <el-card shadow="never" class="mt-2">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <span class="card-title">消耗材料明细</span>
          </el-col>
          <el-col :span="1.5" v-if="routeParams.type !== 'view' && routeParams.type !== 'approval'">
            <el-button type="primary" plain icon="Plus" size="small" @click="handleAddMaterial">新增</el-button>
          </el-col>
          <el-col :span="1.5" v-if="routeParams.type !== 'view' && routeParams.type !== 'approval'">
            <el-button type="danger" plain icon="Delete" size="small" @click="handleDeleteMaterial">删除</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table
        :data="form.materialCostsList"
        border
        show-summary
        :summary-method="getMaterialSummaries"
        @selection-change="handleMaterialSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="55" align="center" />

        <el-table-column label="产品编码" prop="productCode" width="120" show-overflow-tooltip />
        <el-table-column label="产品名称" prop="productName" min-width="150" show-overflow-tooltip />
        <el-table-column label="规格型号" prop="specificationModel" width="120" show-overflow-tooltip />

        <el-table-column label="单位" prop="unitId" width="80" align="center">
          <template #default="scope">
            {{ getUnitName(scope.row.unitId) }}
          </template>
        </el-table-column>

        <el-table-column label="数量" prop="quantity" width="100" align="center" />
        <el-table-column label="税率%" prop="taxRate" width="80" align="center" />

        <el-table-column label="含税单价" prop="taxInclusivePrice" width="120" align="right">
          <template #default="scope"> {{ Number(scope.row.taxInclusivePrice).toFixed(2) }}</template>
        </el-table-column>

        <el-table-column label="含税金额" prop="taxInclusiveAmount" width="120" align="right">
          <template #default="scope"> {{ Number(scope.row.taxInclusiveAmount).toFixed(2) }}</template>
        </el-table-column>

        <el-table-column label="未税单价" prop="taxExclusivePrice" width="120" align="right">
          <template #default="scope"> {{ Number(scope.row.taxExclusivePrice).toFixed(2) }}</template>
        </el-table-column>

        <el-table-column label="未税金额" prop="taxExclusiveAmount" width="120" align="right">
          <template #default="scope"> {{ Number(scope.row.taxExclusiveAmount).toFixed(2) }}</template>
        </el-table-column>

        <el-table-column label="赠品" prop="giftFlag" width="80" align="center">
          <template #default="scope">
            <dict-tag :options="gift_flag" :value="scope.row.giftFlag" />
          </template>
        </el-table-column>

        <el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip />

        <!-- 操作列 -->
        <el-table-column label="操作" align="center" width="120" fixed="right" v-if="routeParams.type !== 'view' && routeParams.type !== 'approval'">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleEditMaterialRow(scope.row, scope.$index)">修改 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- ============ 消耗材料添加弹窗 ============ -->
    <el-dialog :title="materialDialog.title" v-model="materialDialog.visible" width="800px" append-to-body>
      <el-form ref="materialFormRef" :model="materialForm" :rules="materialRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品编码" prop="productCode">
              <el-input v-model="materialForm.productCode" placeholder="请输入产品编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="materialForm.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specificationModel">
              <el-input v-model="materialForm.specificationModel" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="单位" prop="unitId">
              <el-select v-model="materialForm.unitId" placeholder="请选择单位" style="width: 100%" filterable>
                <el-option v-for="item in unitOptions" :key="item.unitId" :label="item.unitName" :value="item.unitId" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="materialForm.quantity" :min="1" style="width: 100%" @change="calculateMaterialInDialog" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率%" prop="taxRate">
              <el-input-number v-model="materialForm.taxRate" :min="0" :max="100" style="width: 100%" @change="calculateMaterialInDialog" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="赠品" prop="giftFlag">
              <el-select v-model="materialForm.giftFlag" placeholder="是否赠品" style="width: 100%">
                <el-option v-for="dict in gift_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="含税单价" prop="taxInclusivePrice">
              <el-input-number
                v-model="materialForm.taxInclusivePrice"
                :min="0"
                :precision="2"
                style="width: 100%"
                @change="calculateMaterialInDialog"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含税金额" prop="taxInclusiveAmount">
              <el-input v-model="materialForm.taxInclusiveAmount" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="未税单价" prop="taxExclusivePrice">
              <el-input v-model="materialForm.taxExclusivePrice" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未税金额" prop="taxExclusiveAmount">
              <el-input v-model="materialForm.taxExclusiveAmount" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="materialForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMaterial">确 定</el-button>
          <el-button @click="materialDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 提交审批组件 -->
    <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
    <!-- 审批记录 -->
    <approvalRecord ref="approvalRecordRef" />
    <ProjectSelect ref="projectSelectRef" :multiple="false" @confirm-call-back="projectInfoSelectCallBack" />
  </div>
</template>

<script setup name="AfterSalesFormComponent" lang="ts">
import { ref, reactive, toRefs, onMounted, getCurrentInstance, watch, computed, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// import type { ElFormInstance } from 'element-plus';
import ProjectSelect from '@/components/ProjectSelect/index.vue';

import { getAfterSales, addAfterSales, updateAfterSales, submitAfterSalesAndFlowStart } from '@/api/oa/erp/afterSales';
import { listProjectInfo } from '@/api/oa/erp/projectInfo';
import { listUser } from '@/api/system/user';
import { getErpProjectContractsList } from '@/api/oa/erp/projectContracts';
import { getContractInfo } from '@/api/oa/erp/contractInfo';
import { getCustomerInfo } from '@/api/oa/crm/customerInfo';
import { listCustomerContact } from '@/api/oa/crm/customerContact';
import { listUnitInfo } from '@/api/oa/base/unitInfo';
import { getRuleGenerateCode } from '@/api/system/codeRule';
import type { ProjectInfoVO } from '@/api/oa/erp/projectInfo/types';

import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import ApprovalButton from '@/components/Process/approvalButton.vue';

import { CodeRuleEnum, FlowCodeEnum } from '@/enums/OAEnum';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();

// 字典加载
const { after_sales_type, solve_status, gift_flag } = toRefs<any>(proxy?.useDict('after_sales_type', 'solve_status', 'gift_flag'));

// 路由与加载状态
const routeParams = ref<Record<string, any>>({});
const buttonLoading = ref(false);

// 组件 Refs
const afterSalesFormRef = ref<ElFormInstance>();
const projectSelectRef = ref<InstanceType<typeof ProjectSelect>>();
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const materialFormRef = ref<any>(null);

// 基础下拉数据源
const projectList = ref<any[]>([]);
const userList = ref<any[]>([]);
const contractList = ref<any[]>([]);
const contactOptions = ref<any[]>([]);
const unitOptions = ref<any[]>([]);

// 页面状态控制
const isCodeGenerated = ref(false); // 编号是否已生成
const editingIndex = ref<number>(-1); // 材料表编辑索引 (-1 为新增)
const checkedLabor = ref<any[]>([]); // 人员表选中项
const checkedMaterial = ref<any[]>([]); // 材料表选中项

// 项目管理角色用户昵称列表（抄送对象）
const projectMgrUserNames = ['于洋'];

// 流程相关变量
const submitFormData = ref<StartProcessBo>({ businessId: '', flowCode: '', variables: {}, bizExt: {} });
const taskVariables = ref<Record<string, any>>({});
const flowInstanceBizExtBo = ref<Record<string, any>>({});

const data = reactive({
  form: {
    // 主表字段
    afterSalesId: undefined,
    afterSalesSubject: undefined,
    afterSalesCode: undefined,
    projectId: undefined,
    projectCode: undefined,
    projectName: undefined,
    customerId: undefined,
    customerName: undefined,
    contractId: undefined,
    contractCode: undefined,
    contactPerson: undefined,
    contactPhone: undefined,
    afterSalesDate: undefined,
    afterSalesType: undefined,
    stakeholderId: [],
    handlerId: [],
    problemDescription: undefined,
    ossId: undefined,
    totalWorkHours: undefined,
    totalCost: undefined,
    completionDate: undefined,
    solveStatus: undefined,
    processingResult: undefined,
    flowStatus: 'draft',

    // 子表数据
    laborCostsList: [] as any[],
    materialCostsList: [] as any[]
  },
  rules: {
    afterSalesSubject: [{ required: true, message: '售后主题不能为空', trigger: 'blur' }],
    // afterSalesCode: [{ required: true, message: '售后编号不能为空', trigger: 'blur' }],
    projectCode: [{ required: true, message: '请选择项目', trigger: 'change' }],
    projectName: [{ required: true, message: '请选择项目', trigger: 'change' }],
    afterSalesDate: [{ required: true, message: '请选择日期', trigger: 'change' }],
    afterSalesType: [{ required: true, message: '请选择售后类型', trigger: 'change' }],
    // stakeholderId: [{ required: true, message: '客户干系人不能为空', trigger: 'change' }],
    handlerId: [{ required: true, message: '售后处理人不能为空', trigger: 'change' }]
  }
});

const { form, rules } = toRefs(data);

// 材料弹窗表单数据
const materialDialog = reactive({ visible: false, title: '添加消耗材料' });
const materialForm = ref<any>({
  productCode: '',
  productName: '',
  specificationModel: '',
  unitId: '',
  quantity: 1,
  taxRate: 13,
  taxInclusivePrice: 0,
  taxInclusiveAmount: 0,
  taxExclusivePrice: 0,
  taxExclusiveAmount: 0,
  giftFlag: '0',
  remark: ''
});
const materialRules = {
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  unitId: [{ required: true, message: '请选择单位', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  taxInclusivePrice: [{ required: true, message: '请输入含税单价', trigger: 'blur' }]
};

const isReadOnly = computed(() => {
  return routeParams.value.type === 'view' || routeParams.value.type === 'approval';
});

// 监听子表变化，自动计算总成本
watch(
  [() => form.value.laborCostsList, () => form.value.materialCostsList],
  () => {
    calculateTotalCost();
  },
  { deep: true }
);

onMounted(async () => {
  nextTick(async () => {
    // 1. 获取路由参数
    routeParams.value = route.query;
    const id = routeParams.value.id;

    // 2. 加载基础数据
    loadBaseOptions();

    // 3. 判断模式 (新增 / 修改 / 查看 / 审批)
    if (id && (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval')) {
      const res: any = await getAfterSales(id);
      form.value = res.data;

      // 格式转换：String -> Array (用于多选下拉回显)
      if (typeof form.value.handlerId === 'string') {
        form.value.handlerId = (form.value.handlerId as string).split(',') as any;
      }
      if (typeof form.value.stakeholderId === 'string') {
        form.value.stakeholderId = (form.value.stakeholderId as string).split(',') as any;
      }

      // 初始化空子表防止报错
      if (!form.value.laborCostsList) form.value.laborCostsList = [];
      if (!form.value.materialCostsList) form.value.materialCostsList = [];

      // 触发级联加载
      if (form.value.projectId) loadContractOptions(form.value.projectId);
      if (form.value.customerId) loadContactOptions(form.value.customerId);

      // 标记编号状态
      if (form.value.afterSalesCode) isCodeGenerated.value = true;
    } else {
      // 新增模式初始化
      form.value.laborCostsList = [];
      form.value.materialCostsList = [];
      form.value.flowStatus = 'draft';
      isCodeGenerated.value = false;
    }
  });
});

// 加载基础下拉数据
function loadBaseOptions() {
  listProjectInfo({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
    projectList.value = res.rows;
  });
  listUser({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
    userList.value = res.rows;
  });
  listUnitInfo({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
    unitOptions.value = res.rows;
  });
}

// 生成售后编号
const generateAfterSalesCode = async () => {
  if (isCodeGenerated.value) return;
  try {
    const params = { codeRuleCode: CodeRuleEnum.AFTER_SALES } as any;
    const res = await getRuleGenerateCode(params);
    if (res.code === 200) {
      form.value.afterSalesCode = res.msg;
      isCodeGenerated.value = true;
      proxy?.$modal.msgSuccess('售后编号生成成功');
    }
  } catch (error) {
    console.error('生成售后编号失败:', error);
    proxy?.$modal.msgError('生成项目编号失败');
  }
};

// 计算售后总成本 (人员 + 材料)
const calculateTotalCost = () => {
  const laborList = form.value.laborCostsList || [];
  const materialList = form.value.materialCostsList || [];

  const laborTotal = laborList.reduce((sum: number, item: any) => {
    const val = Number(item.cost);
    return sum + (Number.isNaN(val) ? 0 : val);
  }, 0);

  const materialTotal = materialList.reduce((sum: number, item: any) => {
    const val = Number(item.taxInclusiveAmount);
    return sum + (Number.isNaN(val) ? 0 : val);
  }, 0);

  form.value.totalCost = Number((laborTotal + materialTotal).toFixed(2));
};

// 打开项目选择弹窗
const openProjectSelect = () => {
  if (isReadOnly.value) return;
  projectSelectRef.value?.open();
};

// 项目选择回调
const projectInfoSelectCallBack = (data: ProjectInfoVO[]) => {
  if (data && data.length > 0) {
    const project = data[0];
    if (form.value.projectId === project.projectId) return;

    // 清空下级数据
    form.value.contractId = undefined;
    form.value.customerName = undefined;
    form.value.customerId = undefined;
    contractList.value = [];

    // 回填项目信息
    form.value.projectId = project.projectId;
    form.value.projectCode = project.projectCode;
    form.value.projectName = project.projectName;

    // 加载关联合同
    if (project.projectId) {
      loadContractOptions(project.projectId);
    }
    afterSalesFormRef.value?.validateField(['projectName', 'projectCode']);
  }
};

const handleProjectSelected = (row: any) => {
  if (form.value.projectId === row.projectId) return;
  form.value.contractId = undefined;
  form.value.customerName = undefined;
  form.value.customerId = undefined;
  contractList.value = [];
  form.value.projectId = row.projectId;
  form.value.projectCode = row.projectCode;
  form.value.projectName = row.projectName;
  loadContractOptions(row.projectId);
};

// 加载项目关联合同
function loadContractOptions(projectId: any) {
  getErpProjectContractsList({ projectId: projectId }).then((res: any) => {
    contractList.value = res.data;
  });
}

// 合同变更联动 -> 客户 -> 联系人
async function handleContractChange(val: any) {
  form.value.customerName = undefined;
  form.value.customerId = undefined;
  contactOptions.value = [];

  if (!val) return;

  try {
    // 1. 获取合同详情
    const resContract = await getContractInfo(val);
    if (resContract.data) {
      const contract = resContract.data;
      form.value.customerId = contract.oneCustomerId;

      // 2. 如果合同详情中有客户名则直接用，否则单独查询客户详情
      if (contract.oneCustomerName) {
        form.value.customerName = contract.oneCustomerName;
      } else if (contract.oneCustomerId) {
        const resCustomer = await getCustomerInfo(contract.oneCustomerId);
        if (resCustomer.data) {
          form.value.customerName = resCustomer.data.customerName;
        }
      }

      // 3. 加载联系人
      if (form.value.customerId) {
        loadContactOptions(form.value.customerId);
      }
    }
  } catch (error) {
    console.error('加载合同关联信息失败:', error);
  }
}

// 加载客户联系人
function loadContactOptions(customerId: any) {
  if (!customerId) return;
  const params = { customerId: customerId, pageNum: 1, pageSize: 1000 };
  listCustomerContact(params as any).then((res: any) => {
    contactOptions.value = res.rows.map((item: any) => ({
      id: String(item.contactId),
      name: item.contactName
    }));
  });
}

// 新增人员行
function handleAddLabor() {
  form.value.laborCostsList.push({
    laborId: undefined,
    laborName: '',
    expenseItem: '',
    cost: 0,
    remark: ''
  });
}

// 删除人员行
function handleDeleteLabor() {
  if (checkedLabor.value.length === 0) return proxy.$modal.msgError('请选择要删除的数据');
  const delList = checkedLabor.value;
  form.value.laborCostsList = form.value.laborCostsList.filter((item: any) => !delList.includes(item));
}

// 人员选择联动回填名称
const handleLaborChange = (val: any, row: any) => {
  const user = userList.value.find((u: any) => u.userId === val);
  row.laborName = user ? user.nickName : '';
};

function handleLaborSelectionChange(selection: any) {
  checkedLabor.value = selection;
}

// 人员表尾合计
const getLaborSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: string[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '';
      return;
    }
    if (index === 1) {
      sums[index] = '合计';
      return;
    }
    if (column.property === 'cost') {
      const values = data.map((item: any) => Number(item[column.property]));
      if (!values.every((value: any) => Number.isNaN(value))) {
        const total = values.reduce((prev: any, curr: any) => {
          const value = Number(curr);
          return !Number.isNaN(value) ? prev + curr : prev;
        }, 0);
        sums[index] = total.toFixed(2) + ' 元';
      } else {
        sums[index] = '0.00 元';
      }
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

// 打开新增弹窗
function handleAddMaterial() {
  editingIndex.value = -1;
  materialForm.value = {
    productCode: '',
    productName: '',
    specificationModel: '',
    unitId: '',
    quantity: 1,
    taxRate: 13,
    taxInclusivePrice: 0,
    taxInclusiveAmount: 0,
    taxExclusivePrice: 0,
    taxExclusiveAmount: 0,
    giftFlag: '0',
    remark: ''
  };
  materialDialog.title = '添加消耗材料';
  materialDialog.visible = true;
}

// 打开修改弹窗
function handleEditMaterialRow(row: any, index: number) {
  editingIndex.value = index;
  materialForm.value = JSON.parse(JSON.stringify(row));
  materialDialog.title = '修改消耗材料';
  materialDialog.visible = true;
}

// 弹窗内自动计算
const calculateMaterialInDialog = () => {
  const row = materialForm.value;
  const quantity = row.quantity || 0;
  const taxRate = row.taxRate || 0;
  const taxInclusivePrice = row.taxInclusivePrice || 0;

  row.taxInclusiveAmount = (quantity * taxInclusivePrice).toFixed(2);
  const taxBase = 1 + taxRate / 100;
  if (taxBase !== 0) {
    row.taxExclusivePrice = (taxInclusivePrice / taxBase).toFixed(2);
  } else {
    row.taxExclusivePrice = 0.0;
  }
  row.taxExclusiveAmount = (row.taxExclusivePrice * quantity).toFixed(2);
};

// 提交弹窗数据
function submitMaterial() {
  materialFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (editingIndex.value > -1) {
        form.value.materialCostsList.splice(editingIndex.value, 1, { ...materialForm.value });
      } else {
        form.value.materialCostsList.push({ ...materialForm.value });
      }
      materialDialog.visible = false;
      proxy.$modal.msgSuccess(editingIndex.value > -1 ? '修改成功' : '添加成功');
    }
  });
}

// 删除材料行
function handleDeleteMaterial() {
  if (checkedMaterial.value.length === 0) return proxy.$modal.msgError('请选择要删除的数据');
  const delList = checkedMaterial.value;
  form.value.materialCostsList = form.value.materialCostsList.filter((item: any) => !delList.includes(item));
}

function handleMaterialSelectionChange(selection: any) {
  checkedMaterial.value = selection;
}

// 获取单位名称
const getUnitName = (unitId: string) => {
  if (!unitId) return '';
  const unit = unitOptions.value.find((u) => u.unitId === unitId);
  return unit ? unit.unitName : unitId;
};

// 材料表尾合计
const getMaterialSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: string[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '';
      return;
    }
    if (index === 1) {
      sums[index] = '合计';
      return;
    }
    if (['taxInclusiveAmount', 'taxExclusiveAmount'].includes(column.property)) {
      const values = data.map((item: any) => Number(item[column.property]));
      if (!values.every((value: any) => Number.isNaN(value))) {
        const total = values.reduce((prev: any, curr: any) => {
          const value = Number(curr);
          return !Number.isNaN(value) ? prev + curr : prev;
        }, 0);
        sums[index] = total.toFixed(2) + ' 元';
      } else {
        sums[index] = '0.00 元';
      }
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

/** 提交按钮 */
const submitForm = (status: string, mode: boolean) => {
  if (status === 'draft') {
    executeSubmit(status, mode);
    return;
  }
  afterSalesFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      executeSubmit(status, mode);
    }
  });
};

const executeSubmit = async (status: string, mode: boolean) => {
  buttonLoading.value = true;
  try {
    const submitData: any = { ...form.value };

    // 数据格式转换：数组 -> 字符串
    if (Array.isArray(submitData.handlerId)) submitData.handlerId = submitData.handlerId.join(',');
    if (Array.isArray(submitData.stakeholderId)) submitData.stakeholderId = submitData.stakeholderId.join(',');

    if (status !== 'draft') {
      // --- 提交审批 ---
      submitData.flowCode = FlowCodeEnum.AFTER_SALES_KEY;
      // 根据昵称匹配项目管理角色用户作为抄送对象
      const copyUserIds = userList.value.filter((u: any) => projectMgrUserNames.includes(u.nickName)).map((u: any) => String(u.userId));
      submitData.variables = {
        afterSalesId: submitData.afterSalesId,
        totalCost: submitData.totalCost || 0,
        startUserId: useUserStore().userId,
        afterSalesCopyUsers: copyUserIds.join(',')
      };
      submitData.bizExt = {
        businessTitle: `售后申请：${submitData.afterSalesSubject}`,
        businessCode: submitData.afterSalesCode
      };
      submitData.afterSalesStatus = '1'; // 审批中
      submitData.flowStatus = 'waiting';

      const res = await submitAfterSalesAndFlowStart(submitData);
      if (res && res.data) {
        form.value = res.data;
        if (!form.value.laborCostsList) form.value.laborCostsList = [];
        if (!form.value.materialCostsList) form.value.materialCostsList = [];
      }
      proxy.$modal.msgSuccess('提交成功，流程已发起');
    } else {
      // --- 暂存草稿 ---
      submitData.flowStatus = 'draft';
      submitData.afterSalesStatus = '0'; // 草稿
      if (submitData.afterSalesId) {
        await updateAfterSales(submitData);
      } else {
        await addAfterSales(submitData);
      }
      proxy.$modal.msgSuccess('暂存成功');
    }
    // 返回列表
    proxy.$tab.closePage(route);
    router.go(-1);
  } catch (error) {
    console.error('提交发生错误:', error);
    proxy.$modal.msgError('提交失败，请查看控制台错误详情');
  } finally {
    buttonLoading.value = false;
  }
};

// 审批记录初始化
const handleApprovalRecord = () => {
  if (form.value.afterSalesId) {
    approvalRecordRef.value?.init(form.value.afterSalesId);
  }
};

// 审批校验弹窗
const approvalVerifyOpen = async () => {
  if (submitVerifyRef.value) {
    await submitVerifyRef.value.openDialog(routeParams.value.taskId);
  }
};

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

<style scoped lang="scss">
.card-title {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.mt-2 {
  margin-top: 10px;
}

/* 问题描述和附件区域容器 - 使用 flexbox */
.problem-attachment-row {
  display: flex;
  margin: 0;
}

.problem-col {
  flex: 0 0 50%;
  max-width: 50%;
  padding-right: 10px;
}

.attachment-col {
  flex: 0 0 50%;
  max-width: 50%;
  padding-left: 10px;
}

/* 附件区域使用负 margin 拉到问题描述同行 */
.file-upload-row {
  margin-top: -95px; /* 向上拉到与问题描述同行 */
  margin-left: 50%; /* 偏移到右侧，与上方表单字段对齐 */
  padding-left: 10px;
  padding-right: 10px;
}

.file-upload-content {
  /* 无需额外样式 */
}
</style>
