<template>
  <div class="page-container">
    <PageTitle title="对账单管理" />
    <SearchBar :form="searchForm" :filters="filters" placeholder="对账编号" />
    <el-table v-loading="loading" :data="tableData" border style="width: 100%">
      <el-table-column prop="billNo" label="对账编号" min-width="130" align="center" />
      <el-table-column prop="billDate" label="对账日期" min-width="110" align="center">
        <template #default="{ row }">{{ parseTime(row.billDate, '{y}-{m}-{d}') }}</template>
      </el-table-column>
      <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="billStatus" label="对账状态" min-width="90" align="center">
        <template #default="{ row }">
          {{ getDictLabel(statement_status, row.billStatus) }}
        </template>
      </el-table-column>
      <el-table-column prop="invoiceStatus" label="开票状态" min-width="90" align="center">
        <template #default="{ row }">
          <span :style="{ color: row.invoiceStatus === '0' ? '#e60012' : '' }">
            {{ getDictLabel(invoice_issuance_status, row.invoiceStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="payStatus" label="支付状态" min-width="90" align="center">
        <template #default="{ row }">
          {{ getDictLabel(payment_status, row.payStatus) }}
        </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>
          <el-button type="danger" link size="small" @click="handleConfirm(row)" :disabled="row.billStatus !== '1'">确认</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>

    <!-- 详情弹窗 -->
    <DetailDialog ref="detailDialogRef" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PageTitle, SearchBar, TablePagination } from '@/components';
import { getStatementList, getStatementInfo, confirmStatement } from '@/api/pc/enterprise/statement';
import type { StatementOrder } from '@/api/pc/enterprise/statementTypes';
import DetailDialog from './detail.vue';

const detailDialogRef = ref<InstanceType<typeof DetailDialog>>();

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

const searchForm = reactive({
  keyword: '', // 对账编号
  dateRange: [],
  billStatus: '',
  invoiceStatus: '',
  payStatus: ''
});

const billStatusOptions = ref([{ label: '全部', value: '' }]);
const invoiceStatusOptions = ref([{ label: '全部', value: '' }]);
const payStatusOptions = ref([{ label: '全部', value: '' }]);

// 状态值到文本的映射
const billStatusMap = ref<Record<string, string>>({});
const invoiceStatusMap = ref<Record<string, string>>({});
const payStatusMap = ref<Record<string, string>>({});

const filters = ref([
  { field: 'billStatus', label: '对账状态', options: billStatusOptions.value },
  { field: 'invoiceStatus', label: '开票状态', options: invoiceStatusOptions.value },
  { field: 'payStatus', label: '支付状态', options: payStatusOptions.value }
]);

const pagination = reactive({ page: 1, pageSize: 5, total: 0 });
const tableData = ref<any[]>([]);
const loading = ref(false);

// 加载对账单列表
const loadStatementList = async () => {
  try {
    loading.value = true;
    const res = await getStatementList({
      pageNum: pagination.page,
      pageSize: pagination.pageSize,
      statementOrderNo: searchForm.keyword,
      statementStatus: searchForm.billStatus,
      isInvoiceStatus: searchForm.invoiceStatus,
      isPaymentStatus: searchForm.payStatus
    });

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

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

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

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

// 加载字典数据

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

const handleView = (row: any) => {
  if (detailDialogRef.value) {
    detailDialogRef.value.open(row.id);
  }
};

const handleConfirm = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要确认对账单"${row.billNo}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await confirmStatement({ id: row.id });
    row.billStatus = '2';
    ElMessage.success('确认成功');
    loadStatementList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认对账单失败:', error);
      ElMessage.error('确认对账单失败');
    }
  }
};
</script>

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