<template>
  <div class="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"
          @selection-change="handleSelectionChange"
          height="400"
          border
          highlight-current-row
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column type="selection" width="40" />
          <!-- <el-table-column prop="fortuneBizType" label="应付单类型" width="120" sortable>
            <template #default="{ row }">
              {{ getFortuneBizTypeLabel(row.fortuneBizType) }}
            </template>
          </el-table-column> -->
          <el-table-column prop="policyNo" label="保单号" />
          <el-table-column prop="receiptStatus" label="回执状态">
            <template #default="{ row }">
              {{ getDictLabel('receipt_status', row.receiptStatus) }}
            </template>
          </el-table-column>
          <el-table-column prop="insurer" label="保险公司" />
          <el-table-column prop="policyHolder" label="保单持有人" />
          <el-table-column prop="createTime" label="创建时间">
            <template #default="{ row }">
              {{ row.createTime ? formatToDate(row.createTime) : '' }}
            </template>
          </el-table-column>

          <el-table-column prop="receiptDate" label="回执日期">
            <template #default="{ row }">
              {{ row.receiptDate ? formatToDate(row.receiptDate) : '' }}
            </template>
          </el-table-column>

          <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="receiptsDialogTitle"
      dialogWidth="80%"
      :openDialog="receiptsFlag"
      :showAction="true"
      :showClose="true"
      @close="receiptsFlag = false"
      @confirm="addReceipts"
    >
      <SearchForm
        ref="addCheckRecordFormRef"
        :config="addCheckRecordConfig"
        v-model="addCheckRecordFormModel"
      />
    </CommonDialog>
    <!-- 导入出账检核页面 -->
    <CommonDialog
      dialogTitle="新增出账检核"
      dialogWidth="80%"
      :openDialog="importCheckRecordFlag"
      :showAction="true"
      :showClose="true"
      @close="importCheckRecordFlag = false"
    >
      <FileUploadPreview
        :header-row="0"
        :required-fields="'amount,exchangeRate'"
        :use-chinese-header="true"
        :transform-submit-data="transformToBackend"
        @submit="onSubmit"
      />
    </CommonDialog>
    <!-- 设置本期出账金额 -->
    <CommonDialog
      dialogTitle="设置本期出账金额"
      dialogWidth="80%"
      :openDialog="setPayoutAmountDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="setPayoutAmountDialogFlag = false"
      @confirm="updatePayoutAmountapi"
    >
      <SearchForm
        ref="setPayoutAmountFormRef"
        :config="setPayoutAmountConfig"
        v-model="setPayoutAmountFormModel"
      />
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import CommonPage from '@/components/commonPage'
import CommonDialog from '@/components/commonDialog'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { ElMessage } from 'element-plus'
import { formatCurrency } from '@/utils/number'
// 接口
import {
  updatePayoutAmount,
} from '@/api/financial/commission'
import {
  getPolicyReceiptList,
  addPolicyReceipt,
  getPolicyReceipt,
  EditPolicyReceipt
} from '@/api/sign/policy'
import useUserStore from '@/store/modules/user'
import { loadDicts, getDictLabel } from '@/utils/useDict'
import { getToken } from '@/utils/auth'
const { proxy } = getCurrentInstance()
const userStore = useUserStore()
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)
const selectedRow = ref(null)
const searchFormRef = ref(null)
const searchParams = ref({})
const receiptsFlag = ref(false) //回执弹窗
const receiptsDialogTitle = ref('新增保单回执')
const searchConfig = ref([
  {
    type: 'input',
    prop: 'appointmentNo',
    label: '预约编号'
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'select',
    prop: 'receiptStatus',
    label: '回执状态',
    multiple: false,
    dictType: 'receipt_status'
  },
  {
    type: 'select',
    prop: 'insurer',
    label: '保险公司',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'queryContent',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: false,
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'abbreviation',
    transform: res => {
      console.log(res)
      return res?.data.records || []
    }
  },
  {
    type: 'input',
    prop: 'policyHolder',
    label: '保单持有人'
  }
])
// 表格操作菜单
const dropdownItems = [
  // { label: '新增回执', value: 'addReceipts' },
  { label: '更新回执', value: 'editRecord' }
  // { label: '查看记录', value: 'viewRecord' }
]
// 应收单类型
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 addCheckRecordFormModel = ref({})
const addCheckRecordFormRef = ref(null)
const addCheckRecordFormDialogFlag = ref(false)

const addCheckRecordConfig = [
  {
    type: 'select',
    prop: 'policyNo',
    label: '保单号码',
    api: '/csf/api/policy/list/page/vo',
    keywordField: 'policyNo',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'policyNo',
    labelKey: 'policyNo',
    onChangeExtraFields: {
      insured: 'insured', // 选择了保单号码，自动填充保单受保人
      policyHolder: 'policyHolder',
      insuranceCompany: 'insuranceCompany',
      productName: 'productName',
      currency: 'currency',
      paymentPremium: 'paymentPremium',
      paymentTerm: 'paymentTerm'
    },
    transform: res => {
      return res?.data.records || []
    },
    rules: [{ required: true, message: '请输入保单号码', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'insured',
    label: '保单受保人',
    disabled: true
  },
  {
    type: 'input',
    prop: 'policyHolder',
    label: '保单持有人姓名',
    disabled: true
  },
  {
    type: 'input',
    prop: 'insuranceCompany',
    label: '保险公司名称',
    disabled: true
  },
  {
    type: 'input',
    prop: 'productName',
    label: '保单产品名称',
    disabled: true
  },
  {
    type: 'input',
    prop: 'paymentTerm',
    label: '缴费年限',
    disabled: true
  },
  {
    type: 'input',
    prop: 'paymentPremium',
    label: '保单年缴保费',
    disabled: true
  },
  {
    type: 'select',
    prop: 'currency',
    label: '保单货币',
    dictType: 'bx_currency_type',
    disabled: true
  },

  {
    type: 'select',
    prop: 'receiptStatus',
    label: '回执状态',
    dictType: 'receipt_status',
    rules: [{ required: true, message: '请输入保单号码', trigger: 'blur' }]
  },
  {
    type: 'date',
    prop: 'receiptDate',
    label: '回执日期',
    placeholder: '请选择',
    maxDate: 'today',
    rules: [{ required: true, message: '请输入保单号码', trigger: 'blur' }]
  },
  {
    type: 'upload',
    prop: 'policyHolderSignatureList',
    label: '签名照片',
    uploadType: 'image',
    multiple: true,
    limit: 3,
    maxSize: 5 * 1024 * 1024, // 5MB
    accept: '.png,.jpg,.jpeg,.webp', // ✅ 改成扩展名！
    action: import.meta.env.VITE_APP_BASE_API + '/oss/api/oss/upload',
    headers: { Authorization: 'Bearer ' + getToken() },
    listType: 'picture-card',
    defaultValue: [],
    span: 24
  }
]

// 设置本期出账金额
const setPayoutAmountFormModel = ref({})
const setPayoutAmountFormRef = ref(null)
const setPayoutAmountDialogFlag = ref(false)
const setPayoutAmountConfig = [
  {
    type: 'input',
    prop: 'currentPaymentAmount',
    label: '出账金额',
    inputType: 'decimal',
    rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'currency',
    label: '出账币种',
    dictType: 'bx_currency_type'
  },
  {
    type: 'select',
    prop: 'status',
    label: '出账状态',
    dictType: 'csf_expected_fortune_status'
  }
]

// 统计信息
const statisticsData = ref({})
// 弹窗相关
const dialogFlag = ref(false)
// 加载表格数据
const getReceiptsDetail = async row => {
  try {
    const res = await getPolicyReceipt(row.policyReceiptBizId)
    addCheckRecordFormModel.value = {
      ...res.data,
      receiptDate: proxy.formatToDate(row.receiptDate),
      policyHolderSignatureList: res.data.policyHolderSignatureList.map(item => ({ url: item }))
    }
    receiptsFlag.value = true
    receiptsDialogTitle.value = '编辑保单回执'
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败')
    receiptsFlag.value = false
  }
}
// 按钮事件处理
const handleAdd = () => {
  console.log(addCheckRecordFormModel.value)

  receiptsFlag.value = true
}

const handleExport = () => {
  ElMessage.info('点击导出按钮')
}
const handleReset = () => {
  // 重置搜索表单
  searchFormRef.value.resetForm()
  console.log('表单已重置')
  currentPage.value = 1
  loadTableData()
}
const handleQuery = async () => {
  const params = searchFormRef.value.getFormData()
  console.log('params', params)

  loadTableData(params)
}
const visibleDefaultButtons = ref(['add', 'reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  {
    key: 'add',
    direction: 'left',
    label: '新增回执',
    click: handleAdd
  },

  // {
  //   key: 'export',
  //   direction: 'right',
  //   click: handleExport
  // },
  {
    key: 'reset',
    direction: 'right',
    click: handleReset
  },
  {
    key: 'query',
    direction: 'right',
    click: handleQuery
  }
])

// 加载表格数据
const loadTableData = async (searchParams = {}) => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams
    }
    const res = await getPolicyReceiptList(params)
    tableData.value = res.data.records || []

    pageTotal.value = res.data.total || 0
    pageSize.value = res.data.size || 0
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}
loadTableData()
// 分页事件
const handleSizeChange = val => {
  pageSize.value = val
  loadTableData()
}
const handleCurrentChange = val => {
  currentPage.value = val
  loadTableData()
}
// 表格数据
const tableData = ref([])

const handleSelect = (e, row) => {
  console.log('选中行:', e, row)
  selectedRow.value = row
  if (e === 'addReceipts') {
    receiptsFlag.value = true
    receiptsDialogTitle.value = '新增保单回执'
  } else if (e == 'editRecord') {
    getReceiptsDetail(row)
  }
}
const addReceipts = async () => {
  try {
    // ✅ 正确：await validate()，成功时返回表单数据
    const formData = await addCheckRecordFormRef.value.validate()

    console.log('新增保单回执:', formData)

    const params = {
      policyNo: formData.policyNo,
      receiptStatus: formData.receiptStatus,
      receiptDate: proxy.formatToDateTime(formData.receiptDate),
      policyHolderSignatureList:
        formData.policyHolderSignatureList.length > 0
          ? formData.policyHolderSignatureList.map(item => item.url)
          : []
    }

    let res = {}
    if (formData.policyReceiptBizId) {
      params.policyReceiptBizId = formData.policyReceiptBizId
      res = await EditPolicyReceipt(params)
    } else {
      res = await addPolicyReceipt(params)
    }
    if (res.code === 200) {
      ElMessage.success(`${receiptsDialogTitle.value}成功`)
      receiptsFlag.value = false // ✅ 校验 & 提交成功后才关闭
      addCheckRecordFormRef.value.resetForm()
      loadTableData()
    } else {
      ElMessage.error(res.msg || `${receiptsDialogTitle.value}失败`)
    }
  } catch (error) {
    // ❌ 校验失败或提交异常都会进入这里
    console.error('操作失败:', error)
    // ⚠️ 不设置 receiptsFlag = false，弹窗保持打开
    ElMessage.warning('请检查表单填写是否正确')
    // 注意：Element Plus 的 validate 失败时，错误信息已自动显示在表单项下方
  }
}

// 设置本期出账金额
const updatePayoutAmountapi = async data => {
  console.log('设置本期出账金额:', data)
  const params = {
    ...setPayoutAmountFormRef.value.getFormData(),
    fortuneBizId: selectedRow.value.fortuneBizId
  }
  try {
    const res = await updatePayoutAmount(params)
    if (res.code === 200) {
      ElMessage.success('设置本期出账金额成功')
      loadTableData()
    } else {
      ElMessage.error(res.msg || '设置本期出账金额失败')
    }
  } catch (error) {
    console.error('设置本期出账金额失败:', error)
    ElMessage.error(error.message || '设置本期出账金额失败')
  }
}
const updatePayRollStatusDisable = ref(true)
const multipleSelection = ref([])
const handleSelectionChange = val => {
  multipleSelection.value = val
  console.log('全选:', val)
  // 完成检核按钮是否禁用
  updatePayRollStatusDisable.value = val.length === 0
}

import FileUploadPreview from '@/components/fileUploadPreview/fileUploadPreview.vue'

const importCheckRecordFlag = ref(false)

const onSubmit = data => {
  console.log('提交给后端的数据:', data)
  // 调用保存 API
}

// 获取入账状态,字典值转化方法
onMounted(async () => {
  try {
    await loadDicts(['receipt_status'])
  } catch (error) {
    console.error('字典加载失败', error)
  } finally {
    loading.value = false
  }
})
watch(receiptsFlag, newVal => {
  if (!newVal) {
    addCheckRecordFormModel.value = {}
    receiptsDialogTitle.value = ''
  }
})
</script>

<style scoped>
.tableOptionContainer {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
