<template>
  <div class='app-container'>
    <CommonPage :operationBtnList='operationBtnList' :visibleDefaultButtons='visibleDefaultButtons'
      :showSearchForm='true' :show-pagination='true' :total='pageTotal' :current-page='currentPage'
      :page-size='pageSize' @size-change='handleSizeChange' @current-change='handleCurrentChange'>
      <!-- 搜索区域 -->
      <template #searchForm>
        <SearchForm ref="searchFormRef" :config="searchConfig" />
      </template>
      <!-- 列表区域 -->
      <template #table>
        <!-- 统计数据 -->
        <div class="statistics-container">
          <el-row :gutter="16">
            <el-col :xs="24" :sm="12" :md="6" class="text-center mb-4">
              <el-statistic title="总金额" :value="statisticInfo.totalAmount" />
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" class="text-center mb-4">
              <el-statistic title="总人数" :value="statisticInfo.brokerCount" />
            </el-col>
          </el-row>
        </div>
        <el-table :data="tableData" @selection-change="handleSelectionChange" v-loading="loading" ref="tableRef"
          row-key="fortuneAccountBizId" :reserve-selection="true" :border="true">
          <el-table-column type="selection" width="55" :reserve-selection="true" />
          <el-table-column prop="broker" label="转介人" min-width="120" sortable />
          <el-table-column prop="team" label="所属团队" min-width="120" sortable />
          <el-table-column prop="amount" label="出账金额" width="120" sortable>
            <template #default="scope">
              {{ formatCurrency(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="currency" label="出账币种" width="120" sortable>
            <template #default="scope">
              <dict-tag :options="currencyTypeOptions" :value="scope.row.currency" />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="出账状态" width="150" sortable>
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ convertStatusToDict(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="fortuneAccountDate" label="出账日" min-width="150" show-overflow-tooltip />
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        </el-table>
      </template>
    </CommonPage>
    <!-- 弹窗-->
    <CommonDialog dialogTitle='出账完成' dialogWidth='80%' :openDialog=billingCompleteDialogVisible :showAction='false'
      :showClose='true' @close='billingCompleteDialogVisible = false'>
      <div style="text-align: center">
        <el-icon size="48" color="#67C23A">
          <SuccessFilled />
        </el-icon>
        <p style="margin-top: 16px; font-size: 16px">出账操作已完成！</p>
      </div>
    </CommonDialog>
    <CommonDialog dialogTitle='修订记录' dialogWidth='80%' :openDialog=showReviseRecord :showAction='false'
      :showClose='true' @close='showReviseRecord = false'>
      <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>
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import CommonPage from '@/components/commonPage'
import CommonDialog from '@/components/commonDialog'
import {
  getReferrerFortuneList,
  salaryStatistics,
} from '@/api/financial/commission'
import { formatCurrency } from '@/utils/number'
import { ElMessageBox, ElMessage } from 'element-plus'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
const searchFormRef = ref(null)
const searchParams = ref({})
const searchConfig = ref([
  {
    type: 'select',
    prop: 'brokerBizIdList',
    label: '转介人',
    api: '/insurance/base/api/userSaleExpand/page',
    keywordField: 'realName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'userSaleBizId',
    labelKey: 'realName',
    multiple: true,
    transform: (res) => {
      return res?.data.records || []
    }
  },
  {
    type: 'daterange',
    prop: 'payoutDate',
    label: '出账日（实）',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    type: 'select',
    prop: 'statusList',
    label: '出账状态',
    dictType: 'csf_expected_fortune_status',
    multiple: true,
    defaultValue: ['6'],//默认查询待出账，已检核的数据
  }
])
// 添加表格引用
const tableRef = ref()
// 存储所有选中的行数据（用于跨页保持选择）
const allSelectedRows = ref(new Map())
const isSearch = ref(false)
const statisticInfo = ref({
  totalAmount: 0,
  brokerCount: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])
const showReviseRecord = ref(false)
const reviseList = ref([])
const currencyTypeOptions = ref([])

// 对话框相关
const billingCompleteDialogVisible = ref(false)
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)


// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 设置当前页的选中状态
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 = () => {
  // 更新当前页的选中状态
  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) {
        statisticInfo.value = res.data
      }
    } 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 getList = async (searchParams = {}) => {
  loading.value = true
  try {
    const params = {
      ...searchParams,
      accountDateStart: searchParams.payoutDate?.[0] || undefined,
      accountDateEnd: searchParams.payoutDate?.[1] || undefined,
      payoutDate:undefined,
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await getReferrerFortuneList(params)

    if (response.data.page) {
      tableData.value = response.data.page.records
      pageTotal.value = response.data.page.total
      loading.value = false
    }
    if (response.data.statisticsVO) {
      statisticInfo.value = response.data.statisticsVO
    }
    // 数据加载完成后，设置当前页的选中状态
    nextTick(() => {
      setCurrentPageSelection()
    })
  } catch (error) {
    loading.value = false
    // ElMessage.error('获取数据失败')
  }
}
getList()

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

// 查询
const handleQuery = () => {
  const params = searchFormRef.value.getFormData()
  console.log('父组件发起查询:', params)
  clearAllSelection()
  getList(params)
}

// 重置查询
const handleReset = () => {
  // 重置搜索表单
  searchFormRef.value.resetForm()
  searchParams.value = {}
  console.log('表单已重置')
  getList(searchParams.value)
}

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



// 完成出账
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('出账操作失败')
    }
  }
}

import { listType } from '@/api/system/dict/type'
const dictLists = ref([])
// 获取出账状态字典值
const getDictLists = () => {
  return new Promise((resolve, reject) => {
    listType({ typeList: ['csf_expected_fortune_status', 'bx_currency_type'] })
      .then(res => {
        if (res.code === 200 && res.data) {
          const dictData = res.data.find(item => item.dictType === 'csf_expected_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)
      })
  })
}
getDictLists()

// 返回数据中状态需要转换为字典值
const convertStatusToDict = status => {
  const dictItem = dictLists.value.find(item => item.itemValue == status)
  return dictItem?.itemLabel ?? status
}

// 完成出账
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) { }
}


const visibleDefaultButtons = ref(['reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  {
    key: 'reset',
    direction: 'right',
    click: handleReset
  },
  {
    key: 'query',
    direction: 'right',
    click: handleQuery
  },
  {
    key: 'custom',
    label: '完成出账',
    icon: 'Check',
    type: 'warning',
    direction: 'right',
    size: 'default',
    click: completeBilling
  }
])

</script>

<style scoped></style>