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

    <el-card shadow="never" style="margin-top: 0">
      <template #header>
        <div style="text-align: left; font-weight: bold; font-size: 24px">
          出差申请{{ routeParams.type === 'view' ? ' - 查看' : form.tripId ? ' - 修改' : ' - 新增' }}
        </div>
      </template>
      <el-form ref="businessTripApplyFormRef" :model="form" :loading="buttonLoading" :rules="computedRules" label-width="120px">
        <!-- 通用字段区域 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出差类型" prop="tripType">
              <el-select v-model="form.tripType" placeholder="请选择出差类型" disabled>
                <el-option v-for="dict in trip_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="applyCode">
              <el-input v-model="form.applyCode" placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人姓名" prop="applicantName">
              <el-input v-model="form.applicantName" placeholder="自动填充" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人部门" prop="deptName">
              <el-input v-model="form.deptName" placeholder="自动填充" disabled />
            </el-form-item>
          </el-col>

          <!-- 业务方向 -->
          <el-col :span="12" v-if="form.tripType === '2' || form.tripType === '3'">
            <el-form-item label="业务方向" prop="businessDirection">
              <el-select v-model="form.businessDirection" placeholder="请选择业务方向" :disabled="isFormDisabled" style="width: 100%">
                <el-option v-for="dict in business_direction" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 总体事由 -->
          <el-col :span="12" v-if="form.tripType !== '2' && form.tripType !== '3'">
            <el-form-item label="出差事由" prop="tripReason">
              <el-input
                v-model="form.tripReason"
                type="textarea"
                placeholder="请输入出差事由"
                :disabled="isFormDisabled"
                maxlength="800"
                show-word-limit
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="开始日期" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择开始日期"
                :disabled="isFormDisabled"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择结束日期"
                :disabled="isFormDisabled"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时长(天)" prop="durationDays">
              <el-input-number v-model="form.durationDays" :precision="1" :step="0.5" :min="0" disabled style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="isFormDisabled" />
            </el-form-item>
          </el-col>

          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="出差申请附件">-->
          <!--              <file-upload-->
          <!--                v-model="form.ossId"-->
          <!--                :limit="5"-->
          <!--                :fileSize="20"-->
          <!--                :fileType="['rar', 'zip', 'doc', 'docx', 'pdf', 'jpg', 'jpeg', 'png']"-->
          <!--                :isShowTip="true"-->
          <!--                :disabled="isFormDisabled"-->
          <!--              />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

          <el-col :span="12" v-if="!isFormDisabled && form.tripType !== '1' && form.tripType !== '2' && form.tripType !== '3'">
            <el-form-item label="下一步审批人" prop="variables.approverId">
              <el-select
                v-model="form.variables.approverId"
                placeholder="请选择或搜索审批人"
                filterable
                clearable
                style="width: 100%"
                @change="handleApproverSelectChange"
              >
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="routeParams.type === 'approval' && !isFormDisabled">
            <el-form-item label="抄送人员" prop="copyUserIds">
              <el-select v-model="form.copyUserIds" placeholder="请选择抄送人员" filterable clearable multiple style="width: 100%">
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="String(user.userId)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 行程明细 -->
    <el-card shadow="never" style="margin-top: 10px">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center">
          <span>行程明细</span>
          <el-button type="primary" plain icon="Plus" size="small" @click="handleAddDetail" v-if="!isFormDisabled">添加行程</el-button>
        </div>
      </template>
      <el-table
        :data="form.crmBusinessTripDetailsList"
        border
        style="width: 100%"
        :row-key="(row) => row.tripDetailsId || row.tempId"
        :expand-row-keys="expandedRowKeys"
      >
        <el-table-column type="expand">
          <template #default="scope">
            <div style="padding: 10px 20px">
              <el-row :gutter="20">
                <!-- 交流对象 / 客户 (Type 2 场景) -->
                <el-col :span="12" v-if="form.tripType === '2'">
                  <el-form-item label="交流对象">
                    <el-select
                      v-model="scope.row.customerId"
                      placeholder="请选择客户"
                      filterable
                      clearable
                      :disabled="isFormDisabled"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="customer in customerList"
                        :key="customer.customerId"
                        :label="customer.customerName"
                        :value="customer.customerId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <!-- 对应项目 (Type 1) -->
                <el-col :span="12" v-if="form.tripType === '1'">
                  <el-form-item label="对应项目">
                    <el-input
                      v-model="scope.row.projectName"
                      placeholder="请选择项目"
                      readonly
                      :disabled="isFormDisabled"
                      @click="openDetailProjectSelect(scope.$index)"
                    >
                      <template #suffix>
                        <el-icon style="cursor: pointer" @click.stop="openDetailProjectSelect(scope.$index)"><Search /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>

                <!-- 项目号 (Type 1) -->
                <el-col :span="12" v-if="form.tripType === '1'">
                  <el-form-item label="项目号">
                    <el-input v-model="scope.row.projectCode" placeholder="选择项目后自动显示" disabled />
                  </el-form-item>
                </el-col>

                <el-col :span="12" v-if="form.tripType === '3'">
                  <el-form-item label="会议/展会名称">
                    <el-input v-model="scope.row.meetingName" placeholder="会议/展会名称" :disabled="isFormDisabled" />
                  </el-form-item>
                </el-col>

                <el-col :span="12" v-if="form.tripType === '2'">
                  <el-form-item label="交流目的">
                    <el-select v-model="scope.row.exchangePurpose" placeholder="请选择交流目的" :disabled="isFormDisabled" style="width: 100%">
                      <el-option v-for="dict in exchange_purpose" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="24" v-if="(form.tripType === '2' || form.tripType === '3') && canViewFeedback">
                  <el-form-item label="交流过程与反馈">
                    <el-input
                      v-model="scope.row.exchangeFeedback"
                      type="textarea"
                      placeholder="达成共识或反馈"
                      :rows="3"
                      :disabled="isFormDisabled"
                    />
                  </el-form-item>
                </el-col>

                <!-- <el-col :span="24">
                  <el-form-item label="具体事由">
                    <el-input
                      v-model="scope.row.tripReason"
                      type="textarea"
                      placeholder="填写本次行程具体事由"
                      :rows="3"
                      :disabled="isFormDisabled"
                    />
                  </el-form-item>
                </el-col> -->
              </el-row>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="序号" type="index" width="60" align="center" />

        <el-table-column prop="tripLocation">
          <template #header> <span style="color: #f56c6c; margin-right: 4px">*</span>出差地点 </template>
          <template #default="scope">
            <el-form-item
              :prop="'crmBusinessTripDetailsList.' + scope.$index + '.tripLocation'"
              :rules="[
                {
                  required: true,
                  validator: (rule, value, callback) => {
                    const item = form.crmBusinessTripDetailsList?.[scope.$index];
                    if (!item || !item.tripLocation || !item.tripLocation.trim()) {
                      callback(new Error('出差地点不能为空'));
                    } else {
                      callback();
                    }
                  },
                  trigger: ['blur', 'change']
                }
              ]"
            >
              <el-input
                v-model="scope.row.tripLocation"
                placeholder="出差地点"
                :disabled="isFormDisabled"
                @input="refreshValidate(scope.$index, 'tripLocation')"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="startTime" width="170">
          <template #header> 开始日期 </template>
          <template #default="scope">
            <el-form-item :prop="'crmBusinessTripDetailsList.' + scope.$index + '.startTime'">
              <el-date-picker
                v-model="scope.row.startTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="开始"
                :disabled="isFormDisabled"
                @change="
                  () => {
                    calculateDetailDuration(scope.row);
                    refreshValidate(scope.$index, 'startTime');
                  }
                "
                style="width: 100%"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="endTime" width="170">
          <template #header> 结束日期 </template>
          <template #default="scope">
            <el-form-item :prop="'crmBusinessTripDetailsList.' + scope.$index + '.endTime'">
              <el-date-picker
                v-model="scope.row.endTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="结束"
                :disabled="isFormDisabled"
                @change="
                  () => {
                    calculateDetailDuration(scope.row);
                    refreshValidate(scope.$index, 'endTime');
                  }
                "
                style="width: 100%"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="时长(天)" prop="durationDays" width="90">
          <template #default="scope">
            <el-input-number v-model="scope.row.durationDays" :precision="1" :step="0.5" :min="0" disabled style="width: 100%" :controls="false" />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="80" align="center" fixed="right" v-if="!isFormDisabled">
          <template #default="scope">
            <el-button link type="danger" icon="Delete" @click="handleDeleteDetail(scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

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

<script setup name="BusinessTripApplyEdit" lang="ts">
import {
  addBusinessTripApply,
  updateBusinessTripApply,
  getBusinessTripApply,
  submitBusinessTripApplyAndFlowStart
} from '@/api/oa/crm/businessTripApply';
import { BusinessTripApplyForm } from '@/api/oa/crm/businessTripApply/types';
import { getRuleGenerateCode } from '@/api/system/codeRule';
import { startWorkFlow } from '@/api/workflow/task';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import ApprovalButton from '@/components/Process/approvalButton.vue';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import ProjectSelect from '@/components/ProjectSelect/index.vue';
import { CodeRuleEnum, FlowCodeEnum } from '@/enums/OAEnum';
import { getInfo } from '@/api/login';
import { useUserStore } from '@/store/modules/user';
import { listUser } from '@/api/system/user'; // 导入用户列表API
import { allListDept } from '@/api/system/dept'; // 导入部门列表API
import { getCrmCustomerInfoList } from '@/api/oa/crm/customerInfo'; // 导入客户列表API
import { ProjectInfoVO } from '@/api/oa/erp/projectInfo/types';
import dayjs from 'dayjs';

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

// 字典加载
const { trip_type, business_direction, exchange_purpose } = toRefs<any>(proxy?.useDict('trip_type', 'business_direction', 'exchange_purpose'));

// 路由参数
const routeParams = ref<Record<string, any>>({});
const buttonLoading = ref(false);

const businessTripApplyFormRef = ref<ElFormInstance>();
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const projectSelectRef = ref<InstanceType<typeof ProjectSelect>>();
// const userSelectRef = ref<InstanceType<typeof UserSelect>>(); // 审批人选择 ref

const userList = ref<any[]>([]); // 用户列表
const deptInfoList = ref<any[]>([]); // 部门列表
const customerList = ref<any[]>([]); // 客户列表

// 流程相关数据
const submitFormData = ref<StartProcessBo>({
  businessId: '',
  flowCode: FlowCodeEnum.BUSINESS_TRIP_CODE,
  variables: {},
  bizExt: {}
});
const taskVariables = ref<Record<string, any>>({});

// 用户角色列表
const userRoles = ref<string[]>([]);
// "市场交流反馈查看"角色：拥有此角色的用户可查看交流过程与反馈
const hasTripCommViewRole = computed(() => userRoles.value?.some((role) => role === 'tripCommView'));
// 交流过程与反馈字段可见性：拥有角色 或 申请人本人
const canViewFeedback = computed(() => {
  if (hasTripCommViewRole.value) return true;
  const currentUserId = String(useUserStore().userId);
  if (form.value.applicantId && currentUserId === String(form.value.applicantId)) return true;
  return false;
});

const initFormData: BusinessTripApplyForm = {
  tripId: undefined,
  applyCode: undefined,
  tripType: undefined,
  applicantId: undefined,
  applicantName: undefined,
  deptId: undefined,
  deptName: undefined,
  tripLocation: undefined,
  startTime: undefined,
  endTime: undefined,
  durationDays: undefined,
  tripReason: undefined,
  projectId: undefined,
  customerId: undefined,
  exchangeObject: undefined,
  businessDirection: undefined,
  exchangePurpose: undefined,
  exchangeFeedback: undefined,
  tripStatus: '1', // 默认暂存
  flowStatus: 'draft',
  remark: undefined,
  // ossId: undefined,
  variables: {}, // 初始化 variables
  copyUserIds: [] as string[], // 抄送人员ID列表
  crmBusinessTripDetailsList: [] // 行程明细列表
};

const data = reactive({
  form: { ...initFormData },
  rules: {
    tripType: [{ required: true, message: '出差类型不能为空', trigger: 'change' }],
    // applyCode: [{ required: true, message: '申请单号不能为空', trigger: 'blur' }],

    // 动态校验
    projectId: [{ required: true, message: '项目名称不能为空', trigger: 'change' }],
    exchangeObject: [{ required: true, message: '交流对象不能为空', trigger: 'blur' }],
    customerId: [{ required: true, message: '请选择交流对象(客户)', trigger: 'change' }],
    businessDirection: [{ required: true, message: '业务方向不能为空', trigger: 'change' }],
    exchangePurpose: [{ required: true, message: '交流目的不能为空', trigger: 'change' }],
    exchangeFeedback: [{ required: true, message: '交流过程与反馈不能为空', trigger: 'blur' }],
    meetingName: [{ required: true, message: '会议/展会名称不能为空', trigger: 'blur' }],
    'variables.approverId': [
      {
        required: true,
        validator: (rule: any, value: any, callback: any) => {
          if ((form.value.tripType === '1' || form.value.tripType === '4') && !value) {
            callback(new Error('请选择下一步审批人'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ],
    startTime: [] as any[],
    endTime: [] as any[]
  }
});

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

const isFormDisabled = computed(() => {
  if (routeParams.value.type === 'view') {
    return true;
  }
  if (routeParams.value.type === 'approval') {
    // 申请人确认节点判定：如果目前流程处于审批类型下，且正在操作的登陆者就是本表单最初的那个申请人
    if (String(useUserStore().userId) === String(form.value.applicantId)) {
      return false; // 在此阶段彻底允许他修改表单内容
    }
    return true; // 其他领导审批时仅查看不可修改
  }
  return false;
});

// 计算动态校验规则
const computedRules = computed(() => {
  const baseRules = { ...rules.value };

  // 申请人确认节点添加强校验（开始日期和结束日期不为空，且结束要在开始之后）
  if (routeParams.value.type === 'approval' && String(useUserStore().userId) === String(form.value.applicantId)) {
    baseRules.startTime = [{ required: true, message: '开始日期不能为空', trigger: 'change' }];
    baseRules.endTime = [
      { required: true, message: '结束日期不能为空', trigger: 'change' },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value && form.value.startTime && dayjs(value).isBefore(dayjs(form.value.startTime))) {
            callback(new Error('结束日期不能早于开始日期'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ];
  }

  return baseRules;
});

// 设置默认抄送人员逻辑
const setDefaultCopyUsers = () => {
  let targetNames: string[] = [];
  let includeDeptLeader = false;

  if (form.value.tripType === '1') {
    // 安装调试：于洋、米兰、张兰艳、部门经理
    targetNames = ['于洋', '米兰', '张兰艳'];
    includeDeptLeader = true;
  } else if (form.value.tripType === '2' || form.value.tripType === '3') {
    // 市场交流 / 展会/会议：张东辉、米兰、张兰艳、陈海军
    targetNames = ['张东辉', '米兰', '张兰艳', '陈海军'];
  } else {
    // 其他类型：默认名单 + 部门负责人/副总
    targetNames = ['米兰', '于洋', '张兰艳', '张东辉', '冯俊杰'];
    includeDeptLeader = true;
  }

  // 根据名字查找ID
  const copyIds = userList.value.filter((u: any) => targetNames.includes(u.nickName)).map((u: any) => String(u.userId));

  // 如果包含部门经理
  if (includeDeptLeader) {
    const deptInfo = deptInfoList.value.find((d: any) => d.deptId === form.value.deptId);
    if (deptInfo) {
      if (deptInfo.leader) copyIds.push(String(deptInfo.leader));
      if (form.value.tripType !== '1' && deptInfo.vicePresident) {
        copyIds.push(String(deptInfo.vicePresident));
      }
    }
  }

  form.value.copyUserIds = [...new Set(copyIds)];
};

onMounted(async () => {
  nextTick(async () => {
    routeParams.value = route.query;
    const id = routeParams.value.id;

    // 加载用户列表 (用于审批人选择和抄送人员选择)
    const userRes = await listUser({ pageNum: 1, pageSize: 1000 });
    userList.value = userRes.rows;

    // 加载部门列表 (用于获取部门负责人和分管副总)
    const deptRes = await allListDept({ deptCategory: '03' } as any);
    deptInfoList.value = deptRes.data || [];

    // 加载客户列表 (用于交流对象选择)
    const customerRes = await getCrmCustomerInfoList({});
    customerList.value = customerRes.data || [];

    // 始终获取当前用户角色（用于反馈字段可见性判断）
    try {
      const infoRes = await getInfo();
      userRoles.value = infoRes.data?.roles || [];
      // 新增时自动填充申请人信息
      if (!id) {
        if (infoRes.data?.user) {
          form.value.applicantId = infoRes.data.user.userId;
          form.value.applicantName = infoRes.data.user.nickName;
          form.value.deptId = infoRes.data.user.deptId;
          form.value.deptName = infoRes.data.user.deptName;
        }
      }
    } catch (e) {
      console.error('获取用户信息失败', e);
      userRoles.value = [];
    }

    if (!id) {
      // 从 index 页面传来 tripType
      if (routeParams.value.tripType) {
        form.value.tripType = routeParams.value.tripType;
      }
      // 必须在 tripType 赋值后，再计算默认抄送人
      setDefaultCopyUsers();
    }

    if (id && (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval')) {
      const res = await getBusinessTripApply(id);
      Object.assign(form.value, res.data);
      // 将抄送人员字符串转换为数组
      if (form.value.copyUserIds && typeof form.value.copyUserIds === 'string') {
        form.value.copyUserIds = (form.value.copyUserIds as string).split(',').filter((id) => id);
      }

      // 编辑模式下，如果抄送人员为空，重新设置默认抄送人员
      if (routeParams.value.type === 'update' && (!form.value.copyUserIds || form.value.copyUserIds.length === 0)) {
        setDefaultCopyUsers();
      }

      // 如果落到“申请人确认”节点，将固定注入陈海军和张东辉，以及业务负责人作为后台流转变量
      if (routeParams.value.type === 'approval' && String(useUserStore().userId) === String(form.value.applicantId)) {
        const confirmCopyIds: string[] = [];
        ['张东辉', '陈海军', '米兰', '张兰艳'].forEach((name) => {
          const matchedUser = userList.value.find((u: any) => u.nickName === name);
          if (matchedUser) {
            confirmCopyIds.push(String(matchedUser.userId));
          }
        });

        // 追加：业务方向负责人的ID映射（与后台 SpelRuleComponent.java 保持一致）
        const BUSINESS_DIRECTION_TO_USERNAME: Record<number, string> = {
          1: '1985254821554475009',
          2: '1985258519835889666',
          3: '1985251968270127105',
          4: '1985257496048226305',
          5: '1985254145713688578'
        };
        const bd = Number(form.value.businessDirection);
        if (bd && BUSINESS_DIRECTION_TO_USERNAME[bd]) {
          confirmCopyIds.push(BUSINESS_DIRECTION_TO_USERNAME[bd]);
        }

        // 兼容原有的手工可选抄送并做个去重合并
        form.value.copyUserIds = Array.from(new Set([...(form.value.copyUserIds || []), ...confirmCopyIds]));
        // 将整理完的抄送群放入该次提交时的全局工作流上下文引擎变量中
        taskVariables.value.businessTripCopyUsers = form.value.copyUserIds.join(',');
      }

      // 确保 variables 对象存在
      if (!form.value.variables) {
        form.value.variables = {};
      }
    }
  });
});

// 计算时长
const calculateDuration = () => {
  if (form.value.startTime && form.value.endTime) {
    const start = dayjs(form.value.startTime);
    const end = dayjs(form.value.endTime);
    const diff = end.diff(start, 'day');
    // 简单的天数计算，实际可能需要包含半天，这里先按自然日 + 1 (如果是同一天算1天) 或者 diff
    // 需求是 decimal(10,1)，通常是 0.5 天为单位。
    // 假设同一天算 1 天
    if (diff >= 0) {
      form.value.durationDays = diff + 1;
    } else {
      form.value.durationDays = 0;
    }
  } else {
    form.value.durationDays = undefined;
  }
};

// 延迟清除校验辅助方法
const refreshValidate = (index: number, field: string) => {
  setTimeout(() => {
    businessTripApplyFormRef.value?.clearValidate(`crmBusinessTripDetailsList.${index}.${field}`);
  }, 0);
};

// 打开项目选择
const currentEditRowIndex = ref<number>(-1);

const openProjectSelect = () => {
  if (isFormDisabled.value) return;
  currentEditRowIndex.value = -1; // -1 表示主表项目选择
  projectSelectRef.value?.open();
};

const openDetailProjectSelect = (index: number) => {
  if (isFormDisabled.value) return;
  currentEditRowIndex.value = index; // 记录当前操作的明细行索引
  projectSelectRef.value?.open();
};

// 项目选择回调
const projectInfoSelectCallBack = (data: ProjectInfoVO[]) => {
  if (data && data.length > 0) {
    const selectedProject = data[0];
    if (currentEditRowIndex.value === -1) {
      // 主表选择
      form.value.projectId = selectedProject.projectId;
      form.value.projectName = selectedProject.projectName;
      form.value.projectCode = selectedProject.projectCode;
    } else {
      // 明细行选择
      const index = currentEditRowIndex.value;
      if (form.value.crmBusinessTripDetailsList[index]) {
        form.value.crmBusinessTripDetailsList[index].projectId = selectedProject.projectId;
        form.value.crmBusinessTripDetailsList[index].projectName = selectedProject.projectName;
        form.value.crmBusinessTripDetailsList[index].projectCode = selectedProject.projectCode; // 自动带出项目号

        // 安装调试的出差申请时，自动带入明细项目的第一顺位项目经理作为下一步审批人
        if (form.value.tripType === '1' && selectedProject.managerId) {
          if (!form.value.variables) {
            form.value.variables = {};
          }
          form.value.variables.approverId = String(selectedProject.managerId);
          handleApproverSelectChange(String(selectedProject.managerId));
          // proxy?.$modal.msgSuccess('已关联项目经理作为下一步审批人');
        }
      }
    }
  }
};

// ================== 行程明细操作 ==================
const handleAddDetail = () => {
  form.value.crmBusinessTripDetailsList.push({
    tempId: Date.now() + Math.random(),
    tripLocation: undefined,
    startTime: undefined,
    endTime: undefined,
    durationDays: undefined,
    projectId: undefined,
    projectName: undefined,
    customerId: undefined,
    meetingName: undefined,
    exchangePurpose: undefined,
    exchangeFeedback: undefined,
    tripReason: undefined,
    remark: undefined
  });
};

// 默认展开所有行
const expandedRowKeys = computed(() => {
  return (form.value.crmBusinessTripDetailsList || []).map((item: any) => item.tripDetailsId || item.tempId);
});

const handleDeleteDetail = (index: number) => {
  form.value.crmBusinessTripDetailsList.splice(index, 1);
};

const calculateDetailDuration = (row: any) => {
  if (row.startTime && row.endTime) {
    const start = dayjs(row.startTime);
    const end = dayjs(row.endTime);
    const diff = end.diff(start, 'day');
    if (diff >= 0) {
      row.durationDays = diff + 1;
    } else {
      row.durationDays = 0;
    }
  }
};

// 自动计算汇总开始时间、结束时间和时长
watch(
  () => form.value.crmBusinessTripDetailsList,
  (newList) => {
    if (newList && newList.length > 0) {
      newList.forEach((item) => {
        if (item.startTime && item.endTime) {
          const start = dayjs(item.startTime);
          const end = dayjs(item.endTime);
          const diff = end.diff(start, 'day');
          item.durationDays = diff >= 0 ? diff + 1 : 0;
        } else {
          item.durationDays = 0;
        }
      });

      // 辅助归集第一行明细数据到主表，用于列表页展示
      form.value.tripLocation = newList[0].tripLocation;
      form.value.customerId = newList[0].customerId;
      form.value.exchangePurpose = newList[0].exchangePurpose;
      form.value.exchangeFeedback = newList[0].exchangeFeedback;
      form.value.meetingName = newList[0].meetingName;
      form.value.projectId = newList[0].projectId;
    }
  },
  { deep: true }
);

// 主卡片选择日期时，独立计算主卡片的总时长
watch(
  () => [form.value.startTime, form.value.endTime],
  ([newStart, newEnd]) => {
    if (newStart && newEnd) {
      const start = dayjs(newStart);
      const end = dayjs(newEnd);
      const diff = end.diff(start, 'day');
      form.value.durationDays = diff >= 0 ? diff + 1 : 0;
    } else {
      form.value.durationDays = 0;
    }
  }
);

// 审批人选择变更
const handleApproverSelectChange = (val: any) => {
  const user = userList.value.find((u) => u.userId === val);
  if (user) {
    form.value.variables = {
      ...form.value.variables,
      approverName: user.nickName
    };
  } else {
    form.value.variables = {
      ...form.value.variables,
      approverName: undefined
    };
  }
};

// 提交表单 (包含暂存和提交审批)
const submitForm = (status: string, mode: boolean) => {
  if (status === 'draft') {
    executeSubmit(status, mode);
    return;
  }
  businessTripApplyFormRef.value?.validate(async (valid) => {
    if (valid) {
      executeSubmit(status, mode);
    }
  });
};

const aggregateDetailsToForm = (): boolean => {
  const details = form.value.crmBusinessTripDetailsList;
  if (!details || details.length === 0) {
    proxy?.$modal.msgError('请添加至少一条行程明细！');
    return false;
  }

  form.value.tripLocation = details[0].tripLocation; // 取第一个行程地点作为主地点
  return true;
};

const executeSubmit = async (status: string, mode: boolean) => {
  buttonLoading.value = true;
  try {
    if (!aggregateDetailsToForm()) {
      buttonLoading.value = false;
      return;
    }

    if (status !== 'draft') {
      // 提交审批
      form.value.tripStatus = '2'; // 审批中
      form.value.flowStatus = 'waiting';
      // 将抄送人员ID数组转换为逗号分隔字符串
      const copyUserIdsStr = Array.isArray(form.value.copyUserIds) ? form.value.copyUserIds.join(',') : form.value.copyUserIds || '';
      form.value.variables = {
        ...form.value.variables,
        tripType: form.value.tripType,
        businessDirection: Number(form.value.businessDirection),
        businessTripCopyUsers: copyUserIdsStr
      };
      form.value.bizExt = {
        businessTitle: '出差申请',
        businessCode: form.value.applyCode
      };
      // 确保流程编码存在
      form.value.flowCode = FlowCodeEnum.BUSINESS_TRIP_CODE;
      const res = await submitBusinessTripApplyAndFlowStart(form.value);
      // 成功后处理
      proxy?.$modal.msgSuccess('提交成功');
      submitCallback();
    } else {
      // 暂存
      form.value.tripStatus = '1';
      form.value.flowStatus = 'draft';
      if (form.value.tripId) {
        await updateBusinessTripApply(form.value);
      } else {
        const res = await addBusinessTripApply(form.value);
      }
      proxy?.$modal.msgSuccess('暂存成功');
      submitCallback();
    }
  } catch (e) {
    console.error(e);
  } finally {
    buttonLoading.value = false;
  }
};

// 审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value?.init(form.value.tripId);
};

// 打开审批详情
const approvalVerifyOpen = async () => {
  if (!isFormDisabled.value) {
    let isValid = false;
    await businessTripApplyFormRef.value?.validate((valid) => {
      isValid = valid;
    });
    if (!isValid) return;

    if (!aggregateDetailsToForm()) return;

    buttonLoading.value = true;
    try {
      if (form.value.tripId) {
        await updateBusinessTripApply(form.value);
      }
    } finally {
      buttonLoading.value = false;
    }
  }
  await submitVerifyRef.value?.openDialog(routeParams.value.taskId);
};

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