<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.label"
                />
              </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="incomeDialogVisible"
      :title="incomeDialogTitle"
      width="600px"
      :before-close="handleCloseDialog"
    >
      <el-form :model="incomeForm" label-width="100px" :rules="incomeFormRules" ref="incomeFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="保单号" prop="policyNo">
              <el-input v-model="incomeForm.policyNo" placeholder="请输入保单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="对账公司" prop="reconciliationCompany">
              <el-select v-model="incomeForm.reconciliationCompany" placeholder="请选择对账公司">
                <el-option
                  v-for="item in companyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前期数" prop="commissionPeriod">
              <el-input-number v-model="incomeForm.commissionPeriod" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总期数" prop="totalPeriod">
              <el-input-number v-model="incomeForm.totalPeriod" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入账项目" prop="commissionName">
              <el-input v-model="incomeForm.commissionName" placeholder="请输入入账项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入账金额" prop="amount">
              <el-input v-model="incomeForm.amount" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="incomeForm.currency" placeholder="请选择币种">
                <el-option
                  v-for="item in currencyTypeOptions"
                  :key="item.itemValue"
                  :label="item.itemLabel"
                  :value="item.itemValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="入账日期" prop="commissionDate">
              <el-date-picker
                v-model="incomeForm.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="incomeForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="incomeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitIncomeForm" :loading="incomeLoading">
            {{ isEditMode ? '更新' : '新增' }}
          </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 currencyTypeOptions = ref([])
const getLists = () => {
    return new Promise((resolve, reject) => {
        listType({typeList: ['csf_commission_status','bx_currency_type']}).then(res => {
            if (res.code === 200 && res.data) {
                const dictData = res.data.find(item => item.dictType === 'csf_commission_status');
                dictLists.value = dictData?.dictItemList || [];
                // 处理币种字典值
                const currencyData = res.data.find(item => item.dictType === 'bx_currency_type');
                currencyTypeOptions.value = currencyData?.dictItemList || [];
                console.log('获取到的币种字典数据:', currencyTypeOptions.value);
                resolve(dictLists.value,currencyTypeOptions.value);
            } else {
                dictLists.value = [];
                currencyTypeOptions.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
})


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 templateUrl = 'https://yd-ali-oss.oss-cn-shanghai-finance-1-pub.aliyuncs.com/xlsx/2025/10/14/54ce715eabab4f1abd8652ba0fca0c51.xlsx'
  // 修改下载文件名
  const fileName = '对账单导入模板.xlsx'
  // 下载文件
  window.open(templateUrl, '_blank', `download=${fileName}-${new Date().getTime()}`)
}


// 新增入账
const handleAdd = () => {
  incomeDialogTitle.value = '新增入账记录'
  isEditMode.value = false
  
  // 重置表单数据
  Object.assign(incomeForm, {
    commissionBizId: '',
    policyNo: '',
    reconciliationCompany: '',
    commissionPeriod: 1,
    totalPeriod: 1,
    commissionName: '',
    amount: 0,
    currency: 'HKD',
    commissionDate: '',
    remark: ''
  })
  
  // 重置表单验证
  if (incomeFormRef.value) {
    incomeFormRef.value.clearValidate()
  }
  
  incomeDialogVisible.value = true
}


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 incomeDialogVisible = ref(false)
const incomeDialogTitle = ref('入账记录')
const incomeLoading = ref(false)
const isEditMode = ref(false)
const incomeFormRef = ref()

// 入账表单数据
const incomeForm = reactive({
  commissionBizId: '',
  policyNo: '',
  reconciliationCompany: '',
  commissionPeriod: 1,
  totalPeriod: 1,
  commissionName: '',
  amount: 0,
  currency: 'CNY',
  commissionDate: '',
  remark: ''
})
// 表单验证规则
const incomeFormRules = {
  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) => {
  incomeDialogTitle.value = `编辑入账记录 - ${row.policyNo}`
  isEditMode.value = true
  
  // 填充表单数据
  Object.assign(incomeForm, {
    commissionBizId: row.commissionBizId,
    policyNo: row.policyNo,
    reconciliationCompany: row.reconciliationCompany,
    commissionPeriod: row.commissionPeriod || 1,
    totalPeriod: row.totalPeriod || 1,
    commissionName: row.commissionName,
    amount: row.amount,
    currency: row.currency || 'CNY',
    commissionDate: row.commissionDate,
    remark: row.remark || ''
  })
  
  // 重置表单验证
  if (incomeFormRef.value) {
    incomeFormRef.value.clearValidate()
  }
  
  incomeDialogVisible.value = true
}


// 提交入账表单（新增/编辑共用）
import { addPolicyCommission } from '@/api/financial/commission'
const submitIncomeForm = async () => {
  if (!incomeFormRef.value) {
    ElMessage.error('请先初始化表单')
    return
  }
  
  try {
    // 表单验证
    const valid = await incomeFormRef.value.validate()
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }
    
    incomeLoading.value = true
    
    if (isEditMode.value) {
      // 编辑模式 - 调用更新接口
      await updatePolicyCommission(incomeForm)
      ElMessage.success('更新成功')
    } else {
      // 新增模式 - 调用新增接口
      // 注意：这里需要根据实际的新增API进行调整
      await addPolicyCommission(incomeForm)
      ElMessage.success('新增成功')
    }
    
    incomeDialogVisible.value = false
    fetchTableData() // 刷新表格数据
  } catch (error) {
    if (error && error.errorFields) {
      ElMessage.warning('请完善表单信息')
    } else {
      console.error(isEditMode.value ? '更新失败:' : '新增失败:', error)
      ElMessage.error(isEditMode.value ? '更新失败' : '新增失败')
    }
  } finally {
    incomeLoading.value = false
  }
}

// 关闭对话框处理
const handleCloseDialog = (done) => {
  if (incomeLoading.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>