<template>
  <div class="loan-products-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>贷款商品</h1>
      <a-button type="primary" @click="handleAddProduct">
        <plus-outlined />
        新增贷款
      </a-button>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <a-row :gutter="16" align="middle">
        <a-col :span="8">
          <a-input
            v-model:value="searchText"
            placeholder="请输入贷款产品"
            allow-clear
          />
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="handleSearch">
            <search-outlined />
            搜索
          </a-button>
        </a-col>
        <a-col :span="4">
          <a-button @click="handleReset">重置</a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 批量操作工具栏 -->
    <div class="batch-toolbar" v-if="selectedRowKeys.length > 0">
      <a-space>
        <span>已选择 {{ selectedRowKeys.length }} 项</span>
        <a-button @click="handleBatchDelete" danger>批量删除</a-button>
        <a-button @click="handleBatchEnable">批量启用</a-button>
        <a-button @click="handleBatchDisable">批量停用</a-button>
        <a-button @click="clearSelection">取消选择</a-button>
      </a-space>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="filteredProducts"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        :locale="{ emptyText: '暂无数据' }"
        :row-selection="rowSelection"
      >
         <template #bodyCell="{ column, record }">
           <template v-if="column.key === 'onSaleStatus'">
             <a-switch 
               v-model:checked="record.onSaleStatus" 
               @change="handleToggleStatus(record)"
             />
           </template>
           <template v-if="column.key === 'action'">
             <a-space>
               <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
               <a-button type="link" size="small" @click="handleView(record)">详情</a-button>
               <a-popconfirm
                 title="确定要删除这个贷款商品吗？"
                 ok-text="确定"
                 cancel-text="取消"
                 @confirm="handleDelete(record)"
               >
                 <a-button type="link" size="small" danger>删除</a-button>
               </a-popconfirm>
             </a-space>
           </template>
         </template>
      </a-table>
    </div>

    <!-- 新增对话框 -->
    <a-modal
      v-model:open="addModalVisible"
      title="新增贷款商品"
      width="800px"
      :confirm-loading="addLoading"
      @ok="handleAddSubmit"
      @cancel="handleAddCancel"
    >
      <a-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        layout="vertical"
        v-if="addModalVisible"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="贷款产品名称" name="productName">
              <a-input v-model:value="addForm.productName" placeholder="请输入贷款产品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="贷款额度" name="loanAmount">
              <a-input
                v-model:value="addForm.loanAmount"
                placeholder="请输入贷款额度，如：50000~5000000"
                style="width: 100%"
                addon-after="元"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="贷款周期" name="loanTerm">
              <a-input-number
                v-model:value="addForm.loanTerm"
                placeholder="请输入贷款周期"
                :min="1"
                style="width: 100%"
                addon-after="个月"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="贷款利率" name="interestRate">
              <a-input
                v-model:value="addForm.interestRate"
                placeholder="请输入贷款利率，如：3.90"
                style="width: 100%"
                addon-after="%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="服务区域" name="serviceArea">
              <a-input v-model:value="addForm.serviceArea" placeholder="请输入服务区域" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务电话" name="servicePhone">
              <a-input v-model:value="addForm.servicePhone" placeholder="请输入服务电话" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="最小贷款金额" name="minLoanAmount">
              <a-input-number
                v-model:value="addForm.minLoanAmount"
                placeholder="请输入最小贷款金额"
                :min="0"
                style="width: 100%"
                addon-after="元"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="最大贷款金额" name="maxLoanAmount">
              <a-input-number
                v-model:value="addForm.maxLoanAmount"
                placeholder="请输入最大贷款金额"
                :min="0"
                style="width: 100%"
                addon-after="元"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="风险等级" name="riskLevel">
              <a-select v-model:value="addForm.riskLevel" placeholder="请选择风险等级">
                <a-select-option value="LOW">低风险</a-select-option>
                <a-select-option value="MEDIUM">中风险</a-select-option>
                <a-select-option value="HIGH">高风险</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="在售状态" name="onSaleStatus">
              <a-switch v-model:checked="addForm.onSaleStatus" />
              <span style="margin-left: 8px">{{ addForm.onSaleStatus ? '在售' : '停售' }}</span>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="产品描述" name="productDescription">
          <a-textarea
            v-model:value="addForm.productDescription"
            placeholder="请输入产品描述"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="申请要求" name="applicationRequirements">
          <a-textarea
            v-model:value="addForm.applicationRequirements"
            placeholder="请输入申请要求"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="所需材料" name="requiredDocuments">
          <a-textarea
            v-model:value="addForm.requiredDocuments"
            placeholder="请输入所需材料"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="审批流程" name="approvalProcess">
          <a-textarea
            v-model:value="addForm.approvalProcess"
            placeholder="请输入审批流程"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑对话框 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑贷款商品"
      width="800px"
      :confirm-loading="editLoading"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        layout="vertical"
        v-if="editModalVisible"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="贷款产品名称" name="productName">
              <a-input v-model:value="editForm.productName" placeholder="请输入贷款产品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="贷款额度" name="loanAmount">
              <a-input
                v-model:value="editForm.loanAmount"
                placeholder="请输入贷款额度，如：50000~5000000"
                style="width: 100%"
                addon-after="元"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="贷款周期" name="loanTerm">
              <a-input-number
                v-model:value="editForm.loanTerm"
                placeholder="请输入贷款周期"
                :min="1"
                style="width: 100%"
                addon-after="个月"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="贷款利率" name="interestRate">
              <a-input
                v-model:value="editForm.interestRate"
                placeholder="请输入贷款利率，如：3.90"
                style="width: 100%"
                addon-after="%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="服务区域" name="serviceArea">
              <a-input v-model:value="editForm.serviceArea" placeholder="请输入服务区域" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务电话" name="servicePhone">
              <a-input v-model:value="editForm.servicePhone" placeholder="请输入服务电话" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="产品描述" name="description">
          <a-textarea
            v-model:value="editForm.description"
            placeholder="请输入产品描述"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="在售状态" name="onSaleStatus">
          <a-switch
            v-model:checked="editForm.onSaleStatus"
            checked-children="在售"
            un-checked-children="停售"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 详情对话框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="贷款商品详情"
      width="800px"
      :footer="null"
    >
      <a-descriptions :column="2" bordered v-if="currentProduct">
        <a-descriptions-item label="产品名称" :span="2">
          {{ currentProduct.productName }}
        </a-descriptions-item>
        <a-descriptions-item label="贷款额度">
          {{ currentProduct.loanAmount }} 万元
        </a-descriptions-item>
        <a-descriptions-item label="贷款周期">
          {{ currentProduct.loanTerm }} 个月
        </a-descriptions-item>
        <a-descriptions-item label="贷款利率">
          {{ currentProduct.interestRate }}%
        </a-descriptions-item>
        <a-descriptions-item label="服务区域">
          {{ currentProduct.serviceArea }}
        </a-descriptions-item>
        <a-descriptions-item label="服务电话">
          {{ currentProduct.servicePhone }}
        </a-descriptions-item>
        <a-descriptions-item label="服务客户总数">
          {{ currentProduct.totalCustomers }}
        </a-descriptions-item>
        <a-descriptions-item label="监管中客户">
          {{ currentProduct.supervisionCustomers }}
        </a-descriptions-item>
        <a-descriptions-item label="已结项客户">
          {{ currentProduct.completedCustomers }}
        </a-descriptions-item>
        <a-descriptions-item label="在售状态">
          <a-tag :color="currentProduct.onSaleStatus ? 'green' : 'red'">
            {{ currentProduct.onSaleStatus ? '在售' : '停售' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="添加时间" :span="2">
          {{ currentProduct.createdAt }}
        </a-descriptions-item>
        <a-descriptions-item label="产品描述" :span="2" v-if="currentProduct.description">
          {{ currentProduct.description }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { api } from '@/utils/api'

const loading = ref(false)
const searchText = ref('')
const products = ref([])

// 新增相关
const addModalVisible = ref(false)
const addLoading = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  productName: '',
  loanAmount: '',
  loanTerm: null,
  interestRate: '',
  serviceArea: '',
  servicePhone: '',
  minLoanAmount: null,
  maxLoanAmount: null,
  riskLevel: 'LOW',
  onSaleStatus: true,
  productDescription: '',
  applicationRequirements: '',
  requiredDocuments: '',
  approvalProcess: ''
})

// 编辑相关
const editModalVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: null,
  productName: '',
  loanAmount: null,
  loanTerm: null,
  interestRate: null,
  serviceArea: '',
  servicePhone: '',
  description: '',
  onSaleStatus: true
})

// 详情相关
const detailModalVisible = ref(false)
const currentProduct = ref(null)

// 批量操作相关
const selectedRowKeys = ref([])
const selectedRows = ref([])

// 表单验证规则
const editFormRules = {
  productName: [
    { required: true, message: '请输入贷款产品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '产品名称长度在2-50个字符', trigger: 'blur' }
  ],
  loanAmount: [
    { required: true, message: '请输入贷款额度', trigger: 'blur' },
    { 
      validator: (rule, value) => {
        if (!value) return Promise.reject('请输入贷款额度')
        // 支持数字或范围字符串（如：50000~5000000）
        if (typeof value === 'number') {
          if (value <= 0) return Promise.reject('贷款额度必须大于0')
        } else if (typeof value === 'string') {
          // 处理范围字符串
          if (value.includes('~')) {
            const [min, max] = value.split('~').map(v => parseFloat(v.trim()))
            if (isNaN(min) || isNaN(max) || min <= 0 || max <= 0) {
              return Promise.reject('贷款额度范围格式不正确')
            }
          } else {
            const numValue = parseFloat(value)
            if (isNaN(numValue) || numValue <= 0) {
              return Promise.reject('贷款额度必须大于0')
            }
          }
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  loanTerm: [
    { required: true, message: '请输入贷款周期', trigger: 'blur' },
    { type: 'number', min: 1, message: '贷款周期必须大于0', trigger: 'blur' }
  ],
  interestRate: [
    { required: true, message: '请输入贷款利率', trigger: 'blur' },
    { 
      validator: (rule, value) => {
        if (!value) return Promise.reject('请输入贷款利率')
        const numValue = parseFloat(value)
        if (isNaN(numValue)) return Promise.reject('请输入有效的数字')
        if (numValue < 0 || numValue > 100) {
          return Promise.reject('贷款利率必须在0-100之间')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  serviceArea: [
    { required: true, message: '请输入服务区域', trigger: 'blur' }
  ],
  servicePhone: [
    { required: true, message: '请输入服务电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 新增表单验证规则
const addFormRules = {
  productName: [
    { required: true, message: '请输入贷款产品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '产品名称长度在2-50个字符', trigger: 'blur' }
  ],
  loanAmount: [
    { required: true, message: '请输入贷款额度', trigger: 'blur' },
    { 
      validator: (rule, value) => {
        if (!value) return Promise.reject('请输入贷款额度')
        // 支持数字或范围字符串（如：50000~5000000）
        if (typeof value === 'number') {
          if (value <= 0) return Promise.reject('贷款额度必须大于0')
        } else if (typeof value === 'string') {
          // 处理范围字符串
          if (value.includes('~')) {
            const [min, max] = value.split('~').map(v => parseFloat(v.trim()))
            if (isNaN(min) || isNaN(max) || min <= 0 || max <= 0) {
              return Promise.reject('贷款额度范围格式不正确')
            }
          } else {
            const numValue = parseFloat(value)
            if (isNaN(numValue) || numValue <= 0) {
              return Promise.reject('贷款额度必须大于0')
            }
          }
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  loanTerm: [
    { required: true, message: '请输入贷款周期', trigger: 'blur' },
    { type: 'number', min: 1, message: '贷款周期必须大于0', trigger: 'blur' }
  ],
  interestRate: [
    { required: true, message: '请输入贷款利率', trigger: 'blur' },
    { 
      validator: (rule, value) => {
        if (!value) return Promise.reject('请输入贷款利率')
        const numValue = parseFloat(value)
        if (isNaN(numValue)) return Promise.reject('请输入有效的数字')
        if (numValue < 0 || numValue > 100) {
          return Promise.reject('贷款利率必须在0-100之间')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  serviceArea: [
    { required: true, message: '请输入服务区域', trigger: 'blur' }
  ],
  servicePhone: [
    { required: true, message: '请输入服务电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  minLoanAmount: [
    { required: true, message: '请输入最小贷款金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '最小贷款金额不能小于0', trigger: 'blur' }
  ],
  maxLoanAmount: [
    { required: true, message: '请输入最大贷款金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '最大贷款金额不能小于0', trigger: 'blur' }
  ],
  riskLevel: [
    { required: true, message: '请选择风险等级', trigger: 'change' }
  ]
}

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys, rows) => {
    selectedRowKeys.value = keys
    selectedRows.value = rows
  },
  onSelect: (record, selected, selectedRows) => {
    console.log('选择行:', record, selected, selectedRows)
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log('全选:', selected, selectedRows, changeRows)
  }
}

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条`,
})

const columns = [
  { 
    title: '贷款产品', 
    dataIndex: 'productName', 
    key: 'productName', 
    sorter: true,
    width: 200
  },
  { 
    title: '贷款额度', 
    dataIndex: 'loanAmount', 
    key: 'loanAmount',
    sorter: true,
    width: 150
  },
  { 
    title: '贷款周期', 
    dataIndex: 'loanTerm', 
    key: 'loanTerm',
    sorter: true,
    width: 100
  },
  { 
    title: '贷款利率', 
    dataIndex: 'interestRate', 
    key: 'interestRate',
    sorter: true,
    width: 100
  },
  { 
    title: '服务区域', 
    dataIndex: 'serviceArea', 
    key: 'serviceArea',
    width: 200
  },
  { 
    title: '服务电话', 
    dataIndex: 'servicePhone', 
    key: 'servicePhone',
    width: 120
  },
  { 
    title: '服务客户总数量', 
    dataIndex: 'totalCustomers', 
    key: 'totalCustomers',
    sorter: true,
    width: 120
  },
  { 
    title: '监管中客户', 
    dataIndex: 'supervisionCustomers', 
    key: 'supervisionCustomers',
    sorter: true,
    width: 120
  },
  { 
    title: '已结项客户', 
    dataIndex: 'completedCustomers', 
    key: 'completedCustomers',
    sorter: true,
    width: 120
  },
  { 
    title: '添加时间', 
    dataIndex: 'createdAt', 
    key: 'createdAt',
    sorter: true,
    width: 150
  },
  { 
    title: '在售状态', 
    dataIndex: 'onSaleStatus', 
    key: 'onSaleStatus',
    width: 100
  },
  { 
    title: '操作', 
    key: 'action', 
    fixed: 'right', 
    width: 120
  },
]

// 获取贷款商品列表
const fetchProducts = async () => {
  loading.value = true
  try {
    const response = await api.loanProducts.getList({
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: searchText.value,
    })
    
    console.log('API响应数据:', response)
    
    if (response.success) {
      console.log('产品数据:', response.data.products)
      console.log('分页数据:', response.data.pagination)
      
      products.value = response.data.products || []
      pagination.total = response.data.pagination?.total || 0
      pagination.current = response.data.pagination?.current || 1
      pagination.pageSize = response.data.pagination?.pageSize || 10
      
      console.log('设置后的products.value:', products.value)
    } else {
      message.error(response.message || '获取贷款商品失败')
    }
  } catch (error) {
    console.error('获取贷款商品失败:', error)
    message.error('获取贷款商品失败')
  } finally {
    loading.value = false
  }
}

const filteredProducts = computed(() => {
  // 后端已经处理了搜索，直接返回数据
  console.log('filteredProducts computed:', products.value)
  return products.value
})

const handleSearch = () => {
  pagination.current = 1
  fetchProducts()
}

const handleReset = () => {
  searchText.value = ''
  pagination.current = 1
  fetchProducts()
}

const handleAddProduct = () => {
  // 重置表单
  Object.assign(addForm, {
    productName: '',
    loanAmount: '',
    loanTerm: null,
    interestRate: '',
    serviceArea: '',
    servicePhone: '',
    minLoanAmount: null,
    maxLoanAmount: null,
    riskLevel: 'LOW',
    onSaleStatus: true,
    productDescription: '',
    applicationRequirements: '',
    requiredDocuments: '',
    approvalProcess: ''
  })
  addModalVisible.value = true
}

const handleEdit = async (record) => {
  try {
    const response = await api.loanProducts.getById(record.id)
    if (response.success) {
      // 填充编辑表单
      Object.assign(editForm, {
        id: record.id,
        productName: record.productName,
        loanAmount: record.loanAmount,
        loanTerm: record.loanTerm,
        interestRate: record.interestRate,
        serviceArea: record.serviceArea,
        servicePhone: record.servicePhone,
        description: record.description || '',
        onSaleStatus: record.onSaleStatus
      })
      editModalVisible.value = true
    } else {
      message.error(response.message || '获取产品详情失败')
    }
  } catch (error) {
    console.error('获取产品详情失败:', error)
    message.error('获取产品详情失败')
  }
}

const handleView = async (record) => {
  try {
    const response = await api.loanProducts.getById(record.id)
    if (response.success) {
      currentProduct.value = response.data
      detailModalVisible.value = true
    } else {
      message.error(response.message || '获取产品详情失败')
    }
  } catch (error) {
    console.error('获取产品详情失败:', error)
    message.error('获取产品详情失败')
  }
}

// 编辑提交
const handleEditSubmit = async () => {
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    const response = await api.loanProducts.update(editForm.id, {
      productName: editForm.productName,
      loanAmount: editForm.loanAmount,
      loanTerm: editForm.loanTerm,
      interestRate: editForm.interestRate,
      serviceArea: editForm.serviceArea,
      servicePhone: editForm.servicePhone,
      description: editForm.description,
      onSaleStatus: editForm.onSaleStatus
    })
    
    if (response.success) {
      message.success('贷款商品更新成功')
      editModalVisible.value = false
      fetchProducts() // 刷新列表
    } else {
      message.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新失败:', error)
    message.error('更新失败')
  } finally {
    editLoading.value = false
  }
}

// 编辑取消
const handleEditCancel = () => {
  editModalVisible.value = false
  editFormRef.value?.resetFields()
}

// 新增提交
const handleAddSubmit = async () => {
  try {
    await addFormRef.value.validate()
    addLoading.value = true
    
    const response = await api.loanProducts.create(addForm)
    
    if (response.success) {
      message.success('新增贷款商品成功')
      addModalVisible.value = false
      addFormRef.value?.resetFields()
      fetchProducts() // 刷新列表
    } else {
      message.error(response.message || '新增失败')
    }
  } catch (error) {
    console.error('新增失败:', error)
    message.error('新增失败')
  } finally {
    addLoading.value = false
  }
}

// 新增取消
const handleAddCancel = () => {
  addModalVisible.value = false
  addFormRef.value?.resetFields()
}

// 删除产品
const handleDelete = async (record) => {
  try {
    const response = await api.loanProducts.delete(record.id)
    if (response.success) {
      message.success(`${record.productName} 删除成功`)
      fetchProducts() // 刷新列表
    } else {
      message.error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要删除的项目')
    return
  }
  
  try {
    const response = await api.loanProducts.batchDelete({
      ids: selectedRowKeys.value
    })
    
    if (response.success) {
      message.success(`成功删除 ${selectedRowKeys.value.length} 个贷款商品`)
      clearSelection()
      fetchProducts() // 刷新列表
    } else {
      message.error(response.message || '批量删除失败')
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    message.error('批量删除失败')
  }
}

// 批量启用
const handleBatchEnable = async () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要启用的项目')
    return
  }
  
  try {
    const response = await api.loanProducts.batchUpdateStatus({
      ids: selectedRowKeys.value,
      onSaleStatus: true
    })
    
    if (response.success) {
      message.success(`成功启用 ${selectedRowKeys.value.length} 个贷款商品`)
      clearSelection()
      fetchProducts() // 刷新列表
    } else {
      message.error(response.message || '批量启用失败')
    }
  } catch (error) {
    console.error('批量启用失败:', error)
    message.error('批量启用失败')
  }
}

// 批量停用
const handleBatchDisable = async () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要停用的项目')
    return
  }
  
  try {
    const response = await api.loanProducts.batchUpdateStatus({
      ids: selectedRowKeys.value,
      onSaleStatus: false
    })
    
    if (response.success) {
      message.success(`成功停用 ${selectedRowKeys.value.length} 个贷款商品`)
      clearSelection()
      fetchProducts() // 刷新列表
    } else {
      message.error(response.message || '批量停用失败')
    }
  } catch (error) {
    console.error('批量停用失败:', error)
    message.error('批量停用失败')
  }
}

// 清除选择
const clearSelection = () => {
  selectedRowKeys.value = []
  selectedRows.value = []
}

const handleToggleStatus = async (record) => {
  try {
    const response = await api.loanProducts.update(record.id, {
      onSaleStatus: record.onSaleStatus
    })
    
    if (response.success) {
      const status = record.onSaleStatus ? '启用' : '停用'
      message.success(`${record.productName} 已${status}`)
    } else {
      message.error(response.message || '更新状态失败')
      // 恢复原状态
      record.onSaleStatus = !record.onSaleStatus
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    message.error('更新状态失败')
    // 恢复原状态
    record.onSaleStatus = !record.onSaleStatus
  }
}

const handleTableChange = (pag, filters, sorter) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchProducts()
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.loan-products-page {
  padding: 0;
  background: #f0f2f5;
  min-height: calc(100vh - 134px);
  margin: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.search-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

/* 表格样式优化 */
:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  color: #262626;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-table-tbody > tr:nth-child(even) > td) {
  background: #fafafa;
}

:deep(.ant-table-tbody > tr:nth-child(odd) > td) {
  background: #fff;
}

/* 开关样式 */
:deep(.ant-switch-checked) {
  background-color: #1890ff;
}

/* 链接按钮样式 */
:deep(.ant-btn-link) {
  color: #1890ff;
  padding: 4px 8px;
}

:deep(.ant-btn-link:hover) {
  color: #40a9ff;
}

/* 批量操作工具栏样式 */
.batch-toolbar {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.batch-toolbar .ant-space {
  flex: 1;
}

.batch-toolbar span {
  color: #1890ff;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .search-section .ant-col {
    margin-bottom: 16px;
  }
  
  .search-section .ant-col:last-child {
    margin-bottom: 0;
  }
  
  .batch-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .batch-toolbar .ant-space {
    justify-content: center;
  }
}
</style>