<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    :width="'1000px'"
    append-to-body
    destroy-on-close
    @closed="handleCancel"
  >
    <div class="flex flex-col">
      <div class="w-full">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
        >
          <div v-if="props.selectedRows.length > 1" class="mb-4 text-gray-500">
            已选择 {{ props.selectedRows.length }} 条记录进行批量排期
          </div>

          <el-form-item label="检验性质" prop="checkType" labelWidth="80px">
            <el-radio-group v-model="formData.checkType">
              <el-radio
                v-for="(label, value) in PressureBoilerCheckTypeMap"
                :key="value"
                :value="value"
              >
                {{ label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 内部检验配置 -->
          <div class="plan-section" v-if="formData.checkType == PressureBoilerCheckType.IN">
            <div class="section-title">
              <span>内部检验</span>
              <span class="section-info">
                待检设备数量: {{ inEquipCount }} &nbsp;&nbsp; 最近临期时间: {{ inLatestTime }}
              </span>
            </div>
            <el-form-item label="内检日期" prop="inDate">
              <el-date-picker
                v-model="formData.inDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
                :disabled="inEquipCount === 0"
                class="!w-240px"
              />
              <el-checkbox
                v-model="formData.inIsOrderConfirm"
                class="ml-4"
                :disabled="inEquipCount === 0"
              >
                由前台约检确认
              </el-checkbox>
            </el-form-item>

            <el-form-item label="检验员" prop="inTeamList" v-if="inEquipCount > 0">
              <div class="checker-select-container">
                <div class="checker-list">
                  <template v-if="inProcessedDeptData.length">
                    <div v-for="dept in inProcessedDeptData" :key="dept.dept.id"
                         class="dept-section">
                      <div v-for="team in dept.teamList" :key="team.id || team.deptGroupId"
                           class="group-section">
                        <div class="group-content">
                          <template v-for="subTeam in team.memberList"
                                    :key="subTeam.id || subTeam.deptGroupId">
                            <div class="group-members">
                              <div class="label">
                                <el-checkbox
                                  v-model="subTeam.checked"
                                  @change="(val: boolean) => handleSubTeamCheckChange(val, subTeam, 'in')"
                                >
                                  {{ subTeam.name }}
                                </el-checkbox>
                              </div>
                              <div class="members-list">
                                <el-checkbox-group
                                  v-model="inSelectedCheckerIds"
                                  @change="handleInMemberChange"
                                >
                                  <el-checkbox
                                    v-for="member in subTeam.memberList"
                                    :key="member.memberId"
                                    :value="subTeam.id + ':' + member.memberId"
                                  >
                                    <span v-if="member.memberId === member.leaderId"
                                          class="leader-tag">组</span>
                                    {{ member.member?.nickname }}
                                  </el-checkbox>
                                </el-checkbox-group>
                              </div>
                            </div>
                          </template>
                        </div>
                      </div>
                    </div>
                  </template>
                  <el-empty v-else description="暂无检验员数据"/>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="收费形式" prop="inChargeType" v-if="inEquipCount > 0">
              <div class="flex items-center gap-4">
                <el-select v-model="formData.inChargeType" placeholder="请选择收费形式"
                           class="!w-120px">
                  <el-option label="非合同收费" value="1"/>
                  <el-option label="合同收费" value="2"/>
                </el-select>
                <span class="text-gray-600">是否免征:</span>
                <el-select v-model="formData.inIsExempt" placeholder="请选择是否免征"
                           class="!w-60px" @change="handleInExemptChange">
                  <el-option label="否" value="0"/>
                  <el-option label="是" value="1"/>
                </el-select>
                <span class="text-gray-600">应收法定金额: {{ formData.inShouldAmount }}</span>
                <span class="text-gray-600">服务收费金额: {{ formData.inServiceAmount }}</span>
                <span class="text-gray-600">免征费用: {{ formData.inReduceFee }}</span>
              </div>
            </el-form-item>
          </div>

          <!-- 外部检验配置 -->
          <div class="plan-section" v-if="formData.checkType == PressureBoilerCheckType.OUT">
            <div class="section-title">
              <span>外部检验</span>
              <span class="section-info">
                待检设备数量: {{ outEquipCount }} &nbsp;&nbsp; 最近临期时间: {{ outLatestTime }}
              </span>
            </div>
            <el-form-item label="外检日期" prop="outDate">
              <el-date-picker
                v-model="formData.outDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
                :disabled="outEquipCount === 0"
                class="!w-240px"
              />
              <el-checkbox
                v-model="formData.outIsOrderConfirm"
                class="ml-4"
                :disabled="outEquipCount === 0"
              >
                由前台约检确认
              </el-checkbox>
            </el-form-item>

            <el-form-item label="检验员" prop="outTeamList" v-if="outEquipCount > 0">
              <div class="checker-select-container">
                <div class="checker-list">
                  <template v-if="outProcessedDeptData.length">
                    <div v-for="dept in outProcessedDeptData" :key="dept.dept.id"
                         class="dept-section">
                      <div v-for="team in dept.teamList" :key="team.id || team.deptGroupId"
                           class="group-section">
                        <div class="group-content">
                          <template v-for="subTeam in team.memberList"
                                    :key="subTeam.id || subTeam.deptGroupId">
                            <div class="group-members">
                              <div class="label">
                                <el-checkbox
                                  v-model="subTeam.checked"
                                  @change="(val: boolean) => handleSubTeamCheckChange(val, subTeam, 'out')"
                                >
                                  {{ subTeam.name }}
                                </el-checkbox>
                              </div>
                              <div class="members-list">
                                <el-checkbox-group
                                  v-model="outSelectedCheckerIds"
                                  @change="handleOutMemberChange"
                                >
                                  <el-checkbox
                                    v-for="member in subTeam.memberList"
                                    :key="member.memberId"
                                    :value="subTeam.id + ':' + member.memberId"
                                  >
                                    <span v-if="member.memberId === member.leaderId"
                                          class="leader-tag">组</span>
                                    {{ member.member?.nickname }}
                                  </el-checkbox>
                                </el-checkbox-group>
                              </div>
                            </div>
                          </template>
                        </div>
                      </div>
                    </div>
                  </template>
                  <el-empty v-else description="暂无检验员数据"/>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="收费形式" prop="outChargeType" v-if="outEquipCount > 0">
              <div class="flex items-center gap-4">
                <el-select v-model="formData.outChargeType" placeholder="请选择收费形式"
                           class="!w-120px">
                  <el-option label="非合同收费" value="1"/>
                  <el-option label="合同收费" value="2"/>
                </el-select>
                <span class="text-gray-600">是否免征:</span>
                <el-select v-model="formData.outIsExempt" placeholder="请选择是否免征"
                           class="!w-60px" @change="handleOutExemptChange">
                  <el-option label="否" value="0"/>
                  <el-option label="是" value="1"/>
                </el-select>
                <span class="text-gray-600">应收法定金额: {{ formData.outShouldAmount }}</span>
                <span class="text-gray-600">服务收费金额: {{ formData.outServiceAmount }}</span>
                <span class="text-gray-600">免征费用: {{ formData.outReduceFee }}</span>
              </div>
            </el-form-item>
          </div>

          <!-- 耐压检验配置 -->
          <div class="plan-section" v-if="formData.checkType == PressureBoilerCheckType.PRESSURE">
            <div class="section-title">
              <span>耐压检验</span>
              <span class="section-info">
                待检设备数量: {{ preEquipCount }} &nbsp;&nbsp; 最近临期时间: {{ preLatestTime }}
              </span>
            </div>
            <el-form-item label="耐压检验日期" prop="preDate">
              <el-date-picker
                v-model="formData.preDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
                :disabled="preEquipCount == 0"
                class="!w-240px"
              />
              <el-checkbox
                v-model="formData.pressureIsOrderConfirm"
                class="ml-4"
                :disabled="preEquipCount == 0"
              >
                由前台约检确认
              </el-checkbox>
            </el-form-item>

            <el-form-item label="检验员" prop="preTeamList" v-if="preEquipCount !== 0">
              <div class="checker-select-container">
                <div class="checker-list">
                  <template v-if="preProcessedDeptData.length">
                    <div v-for="dept in preProcessedDeptData" :key="dept.dept.id"
                         class="dept-section">
                      <div v-for="team in dept.teamList" :key="team.id || team.deptGroupId"
                           class="group-section">
                        <div class="group-content">
                          <template v-for="subTeam in team.memberList"
                                    :key="subTeam.id || subTeam.deptGroupId">
                            <div class="group-members">
                              <div class="label">
                                <el-checkbox
                                  v-model="subTeam.checked"
                                  @change="(val: boolean) => handleSubTeamCheckChange(val, subTeam, 'pre')"
                                >
                                  {{ subTeam.name }}
                                </el-checkbox>
                              </div>
                              <div class="members-list">
                                <el-checkbox-group
                                  v-model="preSelectedCheckerIds"
                                  @change="handlePreMemberChange"
                                >
                                  <el-checkbox
                                    v-for="member in subTeam.memberList"
                                    :key="member.memberId"
                                    :value="subTeam.id + ':' + member.memberId"
                                  >
                                    <span v-if="member.memberId === member.leaderId"
                                          class="leader-tag">组</span>
                                    {{ member.member?.nickname }}
                                  </el-checkbox>
                                </el-checkbox-group>
                              </div>
                            </div>
                          </template>
                        </div>
                      </div>
                    </div>
                  </template>
                  <el-empty v-else description="暂无检验员数据"/>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="收费形式" prop="preChargeType" v-if="preEquipCount !== 0">
              <div class="flex items-center gap-4">
                <el-select v-model="formData.preChargeType" placeholder="请选择收费形式"
                           class="!w-120px">
                  <el-option label="非合同收费" value="1"/>
                  <el-option label="合同收费" value="2"/>
                </el-select>
                <span class="text-gray-600">是否免征:</span>
                <el-select v-model="formData.preIsExempt" placeholder="请选择是否免征"
                           class="!w-60px" @change="handlePreExemptChange">
                  <el-option label="否" value="0"/>
                  <el-option label="是" value="1"/>
                </el-select>
                <span class="text-gray-600">应收法定金额: {{ formData.preShouldAmount }}</span>
                <span class="text-gray-600">服务收费金额: {{ formData.preServiceAmount }}</span>
                <span class="text-gray-600">免征费用: {{ formData.preReduceFee }}</span>
              </div>
            </el-form-item>
          </div>

          <!-- 检验项目 -->
          <div
            class="checkItemContent"
            v-for="checkItem in checkItemList"
            :key="checkItem.inspectionNature"
          >
            <div v-if="checkItem.inspectionNature == formData.checkType">
              <div class="content-title">
                {{ checkItem.inspectionNatureName }}
              </div>
              <div class="inspection-grid">
                <template v-if="checkItem.itemList.length > 0">
                  <!-- Grid 容器 -->
                  <div
                    class="grid-container"
                    :style="{
                    'grid-template-columns':
                      checkItem.itemList.length < 3
                        ? `repeat(${checkItem.itemList.length}, 1fr)`
                        : `repeat(3, 1fr)`
                  }"
                  >
                    <!-- 循环渲染子项（模拟数据） -->
                    <div class="grid-item" v-for="(item, index) in checkItem.itemList" :key="index">
                      <el-checkbox
                        v-model="item.use"
                        :disabled="item.isMainProject === '1'"
                      />
                      <!--                      @change="(val) => handleCheckItemSelectedChange(item, val)"-->
                      <div style="display: flex; align-items: center; gap: 4px;">
                        <span v-if="item.isMainProject === '1'"
                              style="display: inline-flex; align-items: center; justify-content: center; width: 20px; height: 20px; background-color: #6cbcf5; color: #fff; font-size: 12px; border-radius: 2px; font-weight: bold;">主</span>
                        <span>{{ item.name }}</span>
                      </div>
                      <span>
                        (
                        <el-button link type="primary" @click="() => {
                          openFeeDialog(item)
                        }"
                        >费用：{{ item.fee || '无' }}</el-button
                        >
                        <!--                      >费用：{{ getCheckItemFeeType(item) }}</el-button-->
                        )
                      </span>
                    </div>

                  </div>
                </template>
                <el-empty style="height: 200px;" v-else
                          :description="`暂无【${checkItem.inspectionNatureName}】检验项目`"/>
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-end">
        <el-button @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm"
          :disabled="isConfirmDisabled"
        >
          确定
        </el-button>
      </div>
    </template>

    <!-- 费用计算弹窗 -->
    <el-dialog
      title="修改费用"
      v-model="showCalcCheckItemFeeDialog"
      width="500px"
    >
      <el-form>
        <div class="form-row">
          <span class="info-label ml-50px">原费用:</span>
          <span class="info-value fee-amount">{{ oldAmount || 0 }}</span>
        </div>
        <el-form-item label="新费用:" class="fee-form-item ml-50px">
          <el-input-number
            v-model="newAmount"
            class="!w-100px"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="showCalcCheckItemFeeDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmFee">确定
          </el-button>
        </div>
      </template>
    </el-dialog>

  </el-dialog>
</template>

<script setup lang="ts">
import {FormInstance} from 'element-plus'
import {useMessage} from '@/hooks/web/useMessage'
import CheckerSelect from '@/views/pressure2/equipboilerscheduling/components/CheckerSelect.vue'
import dayjs from 'dayjs';
import {
  EquipBoilerSchedulingVO,
  EquipBoilerSchedulingApi
} from "@/api/pressure2/equipboilerscheduling";
import {
  PressureBoilerCheckType,
  PressureBoilerCheckTypeMap,
  PressurePipeCheckTypeMap
} from "@/utils/constants";
import {BoilerTaskOrderApi} from "@/api/pressure2/boilertaskorder";
import {is} from "@/utils/is";
import {EquipBoilerApi} from "@/api/pressure2/equipboiler";
import {DeptGroupTeamApi} from '@/api/pressure2/deptGroupTeam'
import {useUserStoreWithOut} from '@/store/modules/user'
import {processInspectorGroups} from './inspector'
import type {ProcessedDeptData} from './inspector'
import {InspectionNatureTypeApi} from "@/api/pressure2/inspectionnaturetype";

const message = useMessage()
const {queryCheckItemList, querySchedulingCheckItemList} = BoilerTaskOrderApi
const userStore = useUserStoreWithOut()

const props = defineProps({
  selectedRows: {
    type: Array as PropType<EquipBoilerSchedulingVO[]>,
    default: () => []
  },
  selectedInList: {
    type: Array as PropType<EquipBoilerSchedulingVO[]>,
    default: () => []
  },
  selectedOutList: {
    type: Array as PropType<EquipBoilerSchedulingVO[]>,
    default: () => []
  },
  selectedPreList: {
    type: Array as PropType<EquipBoilerSchedulingVO[]>,
    default: () => []
  },
  source: {
    type: String as PropType<string>,
    default: 'pressure'
  }
})

const emit = defineEmits(['success', 'close', 'clear-selected-rows'])
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const isBatch = ref(false)
const title = computed(() => props.selectedRows.length > 1 ? '批量计划排期' : '计划排期')

// 判断确定按钮是否禁用
const isConfirmDisabled = computed(() => {
  // 根据当前选择的检验类型，判断对应设备数量是否为0
  if (formData.value.checkType == PressureBoilerCheckType.IN) {
    return inEquipCount.value === 0
  } else if (formData.value.checkType == PressureBoilerCheckType.OUT) {
    return outEquipCount.value === 0
  } else if (formData.value.checkType == PressureBoilerCheckType.PRESSURE) {
    return preEquipCount.value === 0
  }
  return false
})

// 根据检验类型获取设备数量
const getEquipCountByType = (type: string) => {
  if (type === PressureBoilerCheckType.IN) {
    return inEquipCount.value
  } else if (type === PressureBoilerCheckType.OUT) {
    return outEquipCount.value
  } else if (type === PressureBoilerCheckType.PRESSURE) {
    return preEquipCount.value
  }
  return 0
}

// 检验项目
const checkItemList = ref<any[]>([])
const showCalcCheckItemFeeDialog = ref(false)
const oldAmount = ref<number>(0)
const newAmount = ref<number>(0)

const equipList = ref<any[]>([])
// 内部检验设备数量
const inEquipCount = computed(() => {
  return props.selectedInList.length
})

// 外部检验设备数量
const outEquipCount = computed(() => {
  return props.selectedOutList.length
})

// 耐压检验设备数量
const preEquipCount = computed(() => {
  return props.selectedPreList.length
})

// 内部检验最近临期时间
const inLatestTime = computed(() => {
  const latestTime = props.selectedRows.reduce((nextInCheckDate, row) => {
    if (!row.nextInCheckDate) return nextInCheckDate
    if (!nextInCheckDate || row.nextInCheckDate < nextInCheckDate) {
      return row.nextInCheckDate
    }
    return nextInCheckDate
  }, '')
  return latestTime ? dayjs(latestTime).format('YYYY-MM-DD') : '无'
})

// 外部检验最近临期时间
const outLatestTime = computed(() => {
  const latestTime = props.selectedRows.reduce((nextOutCheckDate, row) => {
    if (!row.nextOutCheckDate) return nextOutCheckDate
    if (!nextOutCheckDate || row.nextOutCheckDate < nextOutCheckDate) {
      return row.nextOutCheckDate
    }
    return nextOutCheckDate
  }, '')
  return latestTime ? dayjs(latestTime).format('YYYY-MM-DD') : '无'
})

// 超年限检验最近临期时间
const preLatestTime = computed(() => {
  const latestTime = props.selectedRows.reduce((nextPressureCheckDate, row) => {
    if (!row.nextPressureCheckDate) return nextPressureCheckDate
    if (!nextPressureCheckDate || row.nextPressureCheckDate < nextPressureCheckDate) {
      return row.nextPressureCheckDate
    }
    return nextPressureCheckDate
  }, '')
  return latestTime ? dayjs(latestTime).format('YYYY-MM-DD') : '无'
})

const formData = ref({
  checkType: '100',
  // 内部检验
  inDate: '',
  inTeamList: [{
    groupTeamId: '',
    leaderId: '',
    memberIdList: []
  }],
  inTaskList: [],
  inIsOrderConfirm: true,
  inChargeType: '1',
  inIsExempt: '0',
  inShouldAmount: 0,
  inServiceAmount: 0,
  inReduceFee: 0,

  // 外部检验
  outDate: '',
  outTeamList: [{
    groupTeamId: '',
    leaderId: '',
    memberIdList: []
  }],
  outTaskList: [],
  outIsOrderConfirm: true,
  outChargeType: '1',
  outIsExempt: '0',
  outShouldAmount: 0,
  outServiceAmount: 0,
  outReduceFee: 0,

  // 耐压检验
  preDate: '',
  preTeamList: [{
    groupTeamId: '',
    leaderId: '',
    memberIdList: []
  }],
  pressureTaskList: [],
  pressureIsOrderConfirm: true,
  preChargeType: '1',
  preIsExempt: '0',
  preShouldAmount: 0,
  preServiceAmount: 0,
  preReduceFee: 0,

  taskList: [{
    inEquipIds: '',
    outEquipIds: '',
    preEquipIds: ''
  }]
})

// 各类型检验员选择状态
const inSelectedCheckers = ref<any[]>([])
const outSelectedCheckers = ref<any[]>([])
const preSelectedCheckers = ref<any[]>([])

// 检验员列表数据（按部门-分组-小组）
const inProcessedDeptData = ref<ProcessedDeptData[]>([])
const outProcessedDeptData = ref<ProcessedDeptData[]>([])
const preProcessedDeptData = ref<ProcessedDeptData[]>([])

// 检验员选中的ID列表（用于checkbox-group绑定）
const inSelectedCheckerIds = ref<string[]>([])
const outSelectedCheckerIds = ref<string[]>([])
const preSelectedCheckerIds = ref<string[]>([])

// 表单验证规则
const formRules = {
  inDate: [{
    validator: (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择内检日期'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }],
  inTeamList: [{
    validator: (rule, value, callback) => {
      if ((!value || value.length === 0)) {
        callback(new Error('请选择检验员'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }],
  outDate: [{
    validator: (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择外检日期'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }],
  outTeamList: [{
    validator: (rule, value, callback) => {
      if ((!value || value.length === 0)) {
        callback(new Error('请选择检验员'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }],
  preDate: [{
    validator: (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择耐压检验日期'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }],
  preTeamList: [{
    validator: (rule, value, callback) => {
      if ((!value || value.length === 0)) {
        callback(new Error('请选择检验员'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }]
}

/** 获取检验员列表 */
const getCheckerList = async (deptId: string, type: 'in' | 'out' | 'pre') => {
  try {
    const originalData = await DeptGroupTeamApi.getDeptGroupTeamMembers({
      deptIds: deptId
    })

    const processedData = processInspectorGroups(originalData)

    const dataMap = {
      in: inProcessedDeptData,
      out: outProcessedDeptData,
      pre: preProcessedDeptData
    }

    dataMap[type].value = processedData

    // 更新选中状态
    updateAllSubTeamCheckStatus(type)
  } catch (error) {
    console.error('获取检验员列表失败:', error)
  }
}

/** 更新所有小组的选中状态 */
const updateAllSubTeamCheckStatus = (type: 'in' | 'out' | 'pre') => {
  const dataMap = {
    in: inProcessedDeptData,
    out: outProcessedDeptData,
    pre: preProcessedDeptData
  }

  const checkerMap = {
    in: inSelectedCheckers,
    out: outSelectedCheckers,
    pre: preSelectedCheckers
  }

  dataMap[type].value.forEach(dept => {
    dept.teamList.forEach(team => {
      team.memberList.forEach(subTeam => {
        updateSubTeamCheckStatus(subTeam, checkerMap[type].value)
      })
    })
  })
}

/** 更新单个小组的选中状态 */
const updateSubTeamCheckStatus = (subTeam: any, selectedCheckers: any[]) => {
  const availableMembers = subTeam.memberList
  const allSubTeamMembers = availableMembers.map(m => m.id + ':' + m.memberId)

  if (allSubTeamMembers.length === 0) {
    subTeam.checked = false
    return
  }

  const selectedSubTeamMembers = selectedCheckers.filter(c =>
    allSubTeamMembers.includes(c.groupTeamId + ':' + c.memberId)
  )

  subTeam.checked = selectedSubTeamMembers.length === allSubTeamMembers.length
}

/** 处理小组全选 */
const handleSubTeamCheckChange = (val: boolean, subTeam: any, type: 'in' | 'out' | 'pre') => {
  const checkerMap = {
    in: inSelectedCheckers,
    out: outSelectedCheckers,
    pre: preSelectedCheckers
  }

  const availableMembers = subTeam.memberList
  const memberIds = availableMembers.map(member => ({
    groupTeamId: subTeam.id,
    memberId: member.memberId,
    leaderId: subTeam.leaderId,
    member: member.member,
    isLeader: member.memberId === subTeam.leaderId
  }))

  if (val) {
    // 选中：添加所有可用成员
    const existingIds = new Set(checkerMap[type].value.map(c => c.groupTeamId + ':' + c.memberId))
    memberIds.forEach(member => {
      if (!existingIds.has(member.groupTeamId + ':' + member.memberId)) {
        checkerMap[type].value.push(member)
      }
    })
  } else {
    // 取消选中：移除当前小组的所有成员
    const memberIdsSet = new Set(memberIds.map(m => m.groupTeamId + ':' + m.memberId))
    checkerMap[type].value = checkerMap[type].value.filter(c =>
      !memberIdsSet.has(c.groupTeamId + ':' + c.memberId)
    )
  }

  // 更新小组选中状态
  updateSubTeamCheckStatus(subTeam, checkerMap[type].value)

  // 同步到其他类型
  syncCheckers(type, checkerMap[type].value)

  // 更新 formData 中的 teamList
  updateTeamList(type)
}

/** 处理成员选择变化 */
const handleMemberChange = (type: 'in' | 'out' | 'pre') => {
  const checkerMap = {
    in: inSelectedCheckers,
    out: outSelectedCheckers,
    pre: preSelectedCheckers
  }

  // 更新所有小组的选中状态
  updateAllSubTeamCheckStatus(type)

  // 同步到其他类型
  syncCheckers(type, checkerMap[type].value)

  // 更新 formData 中的 teamList
  updateTeamList(type)
}

/** 处理内部检验员变化 */
const handleInMemberChange = (values: string[]) => {
  const allMembers = getAllMembersFromData(inProcessedDeptData.value)
  inSelectedCheckers.value = values.map(id => {
    const [groupTeamId, memberId] = id.split(':')
    return allMembers.find(m => m.groupTeamId === groupTeamId && m.memberId.toString() === memberId)
  }).filter(Boolean)
  handleMemberChange('in')
}

/** 处理外部检验员变化 */
const handleOutMemberChange = (values: string[]) => {
  const allMembers = getAllMembersFromData(outProcessedDeptData.value)
  outSelectedCheckers.value = values.map(id => {
    const [groupTeamId, memberId] = id.split(':')
    return allMembers.find(m => m.groupTeamId === groupTeamId && m.memberId.toString() === memberId)
  }).filter(Boolean)
  handleMemberChange('out')
}

/** 处理耐压检验员变化 */
const handlePreMemberChange = (values: string[]) => {
  const allMembers = getAllMembersFromData(preProcessedDeptData.value)
  preSelectedCheckers.value = values.map(id => {
    const [groupTeamId, memberId] = id.split(':')
    return allMembers.find(m => m.groupTeamId === groupTeamId && m.memberId.toString() === memberId)
  }).filter(Boolean)
  handleMemberChange('pre')
}

/** 从处理后的数据中获取所有成员 */
const getAllMembersFromData = (processedData: ProcessedDeptData[]) => {
  const members: any[] = []
  processedData.forEach(dept => {
    dept.teamList.forEach(team => {
      team.memberList.forEach(subTeam => {
        subTeam.memberList.forEach(member => {
          members.push({
            groupTeamId: subTeam.id,
            memberId: member.memberId,
            leaderId: subTeam.leaderId,
            member: member.member,
            isLeader: member.memberId === subTeam.leaderId
          })
        })
      })
    })
  })
  return members
}

// 监听检验员对象变化，同步更新ID列表
watch(() => inSelectedCheckers.value, (newVal) => {
  inSelectedCheckerIds.value = newVal.map(c => c.groupTeamId + ':' + c.memberId)
}, {deep: true})

watch(() => outSelectedCheckers.value, (newVal) => {
  outSelectedCheckerIds.value = newVal.map(c => c.groupTeamId + ':' + c.memberId)
}, {deep: true})

watch(() => preSelectedCheckers.value, (newVal) => {
  preSelectedCheckerIds.value = newVal.map(c => c.groupTeamId + ':' + c.memberId)
}, {deep: true})


/** 监听日期变化 */
watch(() => formData.value.inDate, (newDate) => {
  if (newDate) {
    // 只有在未设置且未勾选"无需安排"的情况下才自动填充
    if (!formData.value.outDate) {
      formData.value.outDate = newDate
    }
    if (!formData.value.preDate) {
      formData.value.preDate = newDate
    }
  }
})

watch(() => formData.value.outDate, (newDate) => {
  if (newDate) {
    if (!formData.value.outDate) {
      formData.value.outDate = newDate
    }
    if (!formData.value.preDate) {
      formData.value.preDate = newDate
    }
  }
})

watch(() => formData.value.preDate, (newDate) => {
  if (newDate) {
    if (!formData.value.inDate) {
      formData.value.inDate = newDate
    }
    if (!formData.value.outDate) {
      formData.value.outDate = newDate
    }
  }
})

/** 监听检验员变化 */
const syncCheckers = (sourceType: string, checkers: any[]) => {
  const typeMap = {
    in: ['out', 'pre'],
    out: ['in', 'pre'],
    pre: ['in', 'out']
  }

  typeMap[sourceType].forEach(type => {
    const checkerMap = {
      in: inSelectedCheckers,
      out: outSelectedCheckers,
      pre: preSelectedCheckers
    }
    // 只有在未选择检验员且未勾选"无需安排"的情况下才自动同步
    if (checkerMap[type].value.length === 0) {
      checkerMap[type].value = [...checkers]
      updateTeamList(type)
    }
  })
}

/** 修改 confirmCheckerSelect 方法 - 已废弃，现在直接在界面上操作 */

const feeInspectionNature = ref()
const feeType= ref()
const feeTemplateId = ref()
const openFeeDialog = (item) => {
  showCalcCheckItemFeeDialog.value = true
  feeInspectionNature.value = item.inspectionNature
  feeTemplateId.value = item.templateId
  feeType.value = item.type

  oldAmount.value = item.fee || 0
  newAmount.value = item.fee || 0
}

const confirmFee = () => {
  console.log(checkItemList.value.find(item => item.inspectionNature == feeInspectionNature.value && item.type == feeType.value));
  let item = checkItemList.value.find(item => item.inspectionNature == feeInspectionNature.value && item.type == feeType.value).itemList.find(i => i.templateId == feeTemplateId.value)
  item.fee = newAmount.value;
  newAmount.value = 0
  handleCheckItemFeeConfirm()
  showCalcCheckItemFeeDialog.value = false;
}

/** 处理内部检验免征变化 */
const handleInExemptChange = (val: string) => {
  calculateInAmounts()
}

/** 处理外部检查免征变化 */
const handleOutExemptChange = (val: string) => {
  calculateOutAmounts()
}

/** 处理耐压检查免征变化 */
const handlePreExemptChange = (val: string) => {
  calculatePreAmounts()
}

/** 计算内部检验金额 */
const calculateInAmounts = () => {
  const inItems = checkItemList.value.filter(i => i.inspectionNature == PressureBoilerCheckType.IN)
  if (!inItems) return

  // 分离法定收费项目和服务收费项目
  const find = inItems?.find(item => item.type === '1');
  if (!find) return;
  const statutoryItems = find.itemList.filter(item => item.use)
  const find1 = inItems?.find(item => item.type === '2');
  if (!find1) return;
  const serviceItems = find1.itemList.filter(item => item.use)
  // 计算法定金额总和
  const totalStatutoryAmount = statutoryItems.reduce((sum, item) => sum + (item.fee || 0), 0)
  // 计算服务收费金额总和
  const totalServiceAmount = serviceItems.reduce((sum, item) => sum + (item.fee || 0), 0)

  if (formData.value.inIsExempt === '1') {
    // 免征：免征费用=应收法定金额，应收法定金额=0
    formData.value.inReduceFee = totalStatutoryAmount
    formData.value.inShouldAmount = 0
  } else {
    // 不免征：免征费用=0，应收法定金额=总金额
    formData.value.inReduceFee = 0
    formData.value.inShouldAmount = totalStatutoryAmount
  }

  formData.value.inServiceAmount = totalServiceAmount
}
/** 外部检验金额 */
const calculateOutAmounts = () => {
  const outItems = checkItemList.value.filter(i => i.inspectionNature == PressureBoilerCheckType.OUT)
  if (!outItems) return

  // 分离法定收费项目和服务收费项目
  const find = outItems?.find(item => item.type === '1');
  if (!find) return;
  const statutoryItems = find.itemList.filter(item => item.use)
  const find1 = outItems?.find(item => item.type === '2');
  if (!find1) return;
  const serviceItems = find1.itemList.filter(item => item.use)

  // 计算法定金额总和
  const totalStatutoryAmount = statutoryItems.reduce((sum, item) => sum + (item.fee || 0), 0)
  // 计算服务收费金额总和
  const totalServiceAmount = serviceItems.reduce((sum, item) => sum + (item.fee || 0), 0)

  if (formData.value.outIsExempt === '1') {
    // 免征：免征费用=应收法定金额，应收法定金额=0
    formData.value.outReduceFee = totalStatutoryAmount
    formData.value.outShouldAmount = 0
  } else {
    // 不免征：免征费用=0，应收法定金额=总金额
    formData.value.outReduceFee = 0
    formData.value.outShouldAmount = totalStatutoryAmount
  }

  formData.value.outServiceAmount = totalServiceAmount
}
/** 计算耐压检验金额 */
const calculatePreAmounts = () => {
  const preItems = checkItemList.value.filter(i => i.inspectionNature == PressureBoilerCheckType.PRESSURE)
  if (!preItems) return

  // 分离法定收费项目和服务收费项目
  const find = preItems?.find(item => item.type === '1');
  if (!find) return;
  const statutoryItems = find.itemList.filter(item => item.use)
  const find1 = preItems?.find(item => item.type === '2');
  if (!find1) return;
  const serviceItems = find1.itemList.filter(item => item.use)

  // 计算法定金额总和
  const totalStatutoryAmount = statutoryItems.reduce((sum, item) => sum + (item.fee || 0), 0)
  // 计算服务收费金额总和
  const totalServiceAmount = serviceItems.reduce((sum, item) => sum + (item.fee || 0), 0)

  if (formData.value.preIsExempt === '1') {
    // 免征：免征费用=应收法定金额，应收法定金额=0
    formData.value.preReduceFee = totalStatutoryAmount
    formData.value.preShouldAmount = 0
  } else {
    // 不免征：免征费用=0，应收法定金额=总金额
    formData.value.preReduceFee = 0
    formData.value.preShouldAmount = totalStatutoryAmount
  }

  formData.value.preServiceAmount = totalServiceAmount
}


const handleCheckItemFeeConfirm = () => {
  // formData.value.actualAmount = 0
  // checkItemList.value.forEach(item => {
  //   item.itemList.forEach(item => {
  //     let num= 0
  //     if (PressureBoilerCheckType.IN == item.inspectionNature){
  //       num = nextInCheckCount.value
  //     }
  //     if (PressureBoilerCheckType.OUT == item.inspectionNature){
  //       num = nextOutCheckCount.value
  //     }
  //     if (PressureBoilerCheckType.PRESSURE == item.inspectionNature){
  //       num = nextPressureCheckCount.value
  //     }
  //     formData.value.actualAmount += item.fee * num
  //   })
  // })
  calculateInAmounts()
  calculateOutAmounts()
  calculatePreAmounts()
}

// 监听检验项目使用状态变化，自动重新计算金额
watch(() => checkItemList.value, () => {
  calculateInAmounts()
  calculateOutAmounts()
  calculatePreAmounts()
}, {deep: true})


/** 更新 teamList */
const updateTeamList = (type) => {
  const checkerMap = {
    in: inSelectedCheckers,
    out: outSelectedCheckers,
    pre: preSelectedCheckers
  }

  const teamListMap = {
    in: 'inTeamList',
    out: 'outTeamList',
    pre: 'preTeamList'
  }

  const groupedTeams = checkerMap[type].value.reduce((acc, checker) => {
    const {groupTeamId} = checker
    if (!acc[groupTeamId]) {
      acc[groupTeamId] = {
        groupTeamId,
        leaderId: '',
        memberIdList: []
      }
    }

    if (checker.isLeader) {
      acc[groupTeamId].leaderId = checker.memberId
    } else {
      acc[groupTeamId].memberIdList.push(checker.memberId)
    }

    return acc
  }, {})

  formData.value[teamListMap[type]] = Object.values(groupedTeams)
}


// 查询项目列表
const handleQueryCheckItemList = async () => {
  let req = []
  console.log(props.selectedRows)
  // if (props.selectedRows?.length > 0) {
  //   for (const item of props.selectedRows) {
  //     req = [...req, ...(item.inEquipIds?.split(',') || []), ...(item.outEquipIds?.split(',') || []), ...(item.preEquipIds?.split(',') || [])]
  //   }
  // } else {
  //   return
  // }
  // if (req.length != 0) {
  //   equipList.value = await EquipBoilerApi.getNameByIds(req)
  // }
  checkItemList.value = []
  const checkTypes = [
    PressureBoilerCheckType.IN,
    PressureBoilerCheckType.OUT,
    PressureBoilerCheckType.PRESSURE
  ];
  // 校验所有选中的任务列表中的设备类型是否一致
  const allTasks = [
    ...formData.value.inTaskList,
    ...formData.value.outTaskList,
    ...formData.value.pressureTaskList
  ]

  if (allTasks.length > 0) {
    const firstType = allTasks[0].type
    const hasDifferentType = allTasks.some(task => task.type !== firstType)

    if (hasDifferentType) {
      ElMessage.error('请选择同一类型设备')
      dialogVisible.value = false
      return
    }
  }

  // 获取统一的设备类型，如果列表为空则设为 undefined
  const equipType = allTasks.length > 0 ? allTasks[0].type : undefined

  for (const type of checkTypes) {
    const params = {
      orderId: "0",
      itemIds: equipList.value.map(item => item.id),
      equipmentCategory: 300,
      inspectionNature: [type],
      equipType:equipType
    };
    const queryResult = await querySchedulingCheckItemList(params);
    const inspectionNatureType = await InspectionNatureTypeApi.getInspectionNatureTypePage({
      pageNo: 1,
      pageSize: 1,
      equip: '200',
      nature: type
    })
    const inType = inspectionNatureType.list[0].type
    checkItemList.value.push({
      inspectionNatureName: PressureBoilerCheckTypeMap[type] + " 法定收费项目",
      inspectionNature: type,
      type: '1',
      itemList: (queryResult || []).map((item) => (
        {
          ...item,
          isAutoAmount: '0', // 批量模式下默认为'0'
          inspectionNature: type,
          type: '1',
          use: inType == 1 ? item.use : false
        }
      ))
    });
    checkItemList.value.push({
      inspectionNatureName: PressureBoilerCheckTypeMap[type] + " 服务收费项目",
      inspectionNature: type,
      type: '2',
      itemList: (queryResult || []).map((item) => (
        {
          ...item,
          isAutoAmount: '0', // 批量模式下默认为'0'
          inspectionNature: type,
          type: '2',
          use: inType == 2 ? item.use : false
        }
      ))
    });
  }

}

/** 打开弹窗 */
const open = async (selectedInList, selectedOutList, selectedPreList, type?: string) => {
  //console.log('open', props.selectedRows)
  dialogVisible.value = true


  // 重置所有检验员选择
  inSelectedCheckers.value = []
  outSelectedCheckers.value = []
  preSelectedCheckers.value = []

  // 使用传入的数据计算各类型设备数量
  const counts = {
    in: selectedInList?.length,
    out: selectedOutList?.length,
    pre: selectedPreList?.length
  }

  // 重置表单数据
  formData.value = {
    checkType: type || '100',
    inDate: '',
    inTeamList: [],
    inTaskList: [],
    inIsOrderConfirm: true,
    inChargeType: '1',
    inIsExempt: '0',
    inShouldAmount: 0,
    inServiceAmount: 0,
    inReduceFee: 0,
    outDate: '',
    outTeamList: [],
    outTaskList: [],
    outChargeType: '1',
    outIsOrderConfirm: true,
    outIsExempt: '0',
    outShouldAmount: 0,
    outServiceAmount: 0,
    outReduceFee: 0,
    preDate: '',
    preTeamList: [],
    pressureTaskList: [],
    pressureIsOrderConfirm: true,
    preChargeType: '1',
    preIsExempt: '0',
    preShouldAmount: 0,
    preServiceAmount: 0,
    preReduceFee: 0,
  }

  formData.value.inTaskList = selectedInList
  formData.value.outTaskList = selectedOutList
  formData.value.pressureTaskList = selectedPreList

  handleQueryCheckItemList()

  // 加载检验员列表（默认当前登录人的部门）
  const deptId = userStore.getUser.deptId?.toString()
  if (deptId) {
    await Promise.all([
      getCheckerList(deptId, 'in'),
      getCheckerList(deptId, 'out'),
      getCheckerList(deptId, 'pre')
    ])
  }
}

/** 取消操作 */
const handleCancel = () => {
  dialogVisible.value = false
  if (!isBatch.value) {
    emit('clear-selected-rows') // 新增事件用于清空选中行
  }
  emit('close')
}

/** 确认操作 */
const handleConfirm = async () => {
  const form = unref(formRef)
  if (!form) return

  //验证
  await form.validate()

  try {
    // 组装新的数据结构
    const submitData: { taskList: any[]; source: number } = {
      taskList: [],
      source: props.source === 'pressure' ? 100 : 200
    }
    const inUnitList = formData.value.inTaskList.reduce((acc, item) => {
      const key = item.unitId;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(item)
      return acc;
    }, {})

    const outUnitList = formData.value.outTaskList.reduce((acc, item) => {
      const key = item.unitId;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(item)
      return acc;
    }, {})
    const preUnitList = formData.value.pressureTaskList.reduce((acc, item) => {
      const key = item.unitId;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(item)
      return acc;
    }, {})

    // 遍历 formData.value.taskList 中的每个项目
    if (formData.value.checkType == '100') {
      Object.values(inUnitList).forEach(item => {
        // 处理内部检验
        if (formData.value.inDate && formData.value.inTaskList.length > 0) {
          let actualAmount = 0
          console.log(checkItemList.value.find(i => i.inspectionNature == PressureBoilerCheckType.IN))
          checkItemList.value.find(i => i.inspectionNature == PressureBoilerCheckType.IN).itemList.filter(i => i.use).forEach(i => {
            actualAmount += i.fee
          })
          submitData.taskList.push({
            equipIds: item.map(item => item.id).join(','),
            type: '100',
            hasOrderConfirm: formData.value.inIsOrderConfirm,
            date: formData.value.inDate,
            teamList: formData.value.inTeamList,
            chargeType: formData.value.inChargeType,
            isExempt: formData.value.inIsExempt,
            shouldAmount: formData.value.inShouldAmount,
            serviceAmount: formData.value.inServiceAmount,
            reduceFee: formData.value.inReduceFee,
            actualAmount,
            checkItemList: [...checkItemList.value.filter(i => i.inspectionNature == PressureBoilerCheckType.IN)[0].itemList.filter(i => i.use).map(
              i => {
                return {
                  //reportId: i.templateId,
                  reportId: i.connectId,
                  newAmount: i.fee,
                  type: i.type,
                }
              }
            ), ...checkItemList.value.filter(i => i.inspectionNature == PressureBoilerCheckType.IN)[1].itemList.filter(i => i.use).map(
              i => {
                return {
                  //reportId: i.templateId,
                  reportId: i.connectId,
                  newAmount: i.fee,
                  type: i.type,
                }
              }
            ),]
          })

        }
      })
    }
    // 处理外部检验
    if (formData.value.checkType == '200') {
      Object.values(outUnitList).forEach(item => {
        // 处理内部检验
        if (formData.value.outDate && formData.value.outTaskList.length > 0) {
          let actualAmount = 0
          checkItemList.value.find(i => i.inspectionNature == PressureBoilerCheckType.OUT).itemList.filter(i => i.use).forEach(i => {
            actualAmount += i.fee
          })
          submitData.taskList.push({
            equipIds: item.map(item => item.id).join(','),
            type: '200',
            hasOrderConfirm: formData.value.outIsOrderConfirm,
            date: formData.value.outDate,
            teamList: formData.value.outTeamList,
            chargeType: formData.value.outChargeType,
            isExempt: formData.value.outIsExempt,
            shouldAmount: formData.value.outShouldAmount,
            serviceAmount: formData.value.outServiceAmount,
            reduceFee: formData.value.outReduceFee,
            actualAmount,
            checkItemList: [...checkItemList.value.filter(i => i.inspectionNature == PressureBoilerCheckType.OUT)[0].itemList.filter(i => i.use).map(
              i => {
                return {
                  //reportId: i.templateId,
                  reportId: i.connectId,
                  newAmount: i.fee,
                  type: i.type,
                }
              }
            ), ...checkItemList.value.filter(i => i.inspectionNature == PressureBoilerCheckType.OUT)[1].itemList.filter(i => i.use).map(
              i => {
                return {
                  //reportId: i.templateId,
                  reportId: i.connectId,
                  newAmount: i.fee,
                  type: i.type,
                }
              }
            ),]
          })

        }
      })
    }

    // 处理耐压检验
    if (formData.value.checkType == '300') {
      Object.values(preUnitList).forEach(item => {
        // 处理内部检验
        if (formData.value.preDate && formData.value.pressureTaskList.length > 0) {
          let actualAmount = 0
          checkItemList.value.find(i => i.inspectionNature == PressureBoilerCheckType.IN).itemList.filter(i => i.use).forEach(i => {
            actualAmount += i.fee
          })
          submitData.taskList.push({
            equipIds: item.map(item => item.id).join(','),
            type: '300',
            hasOrderConfirm: formData.value.pressureIsOrderConfirm,
            date: formData.value.preDate,
            chargeType: formData.value.preChargeType,
            isExempt: formData.value.preIsExempt,
            shouldAmount: formData.value.preShouldAmount,
            serviceAmount: formData.value.preServiceAmount,
            reduceFee: formData.value.preReduceFee,
            actualAmount,
            checkItemList: [...checkItemList.value.filter(i => i.inspectionNature == PressureBoilerCheckType.PRESSURE)[0].itemList.filter(i => i.use).map(
              i => {
                return {
                  //reportId: i.templateId,
                  reportId: i.connectId,
                  newAmount: i.fee,
                  type: i.type,
                }
              }
            ), ...checkItemList.value.filter(i => i.inspectionNature == PressureBoilerCheckType.PRESSURE)[1].itemList.filter(i => i.use).map(
              i => {
                return {
                  //reportId: i.templateId,
                  reportId: i.connectId,
                  newAmount: i.fee,
                  type: i.type,
                }
              }
            ),]
          })

        }
      })
    }

    console.log('submitData', submitData)
    const res = await EquipBoilerSchedulingApi.planSchedulingAssign(submitData)
    //console.log(res)
    message.success('保存成功')
    dialogVisible.value = false
    emit('success')
  } catch
    (error) {
    console.error( error)
    message.error('保存失败')
  }
}


// 向父组件暴露方法
defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.plan-section {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;

  .section-title {
    margin: -16px -16px 16px -16px;
    padding: 8px 16px;
    background-color: #F5F7FA;
    border-bottom: 1px solid #EBEEF5;
    font-weight: bold;
    display: flex;
    align-items: center;

    .section-info {
      font-weight: normal;
      font-size: 13px;
      color: #606266;
      margin-left: 26px;
    }
  }
}

.checker-select-container {
  width: 100%;

  .checker-list {
    border: 1px solid #EBEEF5;
    border-radius: 4px;

    .dept-section {
      .group-section {
        margin-bottom: 0;
        border-bottom: 1px solid #EBEEF5;

        &:last-child {
          border-bottom: none;
        }

        .group-content {
          padding: 6px 0 0 16px;

          .group-members {
            display: flex;
            margin-bottom: 6px;
            align-items: flex-start;

            &:last-child {
              margin-bottom: 0;
            }

            .label {
              flex: 0 0 100px;
              font-weight: bold;

              :deep(.el-checkbox) {
                margin-right: 0;
                display: inline-flex;
                align-items: center;
                font-weight: bold;

                .el-checkbox__label {
                  padding-left: 6px;
                  font-weight: bold !important;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                }
              }
            }

            .members-list {
              flex: 1;
              display: flex;
              flex-wrap: wrap;
              gap: 0 12px;

              :deep(.el-checkbox) {
                margin-right: 0;
                min-width: 90px;
                margin-bottom: 8px;
                display: inline-flex;
                align-items: center;

                .el-checkbox__label {
                  padding-left: 6px;
                  display: inline-block;
                  width: 80px;
                  text-align: left;
                }
              }
            }
          }
        }
      }
    }
  }

}

.content-title {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
  height: 36px;
  line-height: 36px;
  background-color: var(--el-color-primary-light-9);

  &::before {
    content: '';
    height: 70%;
    width: 4px;
    margin-right: 12px;
    background-color: var(--el-color-primary);
  }
}

/* 外层容器 */
.inspection-grid {
  width: 100%;
  padding: 16px;
}

/* 标题行 */
.grid-header {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  height: 38px;
  line-height: 38px;
  border: 1px solid var(--el-border-color-light);
  border-bottom: 0;
  background-color: var(--el-color-primary-light-9);
}

/* Grid 容器核心配置 */
.grid-container {
  display: grid;
  /* 5列等宽，列间距 12px，行间距 16px */
  grid-template-columns: repeat(5, 1fr);
  align-items: center; /* 垂直居中 */
  grid-gap: 1px;
  background-color: var(--el-border-color-light);
  border: 1px solid var(--el-border-color-light);
}

/* 子项布局：复选框 + 文本 + 图标 */
.grid-item {
  display: flex;
  align-items: center;
  padding-left: 20px;
  padding-right: 12px;
  height: 52px;
  background-color: #fff;

  .el-checkbox {
    margin-right: 6px;
  }
}

.form-row {
  display: flex;
  align-items: center;

  .info-label {
    font-weight: bold;
    text-align: right;
    margin-right: 10px;
  }

  .info-value {
    flex: 1;
  }
}

.fee-amount {
  font-weight: bold;
  color: #e6a23c;
  font-size: 16px;
}

.fee-form-item {
  margin-top: 20px;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }
}

.leader-tag {
  display: inline-block;
  width: 14px;
  height: 14px;
  line-height: 12px;
  text-align: center;
  border: 1px solid #4475d6;
  font-size: 10px;
  margin-right: 4px;
  color: #4475d6;
}
</style> 
