<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>
        <el-table :data="tableData" v-loading="loading" ref="tableRef"
          row-key="salarySplitNo" :reserve-selection="true" :border="true">
                <el-table-column v-for="(column, index) in tableColumns" :key="index" :fixed="column.fixed"
                        :prop="column.prop" :label="column.label" :width="column.width" :sortable="column.sortable"
                        :formatter="column.formatter" />
        </el-table>
      </template>
    </CommonPage>


  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import CommonPage from '@/components/commonPage'
import {salarySummary,exportPayRoll} from '@/api/financial/commission'
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: 'clientUserBizId',
    labelKey: 'realName',
    multiple: true,
    transform: (res) => {
      return res?.data.records || []
    }
  },
  {
    type: 'monthrange',
    prop: 'payoutMonth',
    label: '出账年月（实）',
    startPlaceholder: '开始年月',
    endPlaceholder: '结束年月'
  },
  {
    type: 'input',
    prop: 'billOrg',
    label: '出账机构',
  }
])

const tableColumns = ref([
  { prop: 'salarySplitNo', label: '发放编号', sortable: true, width: '150', fixed: 'left' },
    { prop: 'businessNo', label: '业务编号' , width: '150',fixed:'left'},
    { prop: 'brokerName', label: '转介人', sortable: true, width: '150',fixed:'left'},
    { prop: 'internalNumber', label: '内部编号', sortable: true, width: '150'},
    { prop: 'team', label: '所属团队', sortable: true, width: '150'},
    { prop: 'fromAmount', label: '原币种金额', sortable: true, width: '150'},
    { prop: 'currency', label: '原币种', sortable: true, width: '150'},
    { prop: 'exchangeRate', label: '汇率（原币种->目标币种)', sortable: true, width: '150'},
    { prop: 'toAmount', label: '目标金额', sortable: true, width: '150'},
    { prop: 'toCurrency', label: '目标币种', sortable: true, width: '150'},
    { prop: 'fortuneAccountMonth', label: '出账月（实）', sortable: true, width: '150'},
    { prop: 'billOrg', label: '出账机构', sortable: true, width: '150'},
    { prop: 'hkdAmount', label: '本期总出账金额(原币种)', sortable: true, width: '150'},
    { prop: 'fortuneAccountBizId', label: '出账记录业务id', sortable: true, width: '150'},

])
// 添加表格引用
const tableRef = ref()

// 表格数据
const tableData = ref([])
const loading = 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 getList = async (searchParams = {}) => {
  loading.value = true
  try {
    const params = {
      ...searchParams,
      startMonth:searchParams.payoutMonth ? searchParams.payoutMonth[0] : '',
      endMonth:searchParams.payoutMonth ? searchParams.payoutMonth[1] :'',
      payoutMonth:undefined,
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await salarySummary(params)

    if (response.data.page) {
      tableData.value = response.data.page.records
      pageTotal.value = response.data.page.total
      loading.value = false
    }
  } catch (error) {
    loading.value = false
    // ElMessage.error('获取数据失败')
  }
}
getList()

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

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

const handleExport = async () => {
  // 获取搜索参数
  let params = searchFormRef.value?.getFormData()
  params = {
      ...params,
      startMonth:params.payoutMonth ? params.payoutMonth[0] : '',
      endMonth:params.payoutMonth ? params.payoutMonth[1] :'',
      payoutMonth:undefined,

    }
  const response = await exportPayRoll(params)
  if(response.data && response.data.url){
    window.open(response.data.url)
  }else{
    ElMessage.error('导出失败')
  }

}


const visibleDefaultButtons = ref(['export','reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  {
    key: 'reset',
    direction: 'right',
    click: handleReset
  },
  {
    key: 'query',
    direction: 'right',
    click: handleQuery
  },
   {
    key: 'export',
    direction: 'right',
    click: handleExport
  }
])

</script>

<style scoped></style>
