<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.billStatus" placeholder="请选择对账状态" clearable @change="handleSearch">
            <el-option v-for="item in billStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </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 label="支付状态">
          <el-select v-model="searchForm.payStatus" placeholder="请选择支付状态" clearable @change="handleSearch">
            <el-option v-for="item in payStatusOptions" :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%"
      @selection-change="handleSelectionChange"
      @select="handleSelect"
      @select-all="handleSelectAll"
      ref="tableRef"
    >
      <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">
        <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)" v-if="row.billStatus == '1'">确认</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, onMounted, watch, computed, getCurrentInstance, toRefs } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PageTitle, TablePagination } from '@/components';
import { getStatementList, getStatementInfo, confirmStatement, applyForInvoice } from '@/api/pc/enterprise/statement';
import type { StatementOrder } from '@/api/pc/enterprise/statementTypes';

const router = useRouter();

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 = computed(() => [{ label: '全部', value: '' }, ...(statement_status.value || [])]);
const invoiceStatusOptions = computed(() => [{ label: '全部', value: '' }, ...(invoice_issuance_status.value || [])]);
const payStatusOptions = computed(() => [{ label: '全部', value: '' }, ...(payment_status.value || [])]);

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

const form = reactive({
  statementOrderIds: []
});
// 加载对账单列表
const loadStatementList = async () => {
  try {
    loading.value = true;
    const queryParams = {
      pageNum: pagination.page,
      pageSize: pagination.pageSize,
      statementOrderNo: searchForm.keyword,
      statementStatus: searchForm.billStatus,
      isInvoiceStatus: searchForm.invoiceStatus,
      isPaymentStatus: searchForm.payStatus,
      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 getStatementList(queryParams);

    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 handleSelect = (selection: any[], row: any) => {
  // 判断是选中还是取消选中
  const isSelected = selection.some((item) => item.id === row.id);
  if (isSelected && row.billStatus !== '2') {
    ElMessage.warning('该账单未对账，不可申请开票');
    // 取消选中状态
    tableRef.value?.toggleRowSelection(row, false);
    return;
  }
};

// 处理全选
const handleSelectAll = (selection: any[]) => {
  // 如果有选中的行，过滤掉 billStatus !== '2' 的行
  const invalidRows = selection.filter((row) => row.billStatus !== '2');
  if (invalidRows.length > 0) {
    ElMessage.warning('部分账单未对账，已自动过滤');
    // 取消这些行的选中状态
    invalidRows.forEach((row) => {
      tableRef.value?.toggleRowSelection(row, false);
    });
  }
};

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

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

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

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

// 监听搜索条件变化
watch(
  () => [searchForm.keyword, searchForm.dateRange, 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) => {
  router.push(`/reconciliation/billManage/detail?id=${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('确认对账单失败');
    }
  }
};

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('申请开票失败');
    }
  }
};

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

// 重置
const handleReset = () => {
  searchForm.keyword = '';
  searchForm.dateRange = [];
  searchForm.billStatus = '';
  searchForm.invoiceStatus = '';
  searchForm.payStatus = '';
  pagination.page = 1;
  loadStatementList();
};
</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;
}
.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;
}
</style>
