<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">
            <el-form-item label="对账单号" prop="statementOrderNo">
              <el-input v-model="queryParams.statementOrderNo" placeholder="请输入对账单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="对账日期" prop="statementDate">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="对账状态" prop="statementStatus">
              <el-select v-model="queryParams.statementStatus" placeholder="请选择对账状态" clearable>
                <el-option v-for="dict in statement_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="支付状态" prop="isPaymentStatus">
              <el-select v-model="queryParams.isPaymentStatus" placeholder="请选择付款状态" clearable>
                <el-option v-for="dict in payment_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="22"> 对账管理信息列表 </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['bill:statementOrder:add']">新增</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="statementOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="对账单号" align="center" prop="statementOrderNo" />
        <el-table-column label="对账日期" align="center" prop="statementDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.statementDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="对账金额" align="center" prop="amount" />
        <el-table-column label="客户编号" align="center" prop="customerNo" />
        <el-table-column label="客户名称" align="center" prop="customerName" />
        <el-table-column label="对账状态" align="center" prop="statementStatus">
          <template #default="scope">
            <dict-tag :options="statement_status" :value="scope.row.statementStatus" />
          </template>
        </el-table-column>
        <el-table-column label="开票状态" align="center" prop="isInvoiceStatus">
          <template #default="scope">
            <dict-tag :options="invoice_issuance_status" :value="scope.row.isInvoiceStatus" />
          </template>
        </el-table-column>
        <el-table-column label="支付状态" align="center" prop="isPaymentStatus">
          <template #default="scope">
            <dict-tag :options="payment_status" :value="scope.row.isPaymentStatus" />
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="300" fixed="right">
          <template #default="scope">
            <template v-for="btn in getAvailableButtons(scope.row.statementStatus)" :key="btn.action">
              <el-button link type="primary" @click="btn.handler(scope.row)" v-hasPermi="[btn.permission]">
                {{ btn.label }}
              </el-button>
            </template>
          </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>
    <!--新增对账的抽屉 -->
    <add-drawer ref="addDrawerRef" @success="getList" />
    <!--查看对账的抽屉 -->
    <detail-drawer ref="detailDrawerRef" @success="getList" />
  </div>
</template>

<script setup name="StatementOrder" lang="ts">
import { listStatementOrder, getStatementOrder, changeStatus } from '@/api/bill/statementOrder';
import { StatementOrderVO, StatementOrderQuery, StatementOrderForm } from '@/api/bill/statementOrder/types';
import AddDrawer from './addDrawer.vue';
import DetailDrawer from './detailDrawer.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { statement_status, statement_order_type, invoice_issuance_status, payment_status } = toRefs<any>(
  proxy?.useDict('statement_status', 'statement_order_type', 'invoice_issuance_status', 'payment_status')
);

const statementOrderList = ref<StatementOrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const addDrawerRef = ref<InstanceType<typeof AddDrawer>>();
const detailDrawerRef = ref<InstanceType<typeof DetailDrawer>>();
const queryFormRef = ref<ElFormInstance>();
const statementOrderFormRef = ref<ElFormInstance>();
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: StatementOrderForm = {
  id: undefined,
  statementOrderNo: undefined,
  customerId: undefined,
  customerNo: undefined,
  customerName: undefined,
  amount: undefined,
  statementSelf: undefined,
  statementSelfPhone: undefined,
  statementStatus: undefined,
  isPaymentStatus: undefined,
  isInvoiceStatus: undefined,
  statementDate: undefined,
  annexAddress: undefined,
  rejectRemark: undefined,
  remark: undefined,
  detailList: [],
  productList: []
};
const data = reactive<PageData<StatementOrderForm, StatementOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    statementOrderNo: undefined,
    customerId: undefined,
    customerNo: undefined,
    customerName: undefined,
    amount: undefined,
    statementSelf: undefined,
    statementSelfPhone: undefined,
    statementStatus: undefined,
    isPaymentStatus: undefined,
    isInvoiceStatus: undefined,
    statementDate: undefined,
    annexAddress: undefined,
    rejectRemark: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {}
});

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

// 对账单状态枚举
enum StatementStatus {
  DRAFT = 0, // 待确认
  PENDING = 1, // 待对账
  CONFIRMED = 2, // 已对账
  REJECTED = 3, // 已驳回
  OBSOLETE = 4 // 已作废
}

// 按钮配置类型
interface ActionButton {
  action: string;
  label: string;
  handler: (row: StatementOrderVO) => void;
  permission: string;
}

/** 查询对账单主列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStatementOrder(proxy?.addDateRange(queryParams.value, dateRange.value));
  statementOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  statementOrderFormRef.value?.resetFields();
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: StatementOrderVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // 打开抽屉
  addDrawerRef.value?.open();
};

/** 修改按钮操作 */
const handleUpdate = async (row?: StatementOrderVO) => {
  const _id = row?.id || ids.value[0];
  const res = await getStatementOrder(_id);
  // 打开抽屉，传递id和数据
  addDrawerRef.value?.open(_id, res.data);
};

/** 查看按钮操作 */
const handleDetail = async (row?: StatementOrderVO) => {
  const _id = row?.id || ids.value[0];
  const res = await getStatementOrder(_id);
  // 打开抽屉，传递id和数据
  detailDrawerRef.value?.open(_id, res.data);
};

/** 发送按钮操作 */
const handleSend = async (row?: StatementOrderVO) => {
  const _no = row?.statementOrderNo;
  const _ids = row?.id;
  const oldValue = row.statementStatus; // 保存旧值
  await proxy?.$modal.confirm('是否发送当前账单编号【' + _no + '】吗？').finally(() => (loading.value = false));
  //todo 发送
  try {
    await changeStatus(_ids, '1'); // 传新值 1 待确认
  } catch (e) {
    // 恢复旧值
    row.statementStatus = oldValue;
  }
  proxy?.$modal.msgSuccess('发送成功');
  await getList();
};

/** 撤回按钮操作 */
const handleWithdraw = async (row?: StatementOrderVO) => {
  const _no = row?.statementOrderNo;
  const _ids = row?.id;
  const oldValue = row.statementStatus; // 保存旧值
  await proxy?.$modal.confirm('是否撤回当前账单编号【' + _no + '】吗？').finally(() => (loading.value = false));
  //todo 撤回
  try {
    await changeStatus(_ids, '0'); // 传新值 0 待确认
  } catch (e) {
    // 恢复旧值
    row.statementStatus = oldValue;
  }
  proxy?.$modal.msgSuccess('撤回成功');
  await getList();
};

/** 作废按钮操作 */
const handleObsolete = async (row?: StatementOrderVO) => {
  const _no = row?.statementOrderNo;
  const oldValue = row.statementStatus; // 保存旧值
  await proxy?.$modal.confirm('是否作废当前账单编号【' + _no + '】吗？').finally(() => (loading.value = false));
  await changeStatus(row.id, '4'); // 传新值 4 - 作废
  proxy?.$modal.msgSuccess('作废成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'bill/statementOrder/export',
    {
      ...queryParams.value
    },
    `statementOrder_${new Date().getTime()}.xlsx`
  );
};

// 按钮配置映射：状态 -> 可用按钮列表
const buttonConfigMap: Record<number, ActionButton[]> = {
  [StatementStatus.DRAFT]: [
    { action: 'detail', label: '查看', handler: handleDetail, permission: 'bill:statementOrder:edit' },
    { action: 'edit', label: '编辑', handler: handleUpdate, permission: 'bill:statementOrder:edit' },
    { action: 'send', label: '发送对账单', handler: handleSend, permission: 'bill:statementOrder:edit' },
    { action: 'withdraw', label: '撤回', handler: handleWithdraw, permission: 'bill:statementOrder:edit' },
    { action: 'obsolete', label: '作废', handler: handleObsolete, permission: 'bill:statementOrder:remove' }
  ],
  [StatementStatus.PENDING]: [
    { action: 'detail', label: '查看', handler: handleDetail, permission: 'bill:statementOrder:edit' },
    { action: 'edit', label: '编辑', handler: handleUpdate, permission: 'bill:statementOrder:edit' },
    { action: 'withdraw', label: '撤回', handler: handleWithdraw, permission: 'bill:statementOrder:edit' },
    { action: 'obsolete', label: '作废', handler: handleObsolete, permission: 'bill:statementOrder:remove' }
  ],
  [StatementStatus.CONFIRMED]: [
    { action: 'detail', label: '查看', handler: handleDetail, permission: 'bill:statementOrder:edit' },
    { action: 'obsolete', label: '作废', handler: handleObsolete, permission: 'bill:statementOrder:remove' }
  ],
  [StatementStatus.REJECTED]: [
    { action: 'detail', label: '查看', handler: handleDetail, permission: 'bill:statementOrder:edit' },
    { action: 'edit', label: '编辑', handler: handleUpdate, permission: 'bill:statementOrder:edit' },
    { action: 'send', label: '发送对账单', handler: handleSend, permission: 'bill:statementOrder:edit' },
    { action: 'obsolete', label: '作废', handler: handleObsolete, permission: 'bill:statementOrder:remove' }
  ],
  [StatementStatus.OBSOLETE]: [{ action: 'detail', label: '查看', handler: handleDetail, permission: 'bill:statementOrder:edit' }]
};

/**
 * 根据对账单状态获取可用按钮列表
 * @param status 对账单状态
 * @returns 可用按钮配置数组
 */
const getAvailableButtons = (status: number): ActionButton[] => {
  return buttonConfigMap[status] || [{ action: 'detail', label: '查看', handler: handleDetail, permission: 'bill:statementOrder:edit' }];
};

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