<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="statementInvoiceNo">
              <el-input v-model="queryParams.statementInvoiceNo" 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="customerId">
              <el-select
                v-model="queryParams.customerId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入客户名称"
                :remote-method="remoteSearchCustomer"
                :loading="customerLoading"
                clearable
                style="width: 100%"
                @change="handleCustomerChange"
              >
                <el-option v-for="item in customerOptions" :key="item.id" :label="item.customerName" :value="item.id" />
              </el-select>
            </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="invoiceStatus">
              <el-select v-model="queryParams.invoiceStatus" placeholder="请选择开票状态" clearable>
                <el-option v-for="dict in invoice_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="对账单号" prop="statementOrderNo">
              <el-input v-model="queryParams.statementOrderNo" placeholder="请输入对账单号" clearable @keyup.enter="handleQuery" />
            </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:statementInvoice:add']">新增</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="statementInvoiceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="开票编号" align="center" prop="statementInvoiceNo" />
        <el-table-column label="开票时间" align="center" prop="invoiceTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.invoiceTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="center" prop="customerName" />
        <el-table-column label="开票金额" align="center" prop="invoiceAmount">
          <template #default="scope">
            <span>{{ Number(scope.row.invoiceAmount).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开票状态" align="center" prop="invoiceStatus">
          <template #default="scope">
            <dict-tag :options="invoice_status" :value="scope.row.invoiceStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <template v-for="btn in getAvailableButtons(scope.row.invoiceStatus)" :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="StatementInvoice" lang="ts">
import { listStatementInvoice, getStatementInvoice, changeStatus } from '@/api/bill/statementInvoice';
import { StatementInvoiceVO, StatementInvoiceQuery, StatementInvoiceForm } from '@/api/bill/statementInvoice/types';
import { getListBycustomerName } from '@/api/customer/customerFile/customerInfo';
import { CustomerInfoVO } from '@/api/customer/customerFile/customerInfo/types';
import AddDrawer from './addDrawer.vue';
import DetailDrawer from './detailDrawer.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { invoice_status } = toRefs<any>(proxy?.useDict('invoice_status'));
const addDrawerRef = ref<InstanceType<typeof AddDrawer>>();
const detailDrawerRef = ref<InstanceType<typeof DetailDrawer>>();
const statementInvoiceList = ref<StatementInvoiceVO[]>([]);
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 dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const statementInvoiceFormRef = ref<ElFormInstance>();
const customerLoading = ref(false);
const customerOptions = ref<CustomerInfoVO[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 发票单状态枚举
enum InvoiceStatus {
  DRAFT = 0, // 待确认
  PENDING = 1, // 待对账
  CONFIRMED = 2, // 已对账
  OBSOLETE = 3 // 已作废
}

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

const initFormData: StatementInvoiceForm = {
  id: undefined,
  statementInvoiceNo: undefined,
  customerId: undefined,
  customerNo: undefined,
  customerName: undefined,
  invoiceAmount: undefined,
  invoiceStatus: undefined,
  invoiceTime: undefined,
  rejectRemark: undefined,
  remark: undefined
};
const data = reactive<PageData<StatementInvoiceForm, StatementInvoiceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    statementInvoiceNo: undefined,
    customerId: undefined,
    customerNo: undefined,
    customerName: undefined,
    invoiceAmount: undefined,
    invoiceStatus: undefined,
    invoiceTime: undefined,
    rejectRemark: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {}
});

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

/** 查询销售发票主列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStatementInvoice(proxy?.addDateRange(queryParams.value, dateRange.value));
  statementInvoiceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 远程搜索客户 */
const remoteSearchCustomer = async (query: string) => {
  if (query) {
    customerLoading.value = true;
    try {
      const res = await getListBycustomerName(query);
      customerOptions.value = res.data;
    } catch (error) {
      console.error(error);
    } finally {
      customerLoading.value = false;
    }
  } else {
    customerOptions.value = [];
  }
};

/** 客户变更 */
const handleCustomerChange = async (customerId: string | number) => {
  if (customerId) {
    const customer = customerOptions.value.find((item) => item.id === customerId);
    if (customer) {
      form.value.customerName = customer.customerName;
      form.value.customerNo = customer.customerNo;
    }
  } else {
    form.value.customerName = undefined;
    form.value.customerNo = undefined;
  }
};

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: StatementInvoiceVO[]) => {
  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?: StatementInvoiceVO) => {
  const _id = row?.id || ids.value[0];
  const res = await getStatementInvoice(_id);
  // 打开抽屉，传递id和数据
  addDrawerRef.value?.open(_id, res.data);
};

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

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

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

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

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

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

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

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