<template>
  <div class="financial-billing-page app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="保单号">
              <el-input v-model="queryParams.policyNo" placeholder="请输入保单号" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="出账日期">
              <el-date-picker
                v-model="queryParams.billingDate"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <el-row :gutter="20">
        <el-text class="mx-1" type="danger" style="margin-right: 20px"
          >勾选出账记录，点击“下载选中项”按钮，下载导入模版</el-text
        >
      </el-row>
      <div class="button-row" style="display: flex; gap: 1rem; justify-content: end">
        <el-button type="primary" :disabled="selectedRows.length === 0" @click="downloadSelected">
          下载选中项
        </el-button>
        <FileUpload
          :fileType="['xlsx', 'xls']"
          :action="'/csf/api/fortune/upload/excel'"
          :uploadBtnText="'批量导入'"
          :isShowTip="false"
          @uploadEnd="getUploadFileFunc"
          :responseType="'onlyStatus'"
        />
        <el-button
          type="success"
          :disabled="selectedRows.length === 0"
          @click="generateBillingList"
        >
          生成出账清单
        </el-button>
      </div>
      <div class="totalData" v-if="getAllSelectedRows().length > 0 || isSearch">
        <span v-for="(item, index) in statisticList">
          <span :style="{ marginLeft: index == 0 ? ' 0' : '20px' }">{{ item.name }}：</span>
          <span>{{ item.format ? formatCurrency(item.value) : item.value }}</span>
        </span>
      </div>
      <el-table
        :data="tableData"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        row-key="fortuneBizId"
        :reserve-selection="true"
        ref="tableRef"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column prop="policyNo" label="保单号" min-width="120" />
        <el-table-column prop="commissionAmount" label="本次已来佣金额" width="150">
          <template #default="{ row }">
            {{ formatCurrency(row.commissionAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="fortunePeriod" label="出账期数" width="100" />
        <el-table-column prop="fortuneTotalPeriod" label="预计总期数" width="100" />
        <el-table-column prop="fortuneName" label="出账项目" min-width="120" />
        <el-table-column prop="broker" label="转介人" min-width="100" />
        <el-table-column prop="team" label="所属团队" min-width="120" />
        <el-table-column prop="amount" label="出账金额" width="120">
          <template #default="{ row }">
            {{ formatCurrency(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="currency" label="出账币种" width="100" />
        <el-table-column prop="status" label="出账状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ convertStatusToDict(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <!-- <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button size="small" type="info" @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column> -->
      </el-table>

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

    <!-- 新建/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="保单号" required>
          <el-input v-model="formData.policyNo" />
        </el-form-item>
        <el-form-item label="对账公司" required>
          <el-select v-model="formData.company">
            <el-option
              v-for="item in companyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出账期数" required>
          <el-input-number v-model="formData.billingPeriod" :min="1" />
        </el-form-item>
        <el-form-item label="预计总期数" required>
          <el-input-number v-model="formData.totalPeriods" :min="1" />
        </el-form-item>
        <el-form-item label="出账项目" required>
          <el-input v-model="formData.billingItem" />
        </el-form-item>
        <el-form-item label="转介人">
          <el-input v-model="formData.referrer" />
        </el-form-item>
        <el-form-item label="所属团队">
          <el-input v-model="formData.team" />
        </el-form-item>
        <el-form-item label="出账金额" required>
          <el-input-number v-model="formData.amount" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="出账币种" required>
          <el-select v-model="formData.currency">
            <el-option label="人民币" value="CNY" />
            <el-option label="美元" value="USD" />
            <el-option label="港币" value="HKD" />
          </el-select>
        </el-form-item>
        <el-form-item label="出账状态" required>
          <el-select v-model="formData.status">
            <el-option label="待出账" value="pending" />
            <el-option label="已出账" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 引入API
import {
  getPolicyFortuneList,
  downloadPolicyFortune,
  downloadPolicyFortuneAccount,
  billStatistics
} from '@/api/financial/commission'
// 添加表格引用
const tableRef = ref()
// 存储所有选中的行数据（用于跨页保持选择）
const allSelectedRows = ref(new Map())
const isSearch = ref(false)
const statisticList = ref([
  { name: '总出账金额', value: '0', key: 'totalOutAmount', format: true },
  { name: '总入账金额', value: '0', key: 'totalInAmount', format: true },
  { name: '总保单数', value: '0', key: 'totalPolicyCount', format: false }
])
// 查询参数
const queryParams = reactive({
  policyNo: '',
  company: '',
  billingDate: [],
  pageNum: 1,
  pageSize: 100
  // pageSize: 10
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = reactive({
  policyNo: '',
  company: '',
  billingPeriod: 1,
  totalPeriods: 1,
  billingItem: '',
  referrer: '',
  team: '',
  amount: 0,
  currency: 'CNY',
  status: 'pending',
  remark: ''
})
// 设置当前页的选中状态
const setCurrentPageSelection = () => {
  if (!tableRef.value) return

  // 清除当前页的选择
  // tableRef.value.clearSelection()

  // 设置当前页应该选中的行
  tableData.value.forEach(row => {
    if (allSelectedRows.value.has(row.fortuneBizId)) {
      tableRef.value.toggleRowSelection(row, true)
    }
  })
}
// 获取所有选中的行（包含跨页选择的）
const getAllSelectedRows = () => {
  return Array.from(allSelectedRows.value.values())
}
// 更新全局选中状态
const updateAllSelectedRows = () => {
  // 获取当前页的所有行的 key（fortuneBizId）
  const currentPageKeys = tableData.value.map(row => row.fortuneBizId)

  // 从全局选中中移除当前页不再存在的行
  // for (const key of allSelectedRows.value.keys()) {
  //   if (!currentPageKeys.includes(key)) {
  //     allSelectedRows.value.delete(key)
  //   }
  // }

  // 更新当前页的选中状态
  tableData.value.forEach(row => {
    const isSelected = selectedRows.value.some(
      selectedRow => selectedRow.fortuneBizId === row.fortuneBizId
    )

    if (isSelected) {
      allSelectedRows.value.set(row.fortuneBizId, row)
    } else {
      allSelectedRows.value.delete(row.fortuneBizId)
    }
  })
  // 当勾选项发生变化的时候，拿到最新的统计数据
  getStatistics()
}
const getStatistics = async () => {
  try {
    let fortuneIdList = getAllSelectedRows().map(item => item.id)
    if (fortuneIdList.length > 0) {
      // 调用接口获取来佣列表
      const res = await billStatistics({
        fortuneIdList: fortuneIdList
      })
      if (res.data) {
        statisticList.value.forEach(item => {
          item.value = res.data[item.key]
        })
      }
    } else {
      isSearch.value = false
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('统计失败')
  }
}
// 清空所有选择
const clearAllSelection = () => {
  allSelectedRows.value.clear()
  selectedRows.value = []
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}
// 下载选中项
const downloadSelected = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要下载的项')
    return
  }
  try {
    // API调用
    const response = await downloadPolicyFortune({
      fortuneBizIdList: selectedRows.value.map(row => row.fortuneBizId)
    })
    if (response) {
      ElMessage.success('下载成功')
      // 触发文件下载
      // 处理下载响应
      const blob =
        response instanceof Blob
          ? response
          : new Blob([response], { type: 'application/vnd.ms-excel;charset=utf-8' })
      // 创建Blob对象，指定正确的MIME类型
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      // 不需要指定文件名，浏览器会自动使用默认文件名
      link.download = `出账管理_${new Date().getTime()}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } else {
      ElMessage.error('下载失败')
    }
  } catch (error) {
    ElMessage.error('下载失败')
  }
}
const getUploadFileFunc = data => {
  console.log(data)
  if (data === 200) {
    ElMessage.success('上传成功')
    getList()
  } else {
    ElMessage.error('上传失败')
  }
}
// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    // API调用
    const response = await getPolicyFortuneList(queryParams)
    if (response.data.page) {
      tableData.value = response.data.page.records
      total.value = response.data.page.total
      loading.value = false
    }
    if (response.data.statisticsVO && isSearch.value) {
      statisticList.value.forEach(item => {
        item.value = response.data.statisticsVO[item.key]
      })
    }
    // 数据加载完成后，设置当前页的选中状态
    nextTick(() => {
      setCurrentPageSelection()
    })
  } catch (error) {
    loading.value = false
    tableData.value = []
    console.log('获取列表失败', error)

    // ElMessage.error('获取数据失败')
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  Object.values(queryParams).some(value => {
    if (Array.isArray(value) && value.length > 0) {
      isSearch.value = true
    }
    if (value !== '' && value != null) {
      isSearch.value = true
    }
  })
  clearAllSelection()
  getList()
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    policyNo: '',
    company: '',
    billingDate: [],
    pageNum: 1,
    pageSize: 100
  })
  isSearch.value = false
  // 清空选择
  clearAllSelection()
  getList()
}

// 选择行变化
const handleSelectionChange = selection => {
  selectedRows.value = selection
  updateAllSelectedRows()
}

// 新建出账记录
const handleCreate = () => {
  dialogTitle.value = '新建出账记录'
  Object.assign(formData, {
    policyNo: '',
    company: '',
    billingPeriod: 1,
    totalPeriods: 1,
    billingItem: '',
    referrer: '',
    team: '',
    amount: 0,
    currency: 'CNY',
    status: 'pending',
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑出账记录
const handleEdit = row => {
  dialogTitle.value = '编辑出账记录'
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 删除出账记录
const handleDelete = async row => {
  try {
    await ElMessageBox.confirm('确认删除这条出账记录吗？', '提示', {
      type: 'warning'
    })
    // await api.deleteBilling(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 查看详情
const handleView = row => {
  // 这里可以跳转到详情页面或者打开详情对话框
  ElMessage.info(`查看保单号：${row.policyNo}`)
}

const generateBillingList = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要生成清单的记录')
    return
  }
  ElMessageBox.confirm(`确认生成 ${selectedRows.value.length} 条记录的出账清单吗？`, '提示', {
    type: 'warning'
  })
    .then(async () => {
      console.log('开始生成出账清单')
      const response = await downloadPolicyFortuneAccount({
        fortuneBizIdList: selectedRows.value.map(item => item.fortuneBizId)
      })
      console.log(response)
      // 调用下载API
      if (response) {
        // 处理下载响应
        const blob =
          response instanceof Blob
            ? response
            : new Blob([response], { type: 'application/vnd.ms-excel;charset=utf-8' })
        // 创建Blob对象，指定正确的MIME类型
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        // 不需要指定文件名，浏览器会自动使用默认文件名
        link.download = `出账清单_${new Date().getTime()}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } else {
        ElMessage.error('下载失败')
      }
      selectedRows.value = []
    })
    .catch(error => {
      if (error !== 'cancel') {
        console.log('生成出账清单出错:', error)
      }
    })
}

// 提交表单
const submitForm = async () => {
  try {
    // 表单验证
    if (!formData.policyNo || !formData.company || !formData.billingItem) {
      ElMessage.warning('请填写必填字段')
      return
    }

    // 调用保存API
    // if (formData.id) {
    //   await api.updateBilling(formData)
    // } else {
    //   await api.createBilling(formData)
    // }

    ElMessage.success('保存成功')
    dialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 格式化金额
const formatCurrency = amount => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(amount)
}

// 获取状态标签类型
const getStatusType = status => {
  const types = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return types[status] || 'info'
}
import { listType } from '@/api/system/dict/type'
const dictLists = ref([])
// 获取出账状态字典值
const getDictLists = () => {
  return new Promise((resolve, reject) => {
    listType({ typeList: ['csf_fortune_status'] })
      .then(res => {
        if (res.code === 200 && res.data) {
          const dictData = res.data.find(item => item.dictType === 'csf_fortune_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
}

// 初始化
onMounted(() => {
  getDictLists()
  getList()
})
</script>

<style scoped>
.totalData {
  margin-bottom: 10px;
  font-size: 14px;
  color: #000;
}
.financial-billing-page {
  padding: 20px;
}

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

.operation-card {
  margin-bottom: 20px;
}

.el-table {
  margin-bottom: 20px;
}

.el-pagination {
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .financial-billing-page {
    padding: 10px;
  }

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

  .operation-card {
    margin-bottom: 15px;
  }

  .el-col {
    margin-bottom: 10px;
  }
}
</style>
