<template>
  <div>
    <CommonPage :operationBtnList="operationBtnList" :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" v-if="statisticsData.totalPolicyCount > 0">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">应出款总金额</div>
                  <div class="card-value">{{ formatCurrency(statisticsData.totalAmount) }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">已出账金额</div>
                  <div class="card-value">{{ formatCurrency(statisticsData.totalPaidAmount) }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">待出账金额</div>
                  <div class="card-value">{{ formatCurrency(statisticsData.pendingPaidAmount) }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">已出账比例</div>
                  <div class="card-value">{{ statisticsData.paidAmountRatio }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">总保单数</div>
                  <div class="card-value">{{ statisticsData.totalPolicyCount }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">总保费</div>
                  <div class="card-value">{{ statisticsData.totalPolicyCount }}</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <!-- 应付款管理列表 -->
        <el-table :data="tableData" height="400" border highlight-current-row style="width: 100%" v-loading="loading">
          <el-table-column prop="fortuneBizType" label="应付款类型" width="120" fixed="left" sortable>
            <template #default="{ row }">
              {{ getFortuneBizTypeLabel(row.fortuneBizType) }}
            </template>
          </el-table-column>
          <el-table-column prop="payableNo" label="应付款编号" width="120" sortable />
          <el-table-column prop="policyNo" label="保单号" width="120" sortable />
          <el-table-column prop="broker" label="转介人" width="120" sortable />
          <el-table-column prop="status" label="出账状态" width="120" sortable>
            <template #default="{ row }">
              {{ getDictLabel('csf_expected_fortune_status', row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="currency" label="出账币种" width="120" sortable />
          <el-table-column prop="fortunePeriod" label="出账期数" width="120" sortable />
          <el-table-column prop="fortuneTotalPeriod" label="出账总期数" width="120" sortable />
          <el-table-column prop="fortuneName" label="出账项目" width="120" sortable />
          <el-table-column prop="payoutDate" label="出账日(估)" width="120" sortable />
          <el-table-column prop="actualPayoutDate" label="出账日(实)" width="120" sortable />
          <el-table-column prop="commissionRatio" label="出账比例(估)" width="140" sortable>
            <template #default="{ row }">
              {{ (row.commissionRatio || 0) + '%' }}
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="出账金额(估)" width="140" sortable>
            <template #default="{ row }">
              {{ formatCurrency(row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="paidRatio" label="已出账比例" width="120" sortable>
            <template #default="{ row }">
              {{ (row.paidRatio || 0) + '%' }}
            </template>
          </el-table-column>
          <el-table-column prop="paidAmount" label="已出账金额" width="120" sortable>
            <template #default="{ row }">
              {{ formatCurrency(row.paidAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="pendingRatio" label="待出账比例" width="120" sortable>
            <template #default="{ row }">
              {{ (row.pendingRatio || 0) + '%' }}
            </template>
          </el-table-column>
          <el-table-column prop="unpaidAmount" label="待出账金额（估）" width="160" sortable>
            <template #default="{ row }">
              {{ formatCurrency(row.unpaidAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="broker_ratio" label="持有比例" width="120" sortable />
          <el-table-column prop="insurerBizId" label="保险公司" width="120" sortable />
          <el-table-column prop="productLaunchBizId" label="产品计划" width="120" sortable />
          <el-table-column prop="premium" label="期交保费" width="120" sortable>
            <template #default="{ row }">
              {{ formatCurrency(row.premium) }}
            </template>
          </el-table-column>
          <el-table-column prop="statusDesc" label="修改理由" width="150" />
          <el-table-column prop="remark" label="备注" width="150" />
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="{ row }">
              <el-popover placement="right" :width="200" trigger="click">
                <template #reference>
                  <el-icon>
                    <MoreFilled />
                  </el-icon>
                </template>
                <el-menu @select="handleSelect($event, row)" popper-class="custom-menu">
                  <el-menu-item :index="item.value" v-for="item in dropdownItems" :key="item.value">{{
                    item.label
                  }}</el-menu-item>
                </el-menu>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </CommonPage>
    <!-- 出账记录表格弹窗-->
    <CommonDialog dialogTitle="出账记录" dialogWidth="80%" :openDialog="payRecordDialogTableVisible" :showAction="true"
      :showClose="true" @close="payRecordDialogTableVisible = false">
      <el-table :data="payRecordDialogTableData" border style="width: 100%">
        <el-table-column v-for="item in payRecordDialogTableColumns" :key="item.property" :property="item.property"
          :label="item.label" :width="item.width" />
      </el-table>
    </CommonDialog>
    <!-- 新增出账记录 -->
    <CommonDialog dialogTitle="新增出账记录" dialogWidth="80%" :openDialog="addPayRecordDialogVisible" :showAction="true"
      :showClose="true" @close="addPayRecordDialogVisible = false" @confirm="handleConfirmAddPayRecord">
      <SearchForm ref="addPayRecordFormRef" :config="addPayRecordFormConfig" />
    </CommonDialog>
    <!-- 设置出账状态 -->
    <CommonDialog dialogTitle="设置出账状态" dialogWidth="80%" :openDialog="setPayRecordStatusDialogVisible"
      :showAction="false" :showClose="true" @close="setPayRecordStatusDialogVisible = false"
      @confirm="handleConfirmSetPayRecordStatus">
      <SearchForm ref="setPayRecordStatusFormRef" :config="setPayRecordStatusFormConfig" />
    </CommonDialog>

  </div>
</template>

<script setup name="Payables">
import CommonPage from '@/components/commonPage'
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatCurrency } from '@/utils/number'
import { expectedFortuneList, payRecordList, addPayRecord, userSaleExpandDetail } from '@/api/financial/commission'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import CommonDialog from '@/components/commonDialog'
import { getDictLabel } from '@/utils/useDict';
import useUserStore from '@/store/modules/user'
// 设置出账状态
const setPayRecordStatusDialogVisible = ref(false)
const selectedRow = ref(null)
const setPayRecordStatusFormRef = ref(null)
const setPayRecordStatusFormConfig = ref([
  {
    type: 'select',
    prop: 'status',
    label: '出账状态',
    dictType: 'csf_expected_fortune_status'
  }, {
    type: 'textarea',
    prop: 'statusDesc',
    label: '修改理由',
  },
])

const userStore = useUserStore()
// 应收单类型
const fortuneBizTypeOptions = [
  { value: 'R', label: '关联保单应付单' },
  { value: 'U', label: '非关联保单应付单' }
]
// 应付单类型通过value转成label
const getFortuneBizTypeLabel = (value) => {
  const item = fortuneBizTypeOptions.find(item => item.value === value)
  return item?.label || ''
}
const searchFormRef = ref(null)
const searchParams = ref({})
const searchConfig = ref([
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'daterange',
    prop: 'payoutDate',
    label: '出账日（估）',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    type: 'select',
    prop: 'statusList',
    label: '出账状态',
    multiple: true,
    dictType: 'csf_expected_fortune_status'
  },
  {
    type: 'input',
    prop: 'fortunePeriod',
    label: '出账期数',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  },
  {
    type: 'select',
    prop: 'fortuneName',
    label: '出账项目',
    dictType: 'csf_fortune_type'
  },
  {
    type: 'select',
    prop: 'insurerBizId',
    label: '保险公司',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'queryContent',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'abbreviation',
    transform: (res) => {
      console.log(res)
      return res?.data.records || []
    }
  }, {
    type: 'select',
    prop: 'productLaunchBizId',
    label: '产品计划',
    api: '/product/api/relProjectProductLaunch/parameter/page',
    keywordField: 'productName',
    requestParams: {
      tenantBizId: userStore.projectInfo.tenantBizId || '',
      projectBizId: userStore.projectInfo.projectBizId || '', fieldBizId: 'field_olk1qZe81qHHKXbw', fieldValueBizId: 'field_value_uOfJH5ucA2YwJpbn', pageNo: 1, pageSize: 20
    },
    placeholder: '输入产品计划名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'productLaunchBizId',
    labelKey: 'productName',
    transform: (res) => {
      return res?.data.records || []
    }
  }, {
    type: 'select',
    prop: 'fortuneBizType',
    label: '应付单类型',
    options: [
      { value: 'R', label: '关联保单应付单' },
      { value: 'U', label: '非关联保单应付单' }
    ]
  }, {
    type: 'select',
    prop: 'teamBizId',
    label: '出单团队',
    api: '/csf/api/team/page',
    keywordField: 'teamName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入出单团队名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'teamBizId',
    labelKey: 'teamName',
    transform: (res) => {
      return res?.data.records || []
    }
  },
])
const payRecordDialogTableVisible = ref(false)
// 新增出账记录
const addPayRecordDialogVisible = ref(false)
const addPayRecordFormRef = ref()
const addPayRecordFormConfig = ref([
  {
    type: 'select',
    prop: 'fortuneBizType',
    label: '应付单类型',
    options: [
      { value: 'R', label: '关联保单应付单' },
      { value: 'U', label: '非关联保单应付单' }
    ]
  }, {
    type: 'input',
    prop: 'policyNo',
    label: '关联保单号'
  }, {
    type: 'input',
    prop: 'fortunePeriod',
    label: '佣金期数',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  }, {
    type: 'input',
    prop: 'fortuneTotalPeriod',
    label: '总期数',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  }, {
    type: 'date',
    prop: 'payoutDate',
    label: '出账日（估）',
    placeholder: '请选择'
  }, {
    type: 'date',
    prop: 'actualPayoutDate',
    label: '出账日（实）',
    placeholder: '请选择'
  }, {
    type: 'input',
    prop: 'amount',
    label: '出账金额',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  }, {
    type: 'select',
    prop: 'currency',
    label: '出账币种',
    dictType: 'bx_currency_type'
  }, {
    type: 'select',
    prop: 'fortuneType',
    label: '出账项目',
    dictType: 'csf_fortune_type'
  }, {
    type: 'select',
    prop: 'brokerBizId',
    label: '转介人',
    api: '/insurance/base/api/userSaleExpand/page',
    keywordField: 'realName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'userSaleBizId',
    labelKey: 'realName',
    transform: (res) => {
      return res?.data.records || []
    }
  }, {
    type: 'select',
    prop: 'status',
    label: '出账状态',
    dictType: 'csf_expected_fortune_status'
  }
])
const handleConfirmAddPayRecord = async () => {
  const handleConfirmAddPayRecordparams = addPayRecordFormRef.value.getFormData()
  try {
    await addPayRecord([handleConfirmAddPayRecordparams])
    ElMessage.success('新增出账记录成功')
    addPayRecordDialogVisible.value = false
  } catch (error) {
    ElMessage.error(error.message)
  }
}



// 出账记录
const payRecordDialogTableData = ref([])
const payRecordDialogTableColumns = ref([])
const handleSelect = async (e, row) => {
  selectedRow.value = row
  if (e === 'payRecord') {
    payRecordDialogTableVisible.value = true
    loadPayRecordTableData(selectedRow.value.expectedFortuneBizId);
    payRecordDialogTableColumns.value = [
      { property: 'broker', label: '转介人', width: '100', },
      { property: 'fortuneName', label: '出账项目', width: '150' },
      { property: 'amount', label: '出账金额', width: '150' },
      { property: 'currency', label: '出账币种', width: '150' },
      { property: 'amount', label: '出账比例', width: '150' },
      { property: 'currentCommissionRatio', label: '待出账比例', width: '150' },
      { property: 'fortunePeriod', label: '佣金期数', width: '150' },
      { property: 'fortuneTotalPeriod', label: '总期数', width: '150' },
      { property: 'updaterId', label: '操作人', width: '150' },
      { property: 'updateTime', label: '操作时间', width: '150' }
    ]
  } else if (e === 'setStatus') {
    setPayRecordStatusDialogVisible.value = true
    setPayRecordStatusFormConfig.value = [
      {
        type: 'select',
        prop: 'status',
        label: '出账状态',
        dictType: 'csf_expected_fortune_status',
        defaultValue: selectedRow.value.status || ''
      }, {
        type: 'textarea',
        prop: 'statusDesc',
        label: '修改理由',
        defaultValue: selectedRow.value.statusDesc || ''
      },
    ]
  }

}


// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)
// 表格操作菜单
const dropdownItems = [
  { label: '出账记录', value: 'payRecord' },
  { label: '设置状态', value: 'setStatus' }
]

// 表格数据
const tableData = ref([])

// 统计信息
const statisticsData = ref({})

// 按钮事件处理
const handleAdd = () => {
  // ElMessage.info('点击新增按钮')
  addPayRecordDialogVisible.value = true
}

const handleImport = () => {
  ElMessage.info('点击导入按钮')
}

const handleExport = () => {
  ElMessage.info('点击导出按钮')
}

const handleReset = () => {
  // 重置搜索表单
  searchFormRef.value.resetForm()
  searchParams.value = {}
  console.log('表单已重置')
  // 重新加载数据
  loadTableData()
}

const handleQuery = async () => {
  loadTableData()
}

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

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

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadTableData()
}

// 加载表格数据
const loadTableData = async () => {
  const searchParams = searchFormRef.value.getFormData() || {}
  loading.value = true
  try {
    const params = {
      ...searchParams,
      payoutDateStart: searchParams.payoutDate?.[0] || undefined,
      payoutDateEnd: searchParams.payoutDate?.[1] || undefined,
      payoutDate: undefined,
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await expectedFortuneList(params)
    tableData.value = response.data.page.records
    pageTotal.value = response.data.page.total
    pageSize.value = response.data.page.size

    // 统计信息
    statisticsData.value = {
      totalExpectedAmount: response.data.statisticsVO.totalExpectedAmount,
      totalPaidAmount: response.data.statisticsVO.totalPaidAmount,
      totalUnpaidAmount: response.data.statisticsVO.totalUnpaidAmount,
      paidAmountRatio: response.data.statisticsVO.paidAmountRatio,
      totalPolicyCount: response.data.statisticsVO.totalPolicyCount,
      totalPremiumAmount: response.data.statisticsVO.totalPremiumAmount
    }

  } catch (error) {
    console.error('加载数据失败:', error)
    // ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 出账记录查询
const loadPayRecordTableData = async (expectedFortuneBizId) => {
  loading.value = true
  try {
    const params = {
      expectedFortuneBizId: expectedFortuneBizId
    }
    const response = await payRecordList(params)
    payRecordDialogTableData.value = response.data.records

  } catch (error) {
    console.error('加载数据失败:', error)
    // ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 设置出账状态确认
const handleConfirmSetPayRecordStatus = async () => {
  const formData = setPayRecordStatusFormRef.value.getFormData() || {}
  if (!formData.status) {
    ElMessage.error('请选择出账状态')
    return
  }
  if (!formData.statusDesc) {
    ElMessage.error('请输入修改理由')
    return
  }
  try {
    const params = {
      ...formData,
      fortuneBizIdList: [selectedRow.value.expectedFortuneBizId]
    }
    await updataPayrollStatus(params)
    ElMessage.success('设置出账状态成功')
    setPayRecordStatusDialogVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('设置出账状态失败:', error)
    ElMessage.error('设置出账状态失败')
  }
}


</script>

<style scoped lang="scss">
.page-search-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-actions {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}
</style>