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

    <SearchBar :form="searchForm" :filters="filters" placeholder="对账编号" />

    <el-table v-loading="loading" :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="billNo" label="对账编号" min-width="130" align="center" />
      <el-table-column prop="billDate" 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="billStatus" label="对账状态" min-width="90" align="center">
        <template #default="{ row }">
          {{ getDictLabel(statement_status, row.billStatus) }}
        </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="bottom-bar">
      <div class="summary">
        <span
          >已选择 <em>{{ selectedCount }}</em> 个对账单</span
        >
        <span class="total"
          >合计金额 <em>¥{{ totalAmount.toFixed(2) }}</em></span
        >
        <el-button type="primary" :disabled="selectedCount === 0" @click="handleApplyInvoice">申请开票</el-button>
      </div>
    </div>

    <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, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PageTitle, SearchBar, TablePagination } from '@/components';
import { getStatementList, applyForInvoice } from '@/api/pc/enterprise/statement';
import type { StatementOrder } from '@/api/pc/enterprise/statementTypes';
import { get } from 'http';
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: [],
  invoiceStatus: ''
});
const form = reactive({
  statementOrderIds: []
});

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

const filters = ref([{ field: 'invoiceStatus', label: '开票状态', options: invoiceStatusOptions.value }]);

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

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

    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;
  }
};

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],
  () => {
    loadStatementList();
  }
);

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

// // 加载字典数据
// const loadDictData = async () => {
//   try {
//     const res = await getDictByType('invoice_issuance_status');
//     if (res.data) {
//       invoiceStatusOptions.value = [
//         { label: '全部', value: '' },
//         ...res.data.map((item) => ({
//           label: item.dictLabel,
//           value: item.dictValue
//         }))
//       ];
//       filters.value[0].options = invoiceStatusOptions.value;
//     }
//   } catch (error) {
//     console.error('加载字典数据失败:', error);
//   }
// };

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

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 计算选中数量
const selectedCount = computed(() => selectedRows.value.length);

// 计算总金额
const totalAmount = computed(() => {
  return selectedRows.value.reduce((sum, item) => sum + item.amount, 0);
});

const handleView = (row: any) => {
  ElMessage.info(`查看对账单：${row.billNo}`);
};

const handleApplyInvoice = async () => {
  try {
    form.statementOrderIds = selectedRows.value.map((row) => row.id);
    if (!form.statementOrderIds) {
      ElMessage.warning('请选择要申请的对账单');
      return;
    }
    const billNos = selectedRows.value.map((row) => row.billNo).join('、');
    await ElMessageBox.confirm(`确定要为以下对账单申请开票吗？\n${billNos}`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // TODO: 调用申请开票接口
    await applyForInvoice(form);
    ElMessage.success('申请开票成功');
    loadStatementList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('申请开票失败:', error);
      ElMessage.error('申请开票失败');
    }
  }
};
</script>

<style scoped>
.bottom-bar {
  margin-top: 16px;
  padding: 16px;
  background: #fafafa;
  border: 1px solid #eee;
  border-radius: 4px;
  display: flex;
  justify-content: flex-end;
}

.summary {
  display: flex;
  align-items: center;
  gap: 20px;
}

.summary span {
  font-size: 14px;
  color: #666;
}

.summary em {
  color: #e60012;
  font-style: normal;
  font-weight: bold;
}

.summary .total em {
  font-size: 16px;
}

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