<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="申请编号" prop="applicationCode">
              <el-input v-model="queryParams.applicationCode" placeholder="请输入申请编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="申请人" prop="applicantName">
              <el-input v-model="queryParams.applicantName" placeholder="请输入申请人姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerUnitName">
              <el-input v-model="queryParams.customerUnitName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="申请状态" prop="applicationStatus">
              <el-select v-model="queryParams.applicationStatus" placeholder="请选择" clearable>
                <el-option v-for="dict in gift_apply_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-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oa/crm:crmGiftApply:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/crm:crmGiftApply:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="crmGiftApplyList" @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="52" align="center" />
        <el-table-column label="申请编号" align="center" prop="applicationCode" min-width="140" show-overflow-tooltip v-if="columns[0].visible" />
        <el-table-column label="申请人" align="center" prop="applicantName" min-width="88" show-overflow-tooltip v-if="columns[1].visible" />
        <el-table-column label="申请部门" align="center" prop="applicantDeptName" min-width="110" show-overflow-tooltip v-if="columns[2].visible" />
        <el-table-column label="申请日期" align="center" prop="applicationDate" width="112" v-if="columns[3].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applicationDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" prop="customerUnitName" min-width="200" show-overflow-tooltip v-if="columns[4].visible" />
        <el-table-column label="客人姓名" align="center" prop="guestName" min-width="90" show-overflow-tooltip v-if="columns[5].visible" />
        <el-table-column label="人数" align="center" prop="peopleCount" width="64" v-if="columns[6].visible" />
        <el-table-column label="申请总金额" align="center" prop="totalAmount" width="108" v-if="columns[7].visible">
          <template #default="scope">
            <span>{{ scope.row.totalAmount ? '¥' + scope.row.totalAmount : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请状态" align="center" prop="applicationStatus" width="96" v-if="columns[8].visible">
          <template #default="scope">
            <dict-tag :options="gift_apply_status" :value="scope.row.applicationStatus" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="流程状态" align="center" prop="flowStatus" width="100" v-if="columns[9].visible">
          <template #default="scope">
            <dict-tag :options="wf_business_status" :value="scope.row.flowStatus" />
          </template>
        </el-table-column> -->
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[9].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 查看：非草稿状态 -->
            <el-tooltip content="查看" placement="top" v-if="scope.row.applicationStatus !== '1'">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['oa/crm:crmGiftApply:query']"></el-button>
            </el-tooltip>
            <!-- 修改：仅草稿状态 -->
            <el-tooltip content="修改" placement="top" v-if="scope.row.applicationStatus === '1'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/crm:crmGiftApply:edit']"></el-button>
            </el-tooltip>
            <!-- 删除：仅草稿状态 -->
            <el-tooltip content="删除" placement="top" v-if="scope.row.applicationStatus === '1'">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oa/crm:crmGiftApply:remove']"></el-button>
            </el-tooltip>
            <!-- ⚭ 发放记录：仅已审批状态且已发放（审批通过自动发放） -->
            <el-tooltip content="发放记录" placement="top" v-if="scope.row.applicationStatus === '3' && scope.row.recipientDate">
              <el-button
                link
                type="success"
                icon="Tickets"
                @click="handleIssueRecord(scope.row)"
                v-hasPermi="['oa/crm:crmGiftApply:query']"
              ></el-button>
            </el-tooltip>
            <!-- 审批记录：审批中或已完成 -->
            <el-tooltip content="审批记录" placement="top" v-if="scope.row.applicationStatus === '2' || scope.row.applicationStatus === '3'">
              <el-button
                link
                type="primary"
                icon="Tickets"
                @click="handleApprovalRecord(scope.row)"
                v-hasPermi="['oa/crm:crmGiftApply:query']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 审批记录组件 -->
    <ApprovalRecord ref="approvalRecordRef" />

    <!-- ⚭ 发放记录弹窗 -->
    <el-dialog title="发放记录" v-model="issueRecordDialogVisible" width="800px" append-to-body>
      <el-table :data="issueRecordList" border max-height="400">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="礼品名称" prop="giftName" min-width="120" align="center" />
        <el-table-column label="规格型号" prop="specification" min-width="100" align="center" />
        <el-table-column label="发放数量" prop="issueQuantity" width="90" align="center" />
        <el-table-column label="发放前库存" prop="beforeInventory" width="100" align="center" />
        <el-table-column label="发放后库存" prop="afterInventory" width="100" align="center" />
        <el-table-column label="发放时间" prop="issueDate" width="160" align="center">
          <template #default="scope">
            <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="领用人" prop="recipientName" width="100" align="center" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="issueRecordDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CrmGiftApply" lang="ts">
import { delCrmGiftApply, listCrmGiftApply } from '@/api/oa/crm/crmGiftApply';
import { listCrmGiftIssueRecord } from '@/api/oa/crm/crmGiftIssueRecord';
import { CrmGiftApplyQuery, CrmGiftApplyVO } from '@/api/oa/crm/crmGiftApply/types';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();
const { gift_apply_status, wf_business_status } = toRefs<any>(proxy?.useDict('gift_apply_status', 'wf_business_status'));

// 审批记录组件引用
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

const crmGiftApplyList = ref<CrmGiftApplyVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);

// ⚭ 发放记录弹窗相关
const issueRecordDialogVisible = ref(false);
const issueRecordList = ref<any[]>([]);

const queryFormRef = ref<ElFormInstance>();

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `申请编号`, visible: true },
  { key: 1, label: `申请人`, visible: true },
  { key: 2, label: `申请部门`, visible: true },
  { key: 3, label: `申请日期`, visible: true },
  { key: 4, label: `客户名称`, visible: true },
  { key: 5, label: `客人姓名`, visible: true },
  { key: 6, label: `人数`, visible: true },
  { key: 7, label: `申请总金额`, visible: true },
  { key: 8, label: `申请状态`, visible: true },
  { key: 9, label: `创建时间`, visible: true }
]);

const queryParams = reactive<CrmGiftApplyQuery>({
  pageNum: 1,
  pageSize: 10,
  applicationCode: undefined,
  applicantName: undefined,
  customerUnitName: undefined,
  applicationStatus: undefined
});

/** 查询礼品申请列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCrmGiftApply(queryParams);
  crmGiftApplyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: CrmGiftApplyVO[]) => {
  ids.value = selection.map((item) => item.giftApplyId);
};

/** 新增按钮操作 - 跳转到编辑页（query模式，与projectInfo一致） */
const handleAdd = () => {
  proxy?.$tab.closePage(route);
  router.push({ path: '/gift/crmGiftApply/edit', query: { type: 'add' } });
};

/** 修改按钮操作 - 跳转到编辑页 */
const handleUpdate = (row: CrmGiftApplyVO) => {
  proxy?.$tab.closePage(route);
  router.push({ path: '/gift/crmGiftApply/edit', query: { id: row.giftApplyId, type: 'update' } });
};

/** 查看按钮操作 - 跳转到查看页 */
const handleView = (row: CrmGiftApplyVO) => {
  proxy?.$tab.closePage(route);
  router.push({ path: '/gift/crmGiftApply/edit', query: { id: row.giftApplyId, type: 'view' } });
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: CrmGiftApplyVO) => {
  const _giftApplyIds = row?.giftApplyId || ids.value;
  await proxy?.$modal.confirm('是否确认删除礼品申请编号为"' + _giftApplyIds + '"的数据项？').finally(() => (loading.value = false));
  await delCrmGiftApply(_giftApplyIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/crm/crmGiftApply/export',
    {
      ...queryParams
    },
    `crmGiftApply_${new Date().getTime()}.xlsx`
  );
};

/** ⚭ 发放记录按钮操作 */
const handleIssueRecord = async (row: CrmGiftApplyVO) => {
  try {
    proxy?.$modal.loading('正在加载发放记录...');
    const res = await listCrmGiftIssueRecord({ applicationId: row.giftApplyId, pageNum: 1, pageSize: 100 });
    issueRecordList.value = res.rows || [];
    issueRecordDialogVisible.value = true;
  } catch (error) {
    console.error('加载发放记录失败:', error);
    proxy?.$modal.msgError('加载发放记录失败');
  } finally {
    proxy?.$modal.closeLoading();
  }
};

onMounted(() => {
  getList();
});
</script>
