<template>
  <div class="app-container">
    <el-row style="margin-bottom: 20px">
      <el-col style="display: flex; justify-content: space-between">
        <div>
          <el-button type="primary" plain icon="Refresh" @click="updateSpecies('update')"
            >更新规格</el-button
          >
        </div>
      </el-col>
    </el-row>
    <el-table
      height="70%"
      :data="tableData"
      :span-method="objectSpanMethod"
      border
      style="width: 100%; margin-top: 20px"
      row-key="rowKey"
    >
      <!-- 动态生成所有列 -->
      <template v-for="column in tableColumns" :key="column.prop">
        <el-table-column :prop="column.prop" :label="column.label" />
      </template>

      <!-- 固定操作列 -->
      <el-table-column
        label="操作"
        :width="tableData.length > 0 ? 180 : 0"
        align="center"
        fixed="right"
      >
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleCommissionSetting(scope.row)">
            佣金设置
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getSpeciesList"
      style="margin-top: 10px"
    />
    <!-- 佣金设置 -->
    <el-dialog
      title="佣金设置"
      v-model="showCommisionSetting"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
    >
      <!-- 表格数据 -->
      <el-table
        v-loading="settingLoading"
        :data="settingList"
        border
        ref="settingTableRef"
        height="75%"
      >
        <el-table-column
          label="序号 "
          width="55"
          align="center"
          type="index"
          fixed="left"
        ></el-table-column>
        <el-table-column label="费用名称" prop="expenseName" width="150" fixed="left">
          <template #header>
            <span class="required-label">费用名称</span>
          </template>
          <template #default="scope">
            <el-select v-model="scope.row.expenseName" placeholder="请选择">
              <el-option
                v-for="item in commission_cost_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="佣金年限(起)" prop="startPeriod" width="120">
          <template #header>
            <span class="required-label">佣金年限(起)</span>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.startPeriod"
              type="number"
              placeholder="请输入"
              :min="1"
              clearable
              @input="handleNumberInput(scope.row, 'startPeriod', 'positive')"
              @blur="handlePeriodBlur(scope.row, scope.$index, 'startPeriod')"
            />
          </template>
        </el-table-column>
        <el-table-column label="佣金年限(止)" prop="endPeriod" width="120">
          <template #header>
            <span class="required-label">佣金年限(止)</span>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.endPeriod"
              type="number"
              :min="1"
              placeholder="请输入"
              clearable
              @input="handleNumberInput(scope.row, 'endPeriod', 'positive')"
              @blur="handlePeriodBlur(scope.row, scope.$index, 'endPeriod')"
            />
          </template>
        </el-table-column>

        <el-table-column label="佣金率(%)" prop="commissionRate" width="120">
          <template #header>
            <span class="required-label">佣金率(%)</span>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.commissionRate"
              type="number"
              :min="0"
              placeholder="请输入"
              clearable
              @input="handleNumberInput(scope.row, 'commissionRate', 'non-negative')"
            />
          </template>
        </el-table-column>
        <el-table-column label="折标系数(%)" prop="discountRatio" width="120">
          <template #header>
            <span class="required-label">折标系数(%)</span>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.discountRatio"
              type="number"
              :min="0"
              placeholder="请输入"
              clearable
              @input="handleNumberInput(scope.row, 'discountRatio', 'non-negative')"
            />
          </template>
        </el-table-column>
        <el-table-column label="生效日期(起)" prop="effectiveStart" width="150">
          <template #header>
            <span class="required-label">生效日期(起)</span>
          </template>
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.effectiveStart"
              style="width: 100%"
              type="date"
              placeholder="请选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleStartDateChange(scope.row, scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="生效日期(止)" prop="effectiveEnd" width="150">
          <template #header>
            <span class="required-label">生效日期(止)</span>
          </template>
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.effectiveEnd"
              style="width: 100%"
              type="date"
              placeholder="请选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleEndDateChange(scope.row, scope.$index)"
            />
          </template>
        </el-table-column>

        <el-table-column label="是否受汇率影响" prop="isExchangeRate" width="150">
          <template #header>
            <span class="required-label">是否受汇率影响</span>
          </template>
          <template #default="scope">
            <el-select
              v-model="scope.row.isExchangeRate"
              style="width: 100%"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in sys_no_yes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="结算币种" prop="currency" width="120">
          <template #header>
            <span class="required-label">结算币种</span>
          </template>
          <template #default="scope">
            <el-select
              v-model="scope.row.currency"
              style="width: 100%"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in bx_currency_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <!-- <el-table-column label="是否直签" prop="isDirectSign" width="150">
          <template #header>
            <span class="required-label">是否直签</span>
          </template>
          <template #default="scope">
            <el-select
              v-model="scope.row.isDirectSign"
              style="width: 100%"
              placeholder="请选择"
              clearable
              @change="scope.row.reconciliationCompanyName = ''"
            >
              <el-option
                v-for="item in sys_no_yes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column> -->
        <el-table-column
          label="对账公司"
          prop="reconciliationCompanyName"
          align="center"
          width="150"
        >
          <template #header>
            <span class="required-label">对账公司</span>
          </template>
          <template #default="scope">
            <el-select
              @change="selectChange(scope.row, 'reconciliationCompanyName')"
              v-model="scope.row.reconciliationCompanyName"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词搜索"
              :remote-method="
                query =>
                  searchSelectList(query, 'reconciliationCompanyName', scope.row.isDirectSign)
              "
              :loading="searchLoadingStates['reconciliationCompanyName']"
            >
              <el-option
                v-for="item in searchOptions['reconciliationCompanyName'] || []"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="销售组织" prop="salesOrgName" align="center" width="150">
          <template #header>
            <span class="required-label">销售组织</span>
          </template>
          <template #default="scope">
            <el-select
              v-model="scope.row.salesOrgName"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词搜索"
              :remote-method="query => searchSelectList(query, 'salesOrgName')"
              :loading="searchLoadingStates['salesOrgName']"
            >
              <el-option
                v-for="item in searchOptions['salesOrgName'] || []"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="120">
          <template #header>
            <span class="required-label">状态</span>
          </template>
          <!-- <template #default="scope">
            <el-select
              v-model="scope.row.status"
              style="width: 100%"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in sys_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template> -->
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="switchChange(scope.row)"
            />
            <span style="margin-left: 8px">
              {{ scope.row.status === '1' ? '启用' : '禁用' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.remark" type="textarea" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="最近一次操作人" prop="updaterName" width="120" />
        <el-table-column label="最近一次操作时间" prop="updateTime" width="160">
          <template #default="scope">
            <span>{{ scope.row.updateTime ? parseTime(scope.row.updateTime) : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <div class="btnCon">
              <el-button
                v-if="scope.$index == settingList.length - 1"
                @click="handleAddCommission(scope.row)"
                text
                size="small"
                type="primary"
                >新增</el-button
              >

              <el-button
                text
                size="small"
                type="danger"
                @click="handleDeleteCommission(scope.row, scope.$index)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeSetting">关闭</el-button>
          <el-button type="primary" @click="submitSetting">提 交</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="佣金设置错误提示" v-model="errorTip" width="500px" append-to-body>
      <div style="margin-bottom: 10px" v-for="(item, index) in settingErrorTip" :key="index">
        {{ item }}
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="errorTip = false">去修改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="SendInfo">
import { cloneDeep } from 'lodash-es'
import {
  comeCommissionRatio,
  comeCommissionList,
  comeExpectedSpecies,
  comeBatchSave,
  deleteComeCommission,
  changeComeStatus
} from '@/api/product/index'
import { getAllCompanys, getReconciliationCompany, getInsuranceCompany } from '@/api/common'
import { ref, watch } from 'vue'

const props = defineProps({
  // 类型，是新增还是编辑,
  activeName: {
    type: String,
    default: ''
  }
})
const route = useRoute()
const { proxy } = getCurrentInstance()
const loading = ref(true)
const settingLoading = ref(true)
const total = ref(0) //规格表格的总条数
const settingTotal = ref(0) //规格表格的总条数
const showCommisionSetting = ref(false) //佣金设置弹窗开关
const errorTip = ref(false) //佣金设置弹窗开关
const settingList = ref([]) //佣金设置表格数据
const currentSettingRow = ref([]) //当前选中的佣金设置行
const settingErrorTip = ref([]) //提交佣金错误提示信息
const searchOptions = ref({}) // 存储不同key对应的选项
const searchLoadingStates = ref({}) // 存储不同key对应的加载状态
const data = reactive({
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    productLaunchBizId: route.query.productLaunchBizId
  },
  settingQueryParams: {
    pageNo: 1,
    pageSize: 9999
  }
})

const { queryParams, settingQueryParams } = toRefs(data)
const { bx_currency_type, commission_cost_type, sys_no_yes, sys_status } = proxy.useDict(
  'bx_currency_type',
  'commission_cost_type',
  'sys_no_yes',
  'sys_status'
)
const selectChange = (row, key) => {
  if (key == 'reconciliationCompanyName') {
    row.reconciliationCompany = searchOptions.value['reconciliationCompanyName'].find(
      item => item.value == row.reconciliationCompanyName
    ).value
    row.reconciliationCompanyName = searchOptions.value['reconciliationCompanyName'].find(
      item => item.value == row.reconciliationCompanyName
    ).label
  }
}
const switchChange = row => {
  if (!row.expectedCommissionRatioBizId) {
    return
  }
  try {
    changeComeStatus({
      expectedCommissionRatioBizId: row.expectedCommissionRatioBizId,
      status: Number(row.status)
    }).then(response => {
      if (response.code === 200) {
        proxy.$modal.msgSuccess('状态修改成功')
      }
    })
  } catch (error) {
    row.status = row.status === '1' ? '0' : '1'
  }
}
// 搜索方法
const searchSelectList = async (query, fieldKey, isDirectSign = 0) => {
  // 设置该字段的加载状态
  searchLoadingStates.value[fieldKey] = true
  try {
    if (fieldKey === 'reconciliationCompanyName') {
      if (isDirectSign == 1) {
        getInsuranceCompany({
          queryContent: query.trim(),
          pageNo: 1,
          pageSize: 10
        }).then(response => {
          response.data.records = response.data.records.map(item => {
            return {
              ...item,
              label: item.fullName,
              value: item.insuranceCompanyBizId
            }
          })
          searchOptions.value[fieldKey] = response.data.records
        })
        return
      } else {
        getReconciliationCompany({
          name: query.trim(),
          pageNo: 1,
          pageSize: 10
        }).then(response => {
          response.data.records = response.data.records.map(item => {
            return {
              ...item,
              label: item.name,
              value: item.reconciliationCompanyBizId
            }
          })
          searchOptions.value[fieldKey] = response.data.records
        })
      }

      return
    }

    // 根据不同的字段key调用不同的API
    if (fieldKey === 'salesOrgName') {
      const params = {
        deptName: query.trim(),
        pageNo: 1,
        pageSize: 10
      }
      getAllCompanys(params).then(response => {
        response.data.records = response.data.records.map(item => {
          return {
            ...item,
            label: item.deptName,
            value: item.deptBizId
          }
        })
        searchOptions.value[fieldKey] = response.data.records
      })
    }
  } catch (error) {
    console.error(`${fieldKey} 搜索失败`, error)
    searchOptions.value[fieldKey] = []
  } finally {
    searchLoadingStates.value[fieldKey] = false
  }
}
const handleDeleteCommission = (row, index) => {
  if (settingList.value.length === 1) {
    proxy.$modal.msgError('至少保留一条佣金设置数据')
    return
  }
  proxy.$modal
    .confirm(`是否确认删除第${index + 1}行数据?`)
    .then(function () {
      if (row.expectedCommissionRatioBizId) {
        deleteComeCommission(row.expectedCommissionRatioBizId).then(response => {
          if (response.code === 200) {
            settingList.value.splice(index, 1)
          } else {
            proxy.$modal.msgError(response.msg)
          }
        })
      } else {
        settingList.value.splice(index, 1)
      }
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
const handleNumberInput = (row, field, type = 'positive') => {
  const value = row[field]

  if (value === null || value === undefined || value === '') return

  let numValue = Number(value)

  if (isNaN(numValue)) {
    row[field] = null
    return
  }

  if (type === 'positive') {
    // 正整数：移除负号和小数部分
    if (numValue <= 0) {
      row[field] = null
      return
    }
    // 取整数部分
    row[field] = Math.floor(Math.abs(numValue))
  } else if (type === 'non-negative') {
    // 非负数：允许0及以上，不允许负数
    if (numValue < 0) {
      row[field] = 0
    }
  }
}
// 处理开始日期变化
const handleStartDateChange = (row, index) => {
  if (row.effectiveStart && row.effectiveEnd) {
    const start = new Date(row.effectiveStart)
    const end = new Date(row.effectiveEnd)

    if (start > end) {
      proxy.$modal.msgError(
        `第${index + 1}行：生效日期(起)不能晚于生效日期(止),请重新选择生效日期(起)`
      )
      // 清空结束日期，让用户重新选择
      setTimeout(() => {
        row.effectiveStart = ''
      }, 0)
    }
  }
}

// 处理结束日期变化
const handleEndDateChange = (row, index) => {
  console.log('时间', row)

  if (row.effectiveStart && row.effectiveEnd) {
    const start = new Date(row.effectiveStart)
    const end = new Date(row.effectiveEnd)

    if (end < start) {
      proxy.$modal.msgError(
        `第${index + 1}行：生效日期(止)不能早于生效日期(起),请重新选择生效日期(止)`
      )
      // 清空开始日期，让用户重新选择
      setTimeout(() => {
        row.effectiveEnd = ''
      }, 0)
    }
  }
}
const handlePeriodBlur = (row, index, key) => {
  if (row.startPeriod && row.endPeriod && row.startPeriod > row.endPeriod) {
    proxy.$modal.msgError(`第${index + 1}行：佣金开始年限不能大于佣金结束年限,请重新填写`)
    row[key] = ''
    row.unadd = true
  } else {
    row.unadd = false
  }
  console.log('年限', row)
}
const handleAddCommission = row => {
  let newRow = cloneDeep(row)
  let obj = {}
  // 复制当前条的数据
  for (const key in newRow) {
    if (key !== 'startPeriod' && key !== 'endPeriod' && key !== 'commissionRate') {
      obj[key] = newRow[key]
    } else {
      obj[key] = ''
    }
  }
  if (!row.unadd) {
    settingList.value.push(obj)
  }
  console.log('====================================')
  console.log('新增', settingList.value)
  console.log('====================================')
}
const closeSetting = () => {
  showCommisionSetting.value = false
  settingQueryParams.value = {
    pageNo: 1,
    pageSize: 9999
  }
}
// 批量提交佣金设置
const submitSetting = async () => {
  // 校验表格数据
  const validationResult = validateTableData()
  if (!validationResult.valid) {
    proxy.$modal.msgError(validationResult.message)
    return
  }

  let saveTable = cloneDeep(settingList.value)
  saveTable.forEach(item => {
    if (item.reconciliationCompanyName) {
      searchOptions.value['reconciliationCompanyName'].forEach(item1 => {
        if (item.reconciliationCompanyName == item1.value) {
          item.reconciliationCompanyName = item1.label
          item.reconciliationCompany = item1.value
        }
      })
    }
    if (item.salesOrgName) {
      searchOptions.value['salesOrgName'].forEach(item1 => {
        if (item.salesOrgName == item1.value) {
          item.salesOrgName = item1.label
          item.salesOrg = item1.value
        }
      })
    }
  })

  // return
  try {
    comeBatchSave({
      expectedSpeciesBizId: currentSettingRow.value.expectedSpeciesBizId,
      ratioBatchSaveDtoList: saveTable
    }).then(response => {
      console.log('response', response)

      if (response.code === 200) {
        showCommisionSetting.value = false
        proxy.$modal.msgSuccess('提交成功')
      } else if (response.code === 1004) {
        if (response.msg) {
          settingErrorTip.value = response.msg.split('\n').filter(item => item !== '')
        }
        errorTip.value = true
      }
    })
  } catch (error) {
    console.log('错误了', error)
  }
}

// 表格数据校验函数
const validateTableData = () => {
  const errors = []
  const requiredFields = [
    { key: 'expenseName', label: '费用名称' },
    { key: 'startPeriod', label: '佣金年限(起)' },
    { key: 'endPeriod', label: '佣金年限(止)' },
    { key: 'commissionRate', label: '佣金率(%)' },
    { key: 'discountRatio', label: '折标系数(%)' },
    { key: 'effectiveStart', label: '生效日期(起)' },
    { key: 'effectiveEnd', label: '生效日期(止)' },
    { key: 'isExchangeRate', label: '是否受汇率影响' },
    { key: 'currency', label: '结算币种' },
    { key: 'salesOrgName', label: '销售组织' },
    { key: 'reconciliationCompanyName', label: '对账公司' }
  ]

  settingList.value.forEach((row, index) => {
    requiredFields.forEach(field => {
      const value = row[field.key]
      let isValid = true

      if (Array.isArray(value)) {
        isValid = value.length > 0
      } else {
        isValid = value !== null && value !== undefined && value !== ''
      }

      if (!isValid) {
        errors.push({
          rowIndex: index,
          field: field.key,
          label: field.label,
          rowNumber: index + 1
        })
      }
    })
  })

  if (errors.length === 0) {
    return { valid: true }
  }

  // 生成友好的错误提示信息
  const errorMessages = errors
    .slice(0, 3)
    .map(error => `第${error.rowNumber}行【${error.label}】未填写`)

  let message = errorMessages.join('；')
  if (errors.length > 3) {
    message += `等，共${errors.length}处必填项未填写`
  }

  return {
    valid: false,
    errors,
    message
  }
}

/** 获得佣金设置数据 */
function getSettingList() {
  settingLoading.value = true
  let obj = {
    expenseName: '',
    startPeriod: '',
    endPeriod: '',
    commissionRate: '',
    discountRatio: '100',
    effectiveStart: '',
    effectiveEnd: '',
    isExchangeRate: '1',
    currency: 'HKD',
    status: '1',
    remark: '',
    salesOrgName: '',
    reconciliationCompanyName: ''
  }
  settingList.value = []
  settingQueryParams.value.expectedSpeciesBizId = currentSettingRow.value.expectedSpeciesBizId
  comeCommissionRatio(settingQueryParams.value).then(response => {
    if (response.code === 200) {
      if (response.data.records.length > 0) {
        settingList.value = response.data.records
        settingList.value.forEach(row => {
          row.status = row.status === 1 ? '1' : row.status === 0 ? '0' : ''
        })
      } else {
        settingList.value.push(obj)
      }
      settingTotal.value = response.data.total
      settingLoading.value = false
      showCommisionSetting.value = true
    } else {
      settingLoading.value = false
      proxy.$modal.msgError(response.msg)
    }
  })
}
// 原始数据
const originalData = ref([])

// 表格列配置
const tableColumns = ref([])

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

// 合并行配置，存储每列需要合并的行数
const spanConfig = ref({})

// 从数据中提取所有可能的列
const extractColumnsFromData = data => {
  const columnSet = new Map()

  data.forEach(item => {
    try {
      if (item.apiSpeciesSettingDtoList && item.apiSpeciesSettingDtoList.length > 0) {
        item.apiSpeciesSettingDtoList.forEach(species => {
          if (!columnSet.has(species.typeCode)) {
            columnSet.set(species.typeCode, {
              prop: species.typeCode,
              label: species.typeName,
              width: species.typeName.length * 15 + 30,
              align: 'center',
              sortable: false
            })
          }
        })
      }
    } catch (e) {
      console.log('计算列失败', e)
    }
  })

  // 将 Map 转换为数组并按 typeCode 排序（可选）
  return Array.from(columnSet.values())
}

// 处理数据，生成表格需要的格式
const processTableData = () => {
  if (!originalData.value || originalData.value.length === 0) {
    tableData.value = []
    spanConfig.value = {}
    return
  }

  // 1. 提取所有列
  const columns = extractColumnsFromData(originalData.value)
  tableColumns.value = columns

  // 2. 转换数据格式
  const processedData = []

  originalData.value.forEach((item, index) => {
    const rowData = {
      rowKey: `${item.id}_${index}`, // 生成唯一 rowKey
      id: item.id, // 保留原始ID
      rawData: item // 保留原始数据
    }

    // 填充所有列的值
    columns.forEach(column => {
      try {
        if (item.apiSpeciesSettingDtoList && item.apiSpeciesSettingDtoList.length > 0) {
          const matchedSpecies = item.apiSpeciesSettingDtoList.find(s => s.typeCode === column.prop)
          rowData[column.prop] = matchedSpecies ? matchedSpecies.value : ''
        } else {
          rowData[column.prop] = ''
        }
      } catch (e) {
        console.log('填充所有列的值失败', e)
      }
    })

    processedData.push(rowData)
  })

  // 3. 计算合并配置
  calculateSpanConfig(processedData, columns)

  tableData.value = processedData
}

// 计算合并配置
const calculateSpanConfig = (data, columns) => {
  const config = {}

  // 为每一列计算合并配置
  columns.forEach((column, columnIndex) => {
    config[column.prop] = []

    let pos = 0
    while (pos < data.length) {
      const currentValue = data[pos][column.prop]
      let rowspan = 1

      // 向后查找相同值的行
      for (let i = pos + 1; i < data.length; i++) {
        // 只有当该列之前的所有列的值都相同时才合并
        let shouldMerge = true
        for (let j = 0; j < columnIndex; j++) {
          const prevColumn = columns[j]
          if (data[pos][prevColumn.prop] !== data[i][prevColumn.prop]) {
            shouldMerge = false
            break
          }
        }

        if (shouldMerge && data[i][column.prop] === currentValue) {
          rowspan++
        } else {
          break
        }
      }

      // 记录合并配置
      config[column.prop][pos] = rowspan

      // 跳过已经计算的行
      pos += rowspan
    }

    // 填充剩余的配置为0（不合并）
    for (let i = 0; i < data.length; i++) {
      if (!config[column.prop][i]) {
        config[column.prop][i] = 0
      }
    }
  })

  spanConfig.value = config
}

// 合并单元格的方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 最后一列是操作列，不合并
  if (columnIndex === tableColumns.value.length) {
    return {
      rowspan: 1,
      colspan: 1
    }
  }

  const columnProp = tableColumns.value[columnIndex].prop
  const rowspan = spanConfig.value[columnProp]?.[rowIndex] || 0

  if (rowspan > 0) {
    return {
      rowspan: rowspan,
      colspan: 1
    }
  } else {
    return {
      rowspan: 0,
      colspan: 0
    }
  }
}

// 佣金设置操作
const handleCommissionSetting = row => {
  currentSettingRow.value = row.rawData
  console.log(' currentSettingRow.value', currentSettingRow.value)

  getSettingList()
}

/** 获得来佣规格数据 */
function getSpeciesList() {
  loading.value = true
  comeCommissionList(queryParams.value).then(response => {
    if (response.code === 200) {
      originalData.value = response.data.records
      total.value = response.data.total
      loading.value = false
      if (originalData.value.length == 0) {
        // 如果来佣表没有规格数据，那么同步产品规格数据
        updateSpecies()
        // proxy.$modal.msgError('该商品暂无规格数据，请先更新规格数据')
      } else {
        let codeArr = []
        // 自定义没有typeCode影响表格得展示
        originalData.value[0].apiSpeciesSettingDtoList.forEach((item, index) => {
          if (item.isCustomize == '1') {
            item.typeCode = `custom${Date.now() + Math.floor(Math.random() * 1000)}`
            codeArr.push({ index: index, code: item.typeCode })
          }
        })
        originalData.value.forEach((item, oIndex) => {
          item.apiSpeciesSettingDtoList.forEach((species, sIndex) => {
            if (codeArr.length > 0) {
              codeArr.forEach(codeItem => {
                if (codeItem.index == sIndex) {
                  species.typeCode = codeItem.code
                }
              })
            }
          })
        })
      }
      // 计算表格
      processTableData()
      searchSelectList('', 'reconciliationCompanyName')
      searchSelectList('', 'salesOrgName')
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}
/** 更新产品规格数据 */
function updateSpecies(type) {
  loading.value = true
  if (type == 'update') {
    proxy.$modal
      .confirm('确认更新来佣管理-规格数据吗,此操作会重置佣金数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        // 用户点击了确定按钮，执行更新操作
        updateSpecies()
      })
      .catch(() => {
        // 用户点击了取消按钮，不执行任何操作
      })
  } else {
    comeExpectedSpecies({ productLaunchBizId: route.query.productLaunchBizId }).then(response => {
      if (response.code === 200) {
        if (type == 'update') {
          proxy.$modal.msgSuccess('来佣管理-规格更新成功')
        } else {
          console.log('初始化规格数据')
        }
        getSpeciesList()
      } else {
        proxy.$modal.msgError(response.msg)
      }
    })
  }
}

//========多选下拉框悬停效果结束=========

watch(
  () => props.activeName,
  newVal => {
    if (newVal == 'comeCommission') {
      getSpeciesList()
    }
  }
)
</script>
<style lang="scss" scoped>
.required-label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.btnCon {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 错误行样式 */
.error-row {
  background-color: #fff2f0 !important;
  animation: highlight 0.6s ease-in-out;
}

/* 错误字段高亮 */
.error-field :deep(.el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c !important;
}

.error-field :deep(.el-input__inner) {
  color: #f56c6c;
}

.error-field :deep(.el-select__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c !important;
}

/* 闪烁动画吸引用户注意力 */
@keyframes highlight {
  0%,
  50% {
    background-color: #fff2f0;
  }

  25%,
  75% {
    background-color: #ffeaea;
  }

  100% {
    background-color: #fff2f0;
  }
}

/* 错误提示消息样式 */
.validation-message-box {
  :deep(.el-message-box__content) {
    max-height: 400px;
    overflow-y: auto;
  }
}
</style>
