<template>
  <div class="page-container">
    <PageTitle title="开票管理" />

    <!-- 搜索条件区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="开票编号">
          <el-input v-model="searchForm.keyword" placeholder="请输入开票编号" clearable @clear="handleSearch" />
        </el-form-item>
        <el-form-item label="开票日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleSearch"
          />
        </el-form-item>
        <el-form-item label="开票状态">
          <el-select v-model="searchForm.invoiceStatus" placeholder="请选择开票状态" clearable @change="handleSearch">
            <el-option v-for="item in invoiceStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="loading" :data="tableData" border style="width: 100%">
      <el-table-column prop="statementInvoiceNo" label="开票编号" min-width="130" align="center" />
      <el-table-column prop="invoiceTime" label="开票时间" min-width="110" align="center">
        <template #default="scope">
          <span>{{ parseTime(scope.row.invoiceTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="customerName" label="客户名称" min-width="110" align="center" />
      <el-table-column prop="amount" label="开票金额" min-width="110" align="center">
        <template #default="{ row }">¥{{ row.amount.toFixed(2) }}</template>
      </el-table-column>
      <el-table-column prop="invoiceStatus" label="开票状态" min-width="90" align="center">
        <template #default="{ row }">
          {{ getDictLabel(invoice_status, row.invoiceStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="handleView(row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-wrapper">
      <TablePagination v-model:page="pagination.page" v-model:pageSize="pagination.pageSize" :total="pagination.total" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch, computed, getCurrentInstance, toRefs } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { PageTitle, TablePagination } from '@/components';
import { getStatementInvoiceList } from '@/api/pc/enterprise/statement';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { invoice_issuance_status, invoice_status } = toRefs<any>(proxy?.useDict('invoice_issuance_status', 'invoice_status'));
// const { invoice_status } = toRefs<any>(proxy?.useDict('invoice_issuance_status', 'statement_status', 'invoice_status'));
const searchForm = reactive({
  keyword: '',
  dateRange: [],
  invoiceStatus: ''
});
const form = reactive({
  statementOrderIds: []
});

// 从字典生成选项，添加"全部"选项
const invoiceStatusOptions = computed(() => [{ label: '全部', value: '' }, ...(invoice_status.value || [])]);

const pagination = reactive({ page: 1, pageSize: 5, total: 0 });
const tableData = ref<any[]>([]);
const loading = ref(false);
const router = useRouter();
// 加载开票列表
const loadStatementInvoice = async () => {
  try {
    loading.value = true;
    const queryParams = {
      pageNum: pagination.page,
      pageSize: pagination.pageSize,
      statementInvoiceNo: searchForm.keyword,
      invoiceStatus: searchForm.invoiceStatus,
      params: {} as any
    };

    // 添加日期范围参数
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      queryParams.params.beginTime = searchForm.dateRange[0];
      queryParams.params.endTime = searchForm.dateRange[1];
    }

    const res = await getStatementInvoiceList(queryParams);

    if (res.code === 200 && res.rows) {
      tableData.value = res.rows.map((item: any) => ({
        id: item.id,
        statementInvoiceNo: item.statementInvoiceNo,
        invoiceTime: item.invoiceTime,
        customerName: item.customerName,
        amount: parseFloat(item.invoiceAmount as any) || 0,
        invoiceStatus: item.invoiceStatus,
        payStatus: item.isPaymentStatus
      }));
      pagination.total = res.total || 0;
    }
  } catch (error) {
    console.error('加载对账单列表失败:', error);
    ElMessage.error('加载对账单列表失败');
  } finally {
    loading.value = false;
  }
};

const getDictLabel = (dictOptions: any[], value: string) => {
  if (!dictOptions || !value) return value;
  const dict = dictOptions.find((item) => item.value === value);
  return dict ? dict.label : value;
};

// 监听分页变化
watch(
  () => [pagination.page, pagination.pageSize],
  () => {
    loadStatementInvoice();
  }
);

// 监听搜索条件变化
watch(
  () => [searchForm.keyword, searchForm.dateRange, searchForm.invoiceStatus],
  () => {
    pagination.page = 1;
    loadStatementInvoice();
  }
);

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadStatementInvoice();
};

// 重置
const handleReset = () => {
  searchForm.keyword = '';
  searchForm.dateRange = [];
  searchForm.invoiceStatus = '';
  pagination.page = 1;
  loadStatementInvoice();
};

// 页面加载时获取数据
onMounted(() => {
  // loadDictData();
  loadStatementInvoice();
});

const handleView = (row: any) => {
  router.push(`/reconciliation/invoiceManage/detail?id=${row.id}`);
};
</script>

<style scoped>
.search-area {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.search-area .el-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-end;
}

.search-area .el-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

.search-area .el-input,
.search-area .el-select,
.search-area .el-date-picker {
  width: 200px;
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
