<template>
  <div class="financial-salary-page">
    <!-- 查询区域 -->
    <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-input v-model="queryParams.broker" 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.accountDate"
                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 label="出账状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option
                  v-for="item in dictLists"
                  :key="item.itemValue"
                  :label="item.itemLabel"
                  :value="item.itemValue"
                />
              </el-select>
            </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 class="operation-card">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-button type="primary" @click="handleCreate">新建薪资记录</el-button>
          <el-button @click="handleImport">批量导入</el-button>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button type="success" :disabled="selectedRows.length === 0" @click="completeBilling">
            完成出账
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <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"
        ref="tableRef"
        row-key="fortuneAccountBizId"
        :reserve-selection="true"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column prop="broker" label="转介人" min-width="120" />
        <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">
          <template #default="scope">
            <dict-tag :options="currencyTypeOptions" :value="scope.row.currency" />
          </template>
        </el-table-column>
        <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="300" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)">修改</el-button>
            <el-button size="small" type="primary" @click="handleRevise(row)">修订记录</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <!-- <el-button size="small" type="info" @click="generateSalarySlip(row)">生成薪资单</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNo"
        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="新建薪资记录" v-model="createDialogVisible" width="500px">
      <el-form :model="createFormData" label-width="100px">
        <el-form-item label="转介人" required>
          <el-select v-model="createFormData.referrer" placeholder="请选择转介人">
            <el-option
              v-for="item in referrerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出账金额" required>
          <el-input-number
            v-model="createFormData.amount"
            :min="-10000000000000"
            :precision="2"
            placeholder="请输入出账金额"
          />
        </el-form-item>
        <el-form-item label="出账项目" required>
          <el-input v-model="createFormData.billingItem" placeholder="请输入出账项目" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="createFormData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 出账完成弹窗 -->
    <el-dialog title="出账完成" v-model="billingCompleteDialogVisible" width="400px">
      <div style="text-align: center">
        <el-icon size="48" color="#67C23A">
          <SuccessFilled />
        </el-icon>
        <p style="margin-top: 16px; font-size: 16px">出账操作已完成！</p>
      </div>
      <template #footer>
        <!-- <el-button type="primary" @click="generateSalarySlips">生成薪资单</el-button> -->
        <el-button @click="billingCompleteDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog title="修订记录" v-model="showReviseRecord" width="1000px" append-to-body>
      <el-table :data="reviseList" border>
        <el-table-column prop="createTime" label="修订时间" align="center" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修订人" prop="userName" align="center" width="150">
        </el-table-column>

        <el-table-column label="修订内容" prop="editContent" align="center"></el-table-column>
      </el-table>
      <pagination
        v-show="revisePages.total >= 0"
        :total="revisePages.total"
        v-model:page="revisePages.pageNo"
        v-model:limit="revisePages.pageSize"
        @pagination="getReviseData"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { SuccessFilled } from '@element-plus/icons-vue'
import {
  getReferrerFortuneList,
  updatePolicyFortuneStatus,
  salaryStatistics,
  salaryEditRecords
} from '@/api/financial/commission'

// 添加表格引用
const tableRef = ref()
// 存储所有选中的行数据（用于跨页保持选择）
const allSelectedRows = ref(new Map())
const isSearch = ref(false)
const statisticList = ref([
  { name: '总金额', value: '0', key: 'totalAmount', format: true },

  { name: '总人数', value: '0', key: 'brokerCount', format: false }
])
// 查询参数
const queryParams = reactive({
  broker: '',
  accountDate: [],
  accountDateStart: '',
  accountDateEnd: '',
  pageNo: 1,
  pageSize: 10,
  sortField: '',
  sortOrder: 'desc'
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const showReviseRecord = ref(false)
const reviseList = ref([])
const currencyTypeOptions = ref([])
const revisePages = reactive({
  total: 0,
  pageNo: 1,
  pageSize: 5
})
// 对话框相关
const createDialogVisible = ref(false)
const billingCompleteDialogVisible = ref(false)

// 新建表单数据
const createFormData = reactive({
  referrer: '',
  amount: 0,
  billingItem: '',
  remark: ''
})

// 转介人选项
const referrerOptions = [
  { label: '张三', value: 'zhangsan' },
  { label: '李四', value: 'lisi' },
  { label: '王五', value: 'wangwu' },
  { label: '赵六', value: 'zhaoliu' }
]
const currentRow = ref({})
const getReviseData = () => {
  let data = {
    pageNo: revisePages.pageNo,
    pageSize: revisePages.pageSize,
    fortuneAccountBizId: currentRow.value.fortuneAccountBizId
  }
  salaryEditRecords(data).then(response => {
    if (response.code == 200) {
      reviseList.value = response.data.records
      revisePages.total = response.data.total
      showReviseRecord.value = true
    } else {
      ElMessage.error(response.msg)
      showReviseRecord.value = false
      revisePages.total = 0
      reviseList.value = []
    }
  })
}
// 设置当前页的选中状态
const setCurrentPageSelection = () => {
  if (!tableRef.value) return

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

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

  // 从全局选中中移除当前页不再存在的行
  // 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.fortuneAccountBizId === row.fortuneAccountBizId
    )

    if (isSelected) {
      allSelectedRows.value.set(row.fortuneAccountBizId, row)
    } else {
      allSelectedRows.value.delete(row.fortuneAccountBizId)
    }
  })
  // 当勾选项发生变化的时候，拿到最新的统计数据
  getStatistics()
}
const getStatistics = async () => {
  try {
    let fortuneAccountIdList = getAllSelectedRows().map(item => item.id)
    if (fortuneAccountIdList.length > 0) {
      // 调用接口获取来佣列表
      const res = await salaryStatistics({
        fortuneAccountIdList: fortuneAccountIdList
      })
      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 closeDialog = () => {
  showReviseRecord.value = false
  reviseList.value = []
  revisePages.value = {
    pageNo: 1,
    pageSize: 5,
    total: 0
  }
}
// 初始化
onMounted(() => {
  getDictLists()
  getList()
})

// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    if (queryParams.accountDate.length > 0) {
      queryParams.accountDateStart = queryParams.accountDate[0]
      queryParams.accountDateEnd = queryParams.accountDate[1]
    }
    const response = await getReferrerFortuneList(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
    // ElMessage.error('获取数据失败')
  }
}

const getStatusType = status => {
  const types = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return types[status] || 'info'
}

// 查询
const handleQuery = () => {
  queryParams.pageNo = 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, {
    broker: '',
    accountDateStart: '',
    accountDateEnd: '',
    pageNo: 1,
    pageSize: 10,
    sortField: '',
    sortOrder: 'desc'
  })
  isSearch.value = false
  // 清空选择
  clearAllSelection()
  getList()
}

// 选择行变化
const handleSelectionChange = selection => {
  selectedRows.value = selection
  // 更新全局选中状态
  updateAllSelectedRows()
}

// 新建薪资记录
const handleCreate = () => {
  Object.assign(createFormData, {
    referrer: '',
    amount: 0,
    billingItem: '',
    remark: ''
  })
  createDialogVisible.value = true
}

// 编辑薪资记录
const handleEdit = row => {
  // 这里可以打开编辑对话框
  ElMessage.info(`编辑转介人：${row.referrer}`)
}
const handleRevise = row => {
  currentRow.value = row
  getReviseData()
}

const deletePolicyFortuneO = async fortuneAccountBizId => {
  try {
    await deletePolicyFortune({ fortuneAccountBizId })
  } catch (error) {
    ElMessage.error('删除出账失败')
  }
}

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

// 批量导入
const handleImport = () => {
  ElMessage.info('批量导入功能待实现')
}

// 完成出账
const completeBilling = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要出账的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认完成 ${selectedRows.value.length} 条记录的出账操作吗？`,
      '提示',
      { type: 'warning' }
    )
    console.log(selectedRows.value)
    const arr = selectedRows.value.map(item => item.fortuneAccountBizId)

    // 调用出账API
    await fetchCompletePolicyFortune(arr)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('出账操作失败')
    }
  }
}

// 生成薪资单（单条）
const generateSalarySlip = row => {
  // 调用生成薪资单API
  // await api.generateSalarySlip(row.id)
  ElMessage.success(`已为 ${row.referrer} 生成薪资单`)
}

// 生成薪资单（批量）
const generateSalarySlips = () => {
  // 调用批量生成薪资单API
  // await api.generateSalarySlips(selectedRows.value.map(item => item.id))
  ElMessage.success(`已为 ${selectedRows.value.length} 条记录生成薪资单`)
  billingCompleteDialogVisible.value = false
  selectedRows.value = []
}

// 提交新建表单
const submitCreateForm = async () => {
  try {
    // 表单验证
    if (!createFormData.referrer || !createFormData.amount || !createFormData.billingItem) {
      ElMessage.warning('请填写必填字段')
      return
    }

    // 调用保存API
    // await api.createSalary(createFormData)

    ElMessage.success('新建成功')
    createDialogVisible.value = false
    getList()
  } catch (error) {
    ElMessage.error('新建失败')
  }
}

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

import { listType } from '@/api/system/dict/type'
const dictLists = ref([])
// 获取出账状态字典值
const getDictLists = () => {
  return new Promise((resolve, reject) => {
    listType({ typeList: ['csf_fortune_status', 'bx_currency_type'] })
      .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)
          // 处理币种字典值
          const currencyData = res.data.find(item => item.dictType === 'bx_currency_type')
          if (currencyData) {
            currencyData?.dictItemList.forEach(item => {
              item.value = item.itemValue
              item.label = item.itemLabel
            })
          }
          currencyTypeOptions.value = currencyData?.dictItemList || []
          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
}

// 更新出账状态
const updateStatus = async row => {
  try {
    const res = await updatePolicyFortuneStatus({
      fortuneBizIdList: row,
      status: 2
    })
    console.log(res)
    if (res.code === 200) {
      // 显示完成弹窗
      billingCompleteDialogVisible.value = true
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {}
}

// 完成出账
import { completePolicyFortune } from '@/api/financial/commission'
const fetchCompletePolicyFortune = async row => {
  try {
    const res = await completePolicyFortune({
      fortuneAccountBizIdList: row
    })
    console.log(res)
    if (res.code === 200) {
      // 显示完成弹窗
      billingCompleteDialogVisible.value = true
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {}
}

// 删除出账
import { deletePolicyFortune } from '@/api/financial/commission'
// 删除出账
const deleteFortune = async row => {
  try {
    const res = await deletePolicyFortune({
      fortuneAccountBizId: row
    })
    console.log(res)
    if (res.code === 200) {
      // 显示完成弹窗
      billingCompleteDialogVisible.value = true
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {}
}
</script>

<style scoped>
.totalData {
  margin-bottom: 10px;
  font-size: 14px;
  color: #000;
}
.financial-salary-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-salary-page {
    padding: 10px;
  }

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

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

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