<template>
  <div class="finance-page">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <a-page-header title="金融服务监管" sub-title="贷款和保险业务管理">
        <template #extra>
          <a-button type="primary" @click="showAddModal('loan')">
            <PlusOutlined /> 新增贷款申请
          </a-button>
          <a-button @click="showAddModal('insurance')">
            <SafetyOutlined /> 新增保险申请
          </a-button>
        </template>
      </a-page-header>
    </div>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-cards">
      <a-col :span="6">
        <a-card>
          <a-statistic title="贷款申请总数" :value="stats.totalLoans" />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic title="保险申请总数" :value="stats.totalInsurance" />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic 
            title="贷款总金额" 
            :value="stats.totalLoanAmount" 
            suffix="万元" 
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic 
            title="保险总金额" 
            :value="stats.totalInsuranceAmount" 
            suffix="万元" 
          />
        </a-card>
      </a-col>
    </a-row>

    <!-- 标签页 -->
    <a-tabs v-model:activeKey="activeTab" class="finance-tabs">
      <a-tab-pane key="loans" tab="贷款管理">
        <!-- 贷款搜索表单 -->
        <a-card class="search-card">
          <a-form layout="inline" :model="loanSearchForm">
            <a-form-item label="申请人">
              <a-input v-model:value="loanSearchForm.applicant" placeholder="请输入申请人姓名" />
            </a-form-item>
            <a-form-item label="贷款类型">
              <a-select v-model:value="loanSearchForm.loanType" placeholder="请选择贷款类型" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="cattle">牛只质押贷款</a-select-option>
                <a-select-option value="farm">牧场贷款</a-select-option>
                <a-select-option value="equipment">设备贷款</a-select-option>
                <a-select-option value="operating">经营贷款</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model:value="loanSearchForm.status" placeholder="请选择状态" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="submitted">已提交</a-select-option>
                <a-select-option value="under_review">审核中</a-select-option>
                <a-select-option value="approved">已批准</a-select-option>
                <a-select-option value="rejected">已拒绝</a-select-option>
                <a-select-option value="disbursed">已放款</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchLoans">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetLoanSearch" style="margin-left: 8px">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 贷款列表 -->
        <a-card>
          <a-table 
            :columns="loanColumns" 
            :data-source="loans" 
            :loading="loanLoading"
            :pagination="loanPagination"
            @change="handleLoanTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getLoanStatusColor(record.status)">
                  {{ getLoanStatusText(record.status) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewLoanDetail(record)">
                    详情
                  </a-button>
                  <a-button 
                    v-if="record.status === 'under_review'" 
                    size="small" 
                    type="primary"
                    @click="reviewLoan(record)"
                  >
                    审核
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="insurance" tab="保险管理">
        <!-- 保险搜索表单 -->
        <a-card class="search-card">
          <a-form layout="inline" :model="insuranceSearchForm">
            <a-form-item label="申请人">
              <a-input v-model:value="insuranceSearchForm.applicant" placeholder="请输入申请人姓名" />
            </a-form-item>
            <a-form-item label="保险类型">
              <a-select v-model:value="insuranceSearchForm.insuranceType" placeholder="请选择保险类型" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="cattle_death">牛只死亡险</a-select-option>
                <a-select-option value="cattle_health">牛只健康险</a-select-option>
                <a-select-option value="cattle_theft">牛只盗窃险</a-select-option>
                <a-select-option value="property">财产险</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model:value="insuranceSearchForm.status" placeholder="请选择状态" style="width: 150px">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="applied">已申请</a-select-option>
                <a-select-option value="underwriting">核保中</a-select-option>
                <a-select-option value="issued">已出单</a-select-option>
                <a-select-option value="active">生效中</a-select-option>
                <a-select-option value="expired">已过期</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchInsurance">
                <SearchOutlined /> 搜索
              </a-button>
              <a-button @click="resetInsuranceSearch" style="margin-left: 8px">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 保险列表 -->
        <a-card>
          <a-table 
            :columns="insuranceColumns" 
            :data-source="insuranceList" 
            :loading="insuranceLoading"
            :pagination="insurancePagination"
            @change="handleInsuranceTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getInsuranceStatusColor(record.status)">
                  {{ getInsuranceStatusText(record.status) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewInsuranceDetail(record)">
                    详情
                  </a-button>
                  <a-button 
                    v-if="record.status === 'underwriting'" 
                    size="small" 
                    type="primary"
                    @click="reviewInsurance(record)"
                  >
                    核保
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { financeAPI } from '@/services/api.js';
import { 
  PlusOutlined, 
  SearchOutlined, 
  SafetyOutlined 
} from '@ant-design/icons-vue';

export default {
  name: 'Finance',
  components: {
    PlusOutlined,
    SearchOutlined,
    SafetyOutlined
  },
  setup() {
    const activeTab = ref('loans');
    const loanLoading = ref(false);
    const insuranceLoading = ref(false);
    
    // 统计数据
    const stats = reactive({
      totalLoans: 156,
      totalInsurance: 89,
      totalLoanAmount: 2850,
      totalInsuranceAmount: 1260
    });

    // 贷款数据
    const loans = ref([]);
    const loanSearchForm = reactive({
      applicant: '',
      loanType: '',
      status: ''
    });
    const loanPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    });

    // 保险数据
    const insuranceList = ref([]);
    const insuranceSearchForm = reactive({
      applicant: '',
      insuranceType: '',
      status: ''
    });
    const insurancePagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true
    });

    // 贷款表格列
    const loanColumns = [
      { title: '申请编号', dataIndex: 'id', key: 'id', width: 120 },
      { title: '申请人', dataIndex: 'applicant_name', key: 'applicant_name' },
      { title: '贷款类型', dataIndex: 'loan_type', key: 'loan_type' },
      { title: '申请金额(万元)', dataIndex: 'loan_amount', key: 'loan_amount' },
      { title: '状态', dataIndex: 'status', key: 'status' },
      { title: '申请时间', dataIndex: 'created_at', key: 'created_at' },
      { title: '操作', key: 'action', width: 150 }
    ];

    // 保险表格列
    const insuranceColumns = [
      { title: '保单号', dataIndex: 'policy_number', key: 'policy_number', width: 120 },
      { title: '申请人', dataIndex: 'applicant_name', key: 'applicant_name' },
      { title: '保险类型', dataIndex: 'insurance_type', key: 'insurance_type' },
      { title: '保险金额(万元)', dataIndex: 'insured_amount', key: 'insured_amount' },
      { title: '保费(元)', dataIndex: 'premium', key: 'premium' },
      { title: '状态', dataIndex: 'status', key: 'status' },
      { title: '申请时间', dataIndex: 'created_at', key: 'created_at' },
      { title: '操作', key: 'action', width: 150 }
    ];

    // 加载贷款数据
    const loadLoans = async () => {
      loanLoading.value = true;
      try {
        const params = {
          page: loanPagination.current,
          limit: loanPagination.pageSize,
          ...loanSearchForm
        };
        const response = await financeAPI.getLoans(params);
        if (response.success) {
          loans.value = response.data.loans || [];
          loanPagination.total = response.data.pagination?.total || 0;
        }
      } catch (error) {
        console.error('获取贷款列表失败:', error);
        message.error('获取贷款列表失败');
      } finally {
        loanLoading.value = false;
      }
    };

    // 加载保险数据
    const loadInsurance = async () => {
      insuranceLoading.value = true;
      try {
        const params = {
          page: insurancePagination.current,
          limit: insurancePagination.pageSize,
          ...insuranceSearchForm
        };
        const response = await financeAPI.getInsurance(params);
        if (response.success) {
          insuranceList.value = response.data.insurance || [];
          insurancePagination.total = response.data.pagination?.total || 0;
        }
      } catch (error) {
        console.error('获取保险列表失败:', error);
        message.error('获取保险列表失败');
      } finally {
        insuranceLoading.value = false;
      }
    };

    // 贷款状态颜色
    const getLoanStatusColor = (status) => {
      const colors = {
        'submitted': 'blue',
        'under_review': 'orange',
        'approved': 'green',
        'rejected': 'red',
        'disbursed': 'purple',
        'completed': 'green',
        'overdue': 'red'
      };
      return colors[status] || 'default';
    };

    // 贷款状态文本
    const getLoanStatusText = (status) => {
      const texts = {
        'submitted': '已提交',
        'under_review': '审核中',
        'approved': '已批准',
        'rejected': '已拒绝',
        'disbursed': '已放款',
        'completed': '已完成',
        'overdue': '逾期'
      };
      return texts[status] || status;
    };

    // 保险状态颜色
    const getInsuranceStatusColor = (status) => {
      const colors = {
        'applied': 'blue',
        'underwriting': 'orange',
        'issued': 'green',
        'active': 'green',
        'expired': 'red',
        'cancelled': 'red'
      };
      return colors[status] || 'default';
    };

    // 保险状态文本
    const getInsuranceStatusText = (status) => {
      const texts = {
        'applied': '已申请',
        'underwriting': '核保中',
        'issued': '已出单',
        'active': '生效中',
        'expired': '已过期',
        'cancelled': '已取消'
      };
      return texts[status] || status;
    };

    // 搜索贷款
    const searchLoans = () => {
      loanPagination.current = 1;
      loadLoans();
    };

    // 重置贷款搜索
    const resetLoanSearch = () => {
      Object.assign(loanSearchForm, {
        applicant: '',
        loanType: '',
        status: ''
      });
      searchLoans();
    };

    // 搜索保险
    const searchInsurance = () => {
      insurancePagination.current = 1;
      loadInsurance();
    };

    // 重置保险搜索
    const resetInsuranceSearch = () => {
      Object.assign(insuranceSearchForm, {
        applicant: '',
        insuranceType: '',
        status: ''
      });
      searchInsurance();
    };

    // 表格变化处理
    const handleLoanTableChange = (pagination) => {
      loanPagination.current = pagination.current;
      loanPagination.pageSize = pagination.pageSize;
      loadLoans();
    };

    const handleInsuranceTableChange = (pagination) => {
      insurancePagination.current = pagination.current;
      insurancePagination.pageSize = pagination.pageSize;
      loadInsurance();
    };

    // 显示添加模态框
    const showAddModal = (type) => {
      message.info(`添加${type === 'loan' ? '贷款' : '保险'}申请功能开发中`);
    };

    // 查看详情
    const viewLoanDetail = (record) => {
      message.info(`查看贷款详情: ${record.id}`);
    };

    const viewInsuranceDetail = (record) => {
      message.info(`查看保险详情: ${record.policy_number}`);
    };

    // 审核
    const reviewLoan = (record) => {
      message.info(`审核贷款: ${record.id}`);
    };

    const reviewInsurance = (record) => {
      message.info(`核保保险: ${record.policy_number}`);
    };

    onMounted(() => {
      loadLoans();
      loadInsurance();
    });

    return {
      activeTab,
      stats,
      loans,
      loanLoading,
      loanSearchForm,
      loanPagination,
      loanColumns,
      insuranceList,
      insuranceLoading,
      insuranceSearchForm,
      insurancePagination,
      insuranceColumns,
      loadLoans,
      loadInsurance,
      getLoanStatusColor,
      getLoanStatusText,
      getInsuranceStatusColor,
      getInsuranceStatusText,
      searchLoans,
      resetLoanSearch,
      searchInsurance,
      resetInsuranceSearch,
      handleLoanTableChange,
      handleInsuranceTableChange,
      showAddModal,
      viewLoanDetail,
      viewInsuranceDetail,
      reviewLoan,
      reviewInsurance
    };
  }
};
</script>

<style scoped>
.finance-page {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  margin-bottom: 16px;
  border-radius: 8px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stats-cards .ant-card {
  text-align: center;
}

.finance-tabs {
  background: white;
  padding: 24px;
  border-radius: 8px;
}

.search-card {
  margin-bottom: 16px;
}

.search-card .ant-form {
  margin-bottom: 0;
}
</style>