<template>
  <div class="financial-income-page">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="保单号">
              <el-input v-model="searchForm.policyNo" placeholder="请输入保单号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="对账公司">
              <el-select v-model="searchForm.reconciliationCompany" placeholder="请选择对账公司" clearable>
                <el-option
                  v-for="item in companyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入账日期">
              <el-date-picker
                v-model="searchForm.incomeDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div class="search-buttons">
              <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="RefreshLeft" @click="resetForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <div class="action-area">
      <!-- <el-button type="primary" :icon="Plus" @click="handleAdd">新增入账</el-button> -->
      
      <!-- 导入区域 -->
      <el-card class="import-card">
        <div class="import-content">
          <div class="import-actions">
            <FileUpload :fileType="['xlsx', 'xls']" 
            :action="'/csf/api/commission/upload/excel'"
            @uploadEnd = 'getUploadFileFunc'
            :responseType="'onlyStatus'"
            
            />
           
            <el-button text @click="downloadTemplate" size="small" class="download-template-btn">
              下载模板
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 列表区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="policyNo" label="保单号" min-width="120" align="center" />
        <el-table-column prop="reconciliationCompany" label="对账公司" min-width="120" align="center" />
        <el-table-column prop="commissionPeriod" label="当前入账期数" min-width="100" align="center" />
        <el-table-column prop="totalPeriod" label="预计总期数" min-width="100" align="center" />
        <el-table-column prop="commissionName" label="入账项目" min-width="120" align="center" />
        <el-table-column prop="amount" label="入账金额" min-width="100" align="center" />
        <el-table-column prop="currency" label="入账币种" min-width="80" align="center" />
        <el-table-column prop="commissionDate" label="入账日期" min-width="120" align="center" />
        <el-table-column prop="status" label="比对状态" min-width="100" align="center">
          <template #default="scope">
            <span>{{convertStatusToDict(scope.row.status) }}</span>
          </template>
        </el-table-column>>
        <el-table-column prop="remark" label="备注" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button text size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button text size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 底部确认按钮 -->
    <div class="footer-actions" v-if="selectedRows.length > 0">
      <el-button 
        type="primary" 
        size="large" 
        @click="handleGenerateBilling" 
        :disabled="selectedRows.length === 0"
      >
        确认生成可出账记录
      </el-button>
    </div>
  <!-- 编辑对话框 -->
<el-dialog
      v-model="editDialogVisible"
      :title="editDialogTitle"
      width="600px"
      :before-close="handleCloseDialog"
    >
      <el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="保单号" prop="policyNo">
              <el-input v-model="editForm.policyNo" placeholder="请输入保单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="对账公司" prop="reconciliationCompany">
              <el-select v-model="editForm.reconciliationCompany" placeholder="请选择对账公司">
                <el-option
                  v-for="item in companyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前期数" prop="currentPeriod">
              <el-input-number v-model="editForm.currentPeriod" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总期数" prop="totalPeriod">
              <el-input-number v-model="editForm.totalPeriod" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入账项目" prop="commissionName">
              <el-input v-model="editForm.commissionName" placeholder="请输入入账项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入账金额" prop="amount">
              <el-input v-model="editForm.amount" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="editForm.currency" placeholder="请选择币种">
                <el-option label="人民币" value="CNY" />
                <el-option label="港币" value="HKD" />
                <el-option label="美元" value="USD" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="入账日期" prop="commissionDate">
              <el-date-picker
                v-model="editForm.commissionDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="editForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="editLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
      </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, RefreshLeft, UploadFilled, Plus, Document } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'
// 导入有关来佣的接口
import { getPolicyCommissionList, downloadPolicyFortune ,generateCommissionRecord,updatePolicyCommission} from "@/api/financial/commission"

import FileUpload from "@/components/FileUpload/index"
import { useRouter } from 'vue-router'
const router = useRouter()

import { listType } from '@/api/system/dict/type'
// 通过dictType=csf_commission_status获取比对状态字典值,获取对象中的dictItemList
const dictLists = ref([]);
const getLists = () => {
    return new Promise((resolve, reject) => {
        listType({typeList: ['csf_commission_status']}).then(res => {
            if (res.code === 200 && res.data) {
                const dictData = res.data.find(item => item.dictType === 'csf_commission_status');
                dictLists.value = dictData?.dictItemList || [];
                console.log('获取到的字典数据:', dictLists.value);
                resolve(dictLists.value);
            } else {
                dictLists.value = [];
                resolve([]);
            }
        }).catch(error => {
            console.error('获取状态列表失败:', error);
            dictLists.value = [];
            reject(error);
        });
    });
}
// 返回数据中状态需要转换为字典值
const convertStatusToDict = (status) => {
    const dictItem = dictLists.value.find(item => item.itemValue == status);
    return dictItem?.itemLabel ?? status;
}

// 增加通过表格排序，排序字段sortField，升降序sortOrder
const handleSortChange = (column) => {
    pagination.sortField = column.prop
    pagination.sortOrder = column.order === 'ascending' ? 'ascend' : 'descend'
    fetchTableData()
}

// 搜索表单数据
const searchForm = reactive({
  policyNo: '',
  reconciliationCompany: '',
  incomeDateRange: []
})

// 对账公司选项

const companyOptions = ref([])
// 获取对账公司列表
import { getReconciliationCompanyList } from '@/api/financial/commission'
const fetchReconciliationCompanyList = async () => {
  try {
    const response = await getReconciliationCompanyList({
      pageNo: 1,
      pageSize: 1000
    })
    if (response.code === 200) {
      companyOptions.value = response.data.records.map(item => ({
        label: item.companyName,
        value: item.reconciliationCompanyBizId
      }))
    } else {
      ElMessage.error(response.msg)
    }
  } catch (error) {
    ElMessage.error('获取对账公司列表失败')
  }
}

// 表格数据
const tableData = ref([])
const tableLoading = ref(false)
const selectedRows = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// Excel导入相关
const selectedFile = ref(null)
const importLoading = ref(false)

onMounted(() => {
    // 获取字典值后，再调用接口获取来佣列表
    initialData();
})

const initialData = async () => {
    await getLists();
    fetchTableData();
    fetchReconciliationCompanyList()
}


const getUploadFileFunc = (data) => {
  console.log(data)
  if(data===200){
    ElMessage.success('上传成功');
    fetchTableData()
  }else{
    ElMessage.error('上传失败')
  }
}
// 获取列表数据
// 调用接口获取来佣列表
const fetchTableData = async () => {
  tableLoading.value = true
  try {
    // 调用接口获取来佣列表
    const res = await getPolicyCommissionList({
      pageNo: pagination.currentPage,
      pageSize: pagination.pageSize,
      policyNo: searchForm.policyNo,
      reconciliationCompany: searchForm.reconciliationCompany,
      startTime: searchForm.incomeDateRange[0] ? `${searchForm.incomeDateRange[0]} 00:00:00` : '',
      endTime: searchForm.incomeDateRange[1] ? `${searchForm.incomeDateRange[1]} 23:59:59` : ''
    })
    tableData.value = res.data.records
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTableData()
  ElMessage.success('查询成功')
}

// 重置表单
const resetForm = () => {
  searchForm.policyNo = ''
  searchForm.reconciliationCompany = ''
  searchForm.incomeDateRange = []
  ElMessage.success('已重置筛选条件')
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTableData()
}

// 处理分页页码变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTableData()
}

// 处理表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}


// 下载模板
const downloadTemplate = () => {
  const templateData = [
    {
      policyNo: '示例保单号',
      reconciliationCompany: '对账公司代码',
      currentPeriod: '1',
      totalPeriods: '12',
      incomeItem: '入账项目',
      incomeAmount: '1000',
      currency: 'CNY',
      incomeDate: '2024-01-01',
      remark: '备注信息'
    }
  ]
  
  const worksheet = XLSX.utils.json_to_sheet(templateData)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '对账单模板')
  
  XLSX.writeFile(workbook, '对账单导入模板.xlsx')
  ElMessage.success('模板下载成功')
}


// 新增入账
const handleAdd = () => {
  ElMessage.info('打开新增入账对话框')
}

import { deletePolicyCommission } from '@/api/financial/commission'
// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除保单 ${row.policyNo} 的入账记录吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 调用删除接口
    deletePolicyCommission({
      commissionBizId: row.commissionBizId
    }).then((res) => {
      if(res.code === 200){
        ElMessage.success('删除成功')
        fetchTableData()
      }else{
         ElMessage.error('删除失败')
      }
    }).catch(() => {
      ElMessage.error('删除失败')
    })
  })
}

// 生成可出账记录
// 调用generateCommissionRecord接口
const handleGenerateBilling = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要生成可出账记录的记录')
    return
  }
  try {
    console.log(selectedRows.value)
    await generateCommissionRecord({
      commissionBizIdList: selectedRows.value.map(row => row.commissionBizId)
    })
    ElMessage.success('生成成功')
    // 这里可以添加路由跳转到 financialBilling 组件
    // router.push('/financialCenter/financial/billing')
  } catch (error) {
    console.error('生成失败:', error)
    ElMessage.error('生成失败')
  }
}   

// 编辑对话框相关
const editDialogVisible = ref(false)
const editDialogTitle = ref('编辑入账记录')
const editLoading = ref(false)
const editFormRef = ref()

// 编辑表单数据
const editForm = reactive({
  commissionBizId: '',
  policyNo: '',
  reconciliationCompany: '',
  currentPeriod: 1,
  totalPeriod: 1,
  commissionName: '',
  amount: 0,
  currency: 'CNY',
  commissionDate: '',
  remark: ''
})

// 表单验证规则
const editFormRules = {
  policyNo: [{ required: true, message: '请输入保单号', trigger: 'blur' }],
  reconciliationCompany: [{ required: true, message: '请选择对账公司', trigger: 'change' }],
  commissionName: [{ required: true, message: '请输入入账项目', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  commissionDate: [{ required: true, message: '请选择入账日期', trigger: 'change' }]
}

// 编辑入账记录
const handleEdit = (row) => {
  editDialogTitle.value = `编辑入账记录 - ${row.policyNo}`
  
  // 填充表单数据
  Object.assign(editForm, {
    commissionBizId: row.commissionBizId,
    policyNo: row.policyNo,
    reconciliationCompany: row.reconciliationCompany,
    currentPeriod: row.currentPeriod || 1,
    totalPeriod: row.totalPeriod || 1,
    commissionName: row.commissionName,
    amount: row.amount,
    currency: row.currency || 'CNY',
    commissionDate: row.commissionDate,
    remark: row.remark || ''
  })
  
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()
    
    editLoading.value = true
    
    // 调用更新接口
    await updatePolicyCommission(editForm)
    
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    fetchTableData() // 刷新表格数据
  } catch (error) {
    if (error && error.errorFields) {
      ElMessage.warning('请完善表单信息')
    } else {
      console.error('更新失败:', error)
      ElMessage.error('更新失败')
    }
  } finally {
    editLoading.value = false
  }
}

// 关闭对话框处理
const handleCloseDialog = (done) => {
  if (editLoading.value) {
    ElMessage.info('正在保存，请稍候...')
    return
  }
  
  ElMessageBox.confirm('确定要关闭吗？未保存的修改将会丢失', '提示', {
    type: 'warning'
  }).then(() => {
    done()
  }).catch(() => {})
}

</script>

<style scoped>
.financial-income-page {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.search-card {
  margin-bottom: 20px;
  padding: 15px 20px;
}

.search-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
  height: 32px;
}

.action-area {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.import-card {
  padding: 20px;
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
}

.import-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.import-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.upload-excel {
  display: inline-block;
}

/* 文件信息显示样式 */
.file-info {
  margin-top: 15px;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-info-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-info-content .el-icon {
  color: #409eff;
  font-size: 16px;
}

.file-name {
  font-weight: 500;
  color: #303133;
}

.file-size {
  color: #909399;
  font-size: 12px;
}

.confirm-import-btn {
  margin-left: 12px;
}

/* 下载模板按钮样式 */
.download-template-btn {
  color: #409eff;
  font-size: 12px;
  padding: 8px 12px;
}

.download-template-btn:hover {
  background-color: #ecf5ff;
}

.table-card {
  padding: 15px 20px;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

.footer-actions {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .import-actions {
    flex-wrap: wrap;
  }
  
  .download-template-btn {
    margin-top: 10px;
  }
  
  .file-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .confirm-import-btn {
    margin-left: 0;
    align-self: flex-end;
  }
}

@media (max-width: 992px) {
  .search-card .el-col {
    margin-bottom: 15px;
  }
  
  .search-buttons {
    justify-content: flex-start;
  }
}

@media (max-width: 768px) {
  .search-card .el-col {
    width: 100%;
  }
  
  .import-actions {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .download-template-btn {
    margin-top: 10px;
  }
}
</style>