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

    <el-card shadow="never" style="margin-top: 10px">
      <el-form
        ref="formRef"
        :model="form"
        :disabled="routeParams.type === 'view' || routeParams.type === 'approval'"
        :rules="rules"
        label-width="120px"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请编号" prop="applicationCode">
              <el-input v-model="form.applicationCode" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请日期" prop="applicationDate">
              <el-date-picker v-model="form.applicationDate" 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="applicantName">
              <el-input v-model="form.applicantName" placeholder="申请人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请部门" prop="applicantDeptName">
              <el-input v-model="form.applicantDeptName" placeholder="申请部门" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerUnitName">
              <el-autocomplete
                v-model="form.customerUnitName"
                :fetch-suggestions="queryCustomerSuggestions"
                clearable
                placeholder="请输入或选择客户名称"
                style="width: 100%"
                @select="handleCustomerSuggestSelect"
                @blur="onCustomerNameBlur"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客人姓名" prop="guestName">
              <el-input v-model="form.guestName" placeholder="请输入客人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人数" prop="peopleCount">
              <el-input-number v-model="form.peopleCount" :min="1" placeholder="请输入人数" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领用人" prop="recipientName">
              <el-input v-model="form.recipientName" placeholder="请输入领用人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="申请事由" prop="applicationReason">
              <el-input v-model="form.applicationReason" type="textarea" :rows="3" placeholder="请输入申请事由" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 礼品明细 -->
        <el-divider content-position="left">礼品明细</el-divider>
        <el-row :gutter="10" class="mb8" v-if="routeParams.type !== 'view' && routeParams.type !== 'approval'">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAddDetail">添加礼品</el-button>
          </el-col>
        </el-row>
        <el-table :data="form.detailList" border style="width: 100%">
          <el-table-column type="index" label="序号" width="52" align="center" />
          <el-table-column label="礼品" min-width="150" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                link
                icon="Search"
                :disabled="routeParams.type === 'view' || routeParams.type === 'approval'"
                @click="openGiftSelect(scope.$index)"
              >
                {{ scope.row.giftName || '选择礼品' }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" prop="specification" min-width="200" align="center" show-overflow-tooltip />
          <el-table-column label="单价(元)" prop="unitPrice" width="92" align="center">
            <template #default="scope">
              {{ scope.row.unitPrice ? '¥' + scope.row.unitPrice : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="库存数量" prop="inventoryQuantity" width="92" align="center" />
          <el-table-column label="申请数量" width="128" align="center">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.applicationQuantity"
                :min="1"
                :max="scope.row.inventoryQuantity || 999999"
                size="small"
                style="width: 100%"
                @change="calculateAmount(scope.$index)"
                :disabled="routeParams.type === 'view' || routeParams.type === 'approval'"
              />
            </template>
          </el-table-column>
          <el-table-column label="金额(元)" width="104" align="center">
            <template #default="scope">
              {{ scope.row.giftAmount ? '¥' + scope.row.giftAmount : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="140" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="备注" :disabled="routeParams.type === 'view' || routeParams.type === 'approval'" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="64" align="center" fixed="right" v-if="routeParams.type !== 'view' && routeParams.type !== 'approval'">
            <template #default="scope">
              <el-button link type="danger" icon="Delete" @click="handleDeleteDetail(scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 合计金额 -->
        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="24" style="text-align: right">
            <span style="font-size: 16px; font-weight: bold">申请总金额：¥{{ form.totalAmount || 0 }}</span>
          </el-col>
        </el-row>

        <!-- 审批信息（仅非市场部用户显示） -->
        <!--        <template v-if="showApproverSelector && !isFormDisabled">-->
        <!--          <el-divider content-position="left">审批信息</el-divider>-->
        <!--          <el-row :gutter="20">-->
        <!--            <el-col :span="12">-->
        <!--              <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} (${user.deptName || '未知部门'})`"-->
        <!--                    :value="user.userId"-->
        <!--                  />-->
        <!--                </el-select>-->
        <!--                <div style="font-size: 12px; color: #909399; margin-top: 4px">请选择部门/科室负责人作为第一级审批人</div>-->
        <!--              </el-form-item>-->
        <!--            </el-col>-->
        <!--          </el-row>-->
        <!--        </template>-->

        <!-- 备注 -->
        <el-divider content-position="left">其他信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 礼品选择弹窗（单选） -->
    <GiftSelect ref="giftSelectRef" :multiple="false" @confirm-call-back="handleGiftSelectConfirm" />

    <!-- 审批弹窗 -->
    <SubmitVerify ref="submitVerifyRef" @submitCallback="submitCallback" />
    <!-- 审批记录 -->
    <ApprovalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="CrmGiftApplyEdit" lang="ts">
import { addCrmGiftApply, getCrmGiftApply, giftApplySubmitAndFlowStart, updateCrmGiftApply } from '@/api/oa/crm/crmGiftApply';
import { CrmGiftApplyForm } from '@/api/oa/crm/crmGiftApply/types';
import GiftSelect from '@/components/GiftSelect/index.vue';
import { CrmGiftInfoVO } from '@/api/oa/crm/crmGiftInfo/types';
import { getCrmCustomerInfoList } from '@/api/oa/crm/customerInfo';
import { CustomerInfoVO } from '@/api/oa/crm/customerInfo/types';
import { getInfo } from '@/api/login';
import { listUser } from '@/api/system/user';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import approvalButton from '@/components/Process/approvalButton.vue';
import { ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';

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

// 流程编码：P0-1 修复为 CRMGIFT，与后端监听器保持一致
const FLOW_CODE = 'CRMGIFT';

// 路由参数（query模式与projectInfo一致）
const routeParams = ref<any>({});
const currentId = ref<string | undefined>('');

// 表单引用
const formRef = ref<ElFormInstance>();
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

// 状态
const buttonLoading = ref(false);
// 礼品选择组件引用与当前行索引
const giftSelectRef = ref<InstanceType<typeof GiftSelect>>();
const currentRowIndex = ref<number>(-1);
const customerList = ref<CustomerInfoVO[]>([]);
const userList = ref<any[]>([]); // 用户列表，用于审批人选择

// 市场部ID常量
const MARKETING_DEPT_ID = 106;
// 副总角色标识
const VICE_PRESIDENT_ROLE_KEY = 'FGFZ';
// 缓存登录用户角色，用于提交流程变量和界面联动
const currentUserRoles = ref<string[]>([]);

// 表单数据
const initFormData: CrmGiftApplyForm = {
  giftApplyId: undefined,
  applicationCode: undefined,
  applicantId: undefined,
  applicantName: undefined,
  applicantDeptId: undefined,
  applicantDeptName: undefined,
  applicationDate: undefined,
  customerUnitId: undefined,
  customerUnitName: undefined,
  guestName: undefined,
  peopleCount: 1,
  applicationReason: undefined,
  recipientId: undefined,
  recipientName: undefined,
  recipientDate: undefined,
  totalAmount: 0,
  applicationStatus: undefined,
  flowStatus: undefined,
  remark: undefined,
  detailList: [],
  variables: {} as any // 流程变量，包含approverId
};

const form = ref<CrmGiftApplyForm>({ ...initFormData });

// 表单校验规则
const rules = reactive({
  applicationCode: [], // 编号由后端自动生成，前端不需要校验
  applicationDate: [{ required: true, message: '申请日期不能为空', trigger: 'change' }],
  applicantId: [{ required: true, message: '申请人不能为空', trigger: 'blur' }],
  customerUnitName: [{ required: true, message: '客户名称不能为空', trigger: ['blur', 'change'] }]
  // 'variables.approverId': [
  //   {
  //     validator: (rule: any, value: any, callback: any) => {
  //       // 非市场部用户必须选择审批人
  //       if (showApproverSelector.value && !value) {
  //         callback(new Error('请选择下一步审批人'));
  //       } else {
  //         callback();
  //       }
  //     },
  //     trigger: 'change'
  //   }
  // ]
});

// 计算属性：判断是否显示审批人选择器（非市场部用户显示）
const showApproverSelector = computed(() => {
  return form.value.applicantDeptId !== undefined && form.value.applicantDeptId !== MARKETING_DEPT_ID && !isVicePresident.value;
});

// 计算属性：判断表单是否禁用
const isFormDisabled = computed(() => {
  return routeParams.value.type === 'view' || routeParams.value.type === 'approval';
});

// 通过登录用户角色判断是否副总，避免把组织身份写死到部门规则里
const isVicePresident = computed(() => currentUserRoles.value.includes(VICE_PRESIDENT_ROLE_KEY));

/** 加载客户列表 */
const loadCustomerList = async () => {
  try {
    const res = await getCrmCustomerInfoList({ activeFlag: '1' });
    customerList.value = res.data || [];
  } catch (error) {
    console.error('加载客户列表失败:', error);
  }
};

/** 加载表单数据 */
const loadFormData = async (id: string | number) => {
  try {
    proxy?.$modal.loading('正在加载数据...');
    const res = await getCrmGiftApply(id);
    Object.assign(form.value, res.data);
    if (!form.value.detailList) {
      form.value.detailList = [];
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    proxy?.$modal.msgError('加载数据失败');
  } finally {
    proxy?.$modal.closeLoading();
  }
};

/** 加载用户列表（用于审批人选择） */
const loadUserList = async () => {
  try {
    const res = await listUser({ pageNum: 1, pageSize: 1000 });
    userList.value = res.rows || [];
  } catch (error) {
    console.error('加载用户列表失败:', error);
  }
};

/** 初始化当前用户信息 */
const initUserInfo = async () => {
  try {
    const res = await getInfo();
    const user = res.data.user;
    currentUserRoles.value = Array.isArray(res.data.roles) ? res.data.roles : [];
    form.value.applicantId = user.userId;
    form.value.applicantName = user.nickName;
    form.value.applicantDeptId = user.deptId;
    form.value.applicantDeptName = user.deptName;
    // 默认领用人为申请人
    form.value.recipientId = user.userId;
    form.value.recipientName = user.nickName;
    // 初始化variables对象
    if (!form.value.variables) {
      form.value.variables = {};
    }
    // 角色快照写入变量，便于流程排查时直接看到发起时的身份信息
    form.value.variables = {
      ...form.value.variables,
      roleKeys: currentUserRoles.value.join(','),
      isVicePresident: isVicePresident.value ? '1' : '0'
    };
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

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

/** 根据客户名称与档案列表同步 customerUnitId（手填无匹配则清空关联 ID） */
const syncCustomerUnitIdFromName = () => {
  const name = form.value.customerUnitName?.trim();
  if (!name) {
    form.value.customerUnitId = undefined;
    return;
  }
  const matched = customerList.value.find((c) => c.customerName?.trim() === name);
  form.value.customerUnitId = matched?.customerId;
};

type CustomerNameSuggest = { value: string; customerId: string | number };

/** 客户名称联想（档案客户，可点选） */
const queryCustomerSuggestions = (queryString: string, cb: (rows: CustomerNameSuggest[]) => void) => {
  const q = (queryString || '').trim().toLowerCase();
  const rows = customerList.value
    .filter((c) => c.customerName)
    .filter((c) => !q || String(c.customerName).toLowerCase().includes(q))
    .map((c) => ({ value: c.customerName!, customerId: c.customerId }));
  cb(rows);
};

/** 从联想列表选中时写入档案客户 ID */
const handleCustomerSuggestSelect = (item: CustomerNameSuggest) => {
  form.value.customerUnitName = item.value;
  form.value.customerUnitId = item.customerId;
};

/** 失焦保留手输内容并同步关联客户 ID */
const onCustomerNameBlur = () => {
  syncCustomerUnitIdFromName();
};

/** 礼品选择回填 */
const handleGiftSelectConfirm = (data: CrmGiftInfoVO[]) => {
  if (currentRowIndex.value < 0 || !data || data.length === 0) {
    return;
  }
  const gift = data[0];
  const detail = form.value.detailList[currentRowIndex.value];
  detail.giftId = gift.giftId as any;
  detail.giftCode = gift.giftCode;
  detail.giftName = gift.giftName;
  detail.specification = gift.specification;
  detail.unitPrice = gift.unitPrice;
  detail.inventoryQuantity = gift.inventoryQuantity;
  detail.applicationQuantity = 1;
  calculateAmount(currentRowIndex.value);
};

/** 计算金额 */
const calculateAmount = (index: number) => {
  if (form.value.detailList) {
    const detail = form.value.detailList[index];
    if (detail.unitPrice && detail.applicationQuantity) {
      detail.giftAmount = Number((detail.unitPrice * detail.applicationQuantity).toFixed(2));
    }
    calculateTotalAmount();
  }
};

/** 计算总金额 */
const calculateTotalAmount = () => {
  if (form.value.detailList) {
    form.value.totalAmount = form.value.detailList.reduce((sum, item) => sum + (item.giftAmount || 0), 0);
  }
};

/** 添加礼品明细 */
const handleAddDetail = () => {
  if (!form.value.detailList) {
    form.value.detailList = [];
  }
  form.value.detailList.push({
    giftId: undefined,
    giftCode: undefined,
    giftName: undefined,
    specification: undefined,
    unitPrice: undefined,
    inventoryQuantity: undefined,
    applicationQuantity: 1,
    giftAmount: undefined,
    remark: undefined
  });
};

/** 打开礼品选择弹窗 */
const openGiftSelect = (index: number) => {
  currentRowIndex.value = index;
  giftSelectRef.value?.open();
};

/** 删除礼品明细 */
const handleDeleteDetail = (index: number) => {
  if (form.value.detailList) {
    form.value.detailList.splice(index, 1);
    calculateTotalAmount();
  }
};

/** 提交表单 */
const submitForm = async (status: string) => {
  try {
    await formRef.value?.validate();
    syncCustomerUnitIdFromName();

    // P0-1: 校验业务状态 - 只有草稿状态才能修改
    if (form.value.giftApplyId && form.value.applicationStatus !== '1') {
      proxy?.$modal.msgWarning('只有草稿状态的礼品申请才能修改');
      return;
    }

    // 校验明细
    if (!form.value.detailList || form.value.detailList.length === 0) {
      proxy?.$modal.msgWarning('请至少添加一条礼品明细');
      return;
    }
    for (const detail of form.value.detailList) {
      if (!detail.giftId) {
        proxy?.$modal.msgWarning('请选择礼品');
        return;
      }
      if (!detail.applicationQuantity || detail.applicationQuantity <= 0) {
        proxy?.$modal.msgWarning('申请数量必须大于0');
        return;
      }
    }

    buttonLoading.value = true;

    if (status === 'draft') {
      // 暂存
      form.value.applicationStatus = '1';
      form.value.flowStatus = 'draft';
      if (form.value.giftApplyId) {
        await updateCrmGiftApply(form.value);
      } else {
        const res = await addCrmGiftApply(form.value);
        form.value.giftApplyId = res.data?.giftApplyId;
        // 新增成功后刷新数据以获取后端生成的编号
        if (res.data?.applicationCode) {
          form.value.applicationCode = res.data.applicationCode;
        }
      }
      proxy?.$modal.msgSuccess('暂存成功');
    } else {
      // 提交审批
      form.value.flowCode = FLOW_CODE;
      // 这里同时传部门与角色变量，原因是礼品流程既要按部门分支，也要优先识别“副总直达市场经理”
      form.value.variables = {
        ...form.value.variables, // 保留 approverId 和 approverName
        giftApplyId: form.value.giftApplyId,
        applicationCode: form.value.applicationCode,
        applicantId: form.value.applicantId,
        applicantName: form.value.applicantName,
        deptId: form.value.applicantDeptId,
        deptName: form.value.applicantDeptName,
        roleKeys: currentUserRoles.value.join(','),
        isVicePresident: isVicePresident.value ? '1' : '0',
        totalAmount: form.value.totalAmount,
        customerUnitName: form.value.customerUnitName
      };
      // P2-2: 完善 businessTitle 格式，包含申请人和客户单位信息
      form.value.bizExt = {
        businessTitle: `礼品申请审批`,
        businessCode: form.value.applicationCode,
        businessId: String(form.value.giftApplyId)
      };
      try {
        await giftApplySubmitAndFlowStart(form.value);
        proxy?.$modal.msgSuccess('提交成功');
      } catch (submitError: any) {
        // ⭐ 捕获库存不足异常，友好提示
        if (submitError?.message && submitError.message.includes('库存不足')) {
          // 将换行符转换为HTML换行标签，便于弹窗展示
          const formattedMsg = submitError.message.replace(/\n/g, '<br/>');
          await ElMessageBox.alert(formattedMsg, '库存不足提示', {
            type: 'warning',
            dangerouslyUseHTMLString: true,
            confirmButtonText: '我知道了'
          });
          return; // 不关闭页面，允许用户调整
        }
        throw submitError; // 重新抛出其他异常
      }
    }

    // 关闭页面返回列表
    proxy?.$tab.closePage();
    router.go(-1);
  } catch (error: any) {
    console.error('提交失败:', error);
    if (error?.message) {
      proxy?.$modal.msgError(error.message);
    }
  } finally {
    buttonLoading.value = false;
  }
};

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

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

/** 审批回调 */
const submitCallback = async () => {
  await proxy?.$tab.closePage(route);
  router.go(-1);
};

onMounted(async () => {
  // 获取路由参数（query模式）
  routeParams.value = route.query;
  currentId.value = (route.query.id as string) || undefined;

  // 加载用户列表（用于审批人选择）
  await loadUserList();

  // 初始化用户信息（申请人）
  await initUserInfo();

  // 查询客户列表
  await loadCustomerList();

  // 如果有ID则查询详情
  if (currentId.value) {
    await loadFormData(currentId.value);
  } else {
    // 新增时初始化默认数据（保留 initUserInfo 已写入的申请人/领用人信息）
    // 注意：initFormData 中 recipientName 为 undefined，直接 Object.assign 会覆盖已有值
    Object.assign(form.value, { ...initFormData, ...form.value });
    console.debug('[crmGiftApply] init defaults merged', {
      applicantName: form.value.applicantName,
      recipientName: form.value.recipientName
    });
    // 申请日期默认当天，便于快速选择
    form.value.applicationDate = dayjs().format('YYYY-MM-DD');
    calculateTotalAmount();
  }
});
</script>

<style scoped>
.el-divider--horizontal {
  margin: 20px 0 15px 0;
}
</style>
