<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    :width="'1000px'"
    append-to-body
    destroy-on-close
  >
    <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 PressurePipeCheckTypeMap"
                :key="value"
                :value="value"
              >
                {{ label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 定期检验配置 -->
          <div class="plan-section" v-if="formData.checkType == PressurePipeCheckType.REGULAR">
            <div class="section-title">
              <span>定期检验</span>
              <span class="section-info">
                待检设备数量: {{ legalEquipCount }} &nbsp;&nbsp; 最近临期时间: {{ legalLatestTime }}
              </span>
            </div>
            <el-form-item label="检验日期" prop="legalDate">
              <el-date-picker
                v-model="formData.legalDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
                class="!w-240px"
              />
              <el-checkbox
                v-if="!isFrontDesk"
                v-model="formData.legalIsOrderConfirm"
                class="ml-4"
                :disabled="legalEquipCount === 0"
              >
                由前台约检确认
              </el-checkbox>
            </el-form-item>

            <el-form-item label="检验员">
              <CheckerSelect
                ref="checkerLegalRef"
                v-model="legalSelectedCheckers"
                @change="(v: CheckerItem[]) => handleCheckerSelectChange('legal', v)"
              />
            </el-form-item>

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

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

            <el-form-item label="检验员">
              <CheckerSelect
                ref="checkerYearRef"
                v-model="yearSelectedCheckers"
                @change="(v: CheckerItem[]) => handleCheckerSelectChange('year', v)"
              />
            </el-form-item>

            <el-form-item label="收费形式" prop="yearChargeType">
              <div class="flex items-center gap-4">
                <el-select v-model="formData.yearChargeType" placeholder="请选择收费形式"
                           class="!w-120px">
                  <el-option label="非合同收费" value="1"/>
                </el-select>
                <span class="text-gray-600">应收法定金额: {{ formData.yearShouldAmount }}</span>
                <span class="text-gray-600">服务收费金额: {{ formData.yearServiceAmount }}</span>
              </div>
            </el-form-item>
          </div>

          <!-- 检验项目 -->
          <div
            class="checkItemContent"
            v-for="checkItem in checkItemList"
            v-show="showCheck(checkItem)"
            :key="checkItem.inspectionNature + '-' + checkItem.type"
          >
            <div v-if="checkItem.inspectionNature == formData.checkType && getEquipCountByType(checkItem.inspectionNature) != 0 && (checkItem.inspectionNature == '100' ? checkItem.type == '1' : checkItem.type == '2')">
              <div class="content-title" @click="toggleCheckItemCollapse(checkItem)">
                <el-icon class="collapse-icon" :class="{ 'is-collapsed': !checkItem.isExpanded }">
                  <ArrowDown />
                </el-icon>
                {{ checkItem.inspectionNatureName }}
              </div>
              <div class="inspection-grid" v-show="checkItem.isExpanded">
                <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
                        :disabled="item.isMainProject === '1'|| item.name === '一览表'"
                        v-model="item.use"
                      />
                      <!--                      @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 v-if="item.isFee === '1'">
                      (
                      <el-button link type="primary" @click="() => {
                        openFeeDialog(item)
                      }"
                      >费用：{{ item.fee || '无' }}</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" :loading="submitLoading" @click="handleConfirm">确定</el-button>
      </div>
    </template>
    <!-- 费用计算弹窗 -->
    <CalcProjectFee
      v-if="currentFeeItem"
      v-model="showCalcCheckItemFeeDialog"
      :project-id="currentFeeItem.connectId"
      :old-fee="currentFeeItem.fee || 0"
      :fee-calculate-json-str="currentFeeItem.feeCalculateJson || ''"
      @save="handleFeeSave"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import {FormInstance} from 'element-plus'
import {ArrowDown} from '@element-plus/icons-vue'
import {useMessage} from '@/hooks/web/useMessage'
import dayjs from 'dayjs';
import {EquipPipeSchedulingApi, EquipPipeSchedulingVO} from "@/api/pressure2/pipescheduling";
import {
  PressurePipeCheckType,
  PressurePipeCheckTypeMap
} from "@/utils/constants";
import {PipeTaskOrderApi} from "@/api/pressure2/pipetaskorder";
import {InspectionNatureTypeApi} from "@/api/pressure2/inspectionnaturetype";
import CheckerSelect from '@/views/pressure2/components/CheckerSelect/index.vue'
import type { CheckerItem } from '@/views/pressure2/components/CheckerSelect'
import {ClientUnitApi} from "../../../../api/system/clientunit";
import CalcProjectFee from '@/views/pressure2/equipboilerscheduling/components/calcProjectFee.vue'

const message = useMessage()
const {queryCheckItemList, querySchedulingCheckItemList} = PipeTaskOrderApi

const props = defineProps({
  selectedRows: {
    type: Array as PropType<EquipPipeSchedulingVO[]>,
    default: () => []
  },
  selectedPipeRows: {
    type: Array as PropType<EquipPipeSchedulingVO[]>,
    default: () => []
  },
  selectedLegalList: {
    type: Array as PropType<EquipPipeSchedulingVO[]>,
    default: () => []
  },
  selectedYearList: {
    type: Array as PropType<EquipPipeSchedulingVO[]>,
    default: () => []
  },
  source: {
    type: String as PropType<string>,
    default: 'pressure'
  }
})

// 是否前台约检来源：前台约检跳过计划表提交+约检确认，直接生成受理单
const isFrontDesk = computed(() => props.source === 'plan')

const emit = defineEmits(['success', 'close'])
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const submitLoading = ref(false) // 提交按钮 loading
const checkerLegalRef = ref()
const checkerYearRef = ref()

const title = computed(() => props.selectedPipeRows.length > 1 ? '批量计划排期' : '计划排期')

// 检验项目
const checkItemList = ref<any[]>([])
const showCalcCheckItemFeeDialog = ref(false)
const currentFeeItem = ref<any>(null)
const equipList = ref<any[]>([])
// 定期检验设备数量
const legalEquipCount = computed(() => {
  return props.selectedLegalList.length
})

// 年度检查设备数量
const yearEquipCount = computed(() => {
  return props.selectedYearList.length
})

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

// 年度检查最近临期时间
const yearLatestTime = computed(() => {
  const latestTime = props.selectedPipeRows.reduce((nextYearCheckDate, row) => {
    if (!row.nextYearCheckDate) return nextYearCheckDate
    if (!nextYearCheckDate || row.nextYearCheckDate < nextYearCheckDate) {
      return row.nextYearCheckDate
    }
    return nextYearCheckDate
  }, '')
  return latestTime ? dayjs(latestTime).format('YYYY-MM-DD') : '无'
})


const formData = ref({
  checkType: '100',
  // 定期检验
  legalDate: '',
  legalTeamList: [],
  legalTaskList: [],
  legalIsOrderConfirm: true,
  legalChargeType: '1',
  legalIsExempt: '0',
  legalShouldAmount: 0,
  legalServiceAmount: 0,
  legalReduceFee: 0,

  // 年度检查
  yearDate: '',
  yearTeamList: [],
  yearTaskList: [],
  yearIsOrderConfirm: true,
  yearChargeType: '1',
  yearIsExempt: '0',
  yearShouldAmount: 0,
  yearServiceAmount: 0,
  yearReduceFee: 0,
})

// 各类型检验员选择状态
const legalSelectedCheckers = ref<CheckerItem[]>([])
const yearSelectedCheckers = ref<CheckerItem[]>([])

// 表单验证规则
const formRules = {
  legalDate: [{
    validator: (rule, value, callback) => {
      if (!value && formData.value.legalTaskList.length > 0) {
        callback(new Error('请选择定检日期'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }],
  yearDate: [{
    validator: (rule, value, callback) => {
      if (!value && formData.value.yearTaskList.length > 0) {
        callback(new Error('请选择年检日期'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }],
}

/** 处理统一 CheckerSelect 组件的选择变化 */
const handleCheckerSelectChange = (type: 'legal' | 'year', checkers: CheckerItem[]) => {
  updateTeamList(type)
}

/** 监听检验员变化 */
const syncCheckers = (sourceType: string, checkers: CheckerItem[]) => {
  const typeMap = {
    legal: ['year'],
    year: ['legal']
  }

  typeMap[sourceType].forEach(type => {
    const checkerMap = {
      legal: legalSelectedCheckers,
      year: yearSelectedCheckers,
    }
    // 只有在未选择检验员的情况下才自动同步
    if (checkerMap[type].value.length === 0) {
      checkerMap[type].value = [...checkers]
      updateTeamList(type)
    }
  })
}


const openFeeDialog = (item) => {
  showCalcCheckItemFeeDialog.value = true
  currentFeeItem.value = item
}

const handleFeeSave = (result: { fee: number; feeCalculateJson: string }) => {
  if (currentFeeItem.value) {
    currentFeeItem.value.fee = result.fee
    currentFeeItem.value.feeCalculateJson = result.feeCalculateJson
  }
  currentFeeItem.value = null
  handleCheckItemFeeConfirm()
  showCalcCheckItemFeeDialog.value = false
}

/** 处理定期检验免征变化 */
const handleLegalExemptChange = (val: string) => {
  calculateLegalAmounts()
}

/** 处理年度检查免征变化 */
const handleYearExemptChange = (val: string) => {
  calculateYearAmounts()
}

/** 计算定期检验金额 */
const calculateLegalAmounts = () => {
  const legalItems = checkItemList.value.filter(i => i.inspectionNature == PressurePipeCheckType.REGULAR)
  if (!legalItems) return

  // 分离法定收费项目和服务收费项目
  const find = legalItems?.find(item => item.type === '1');
  if (!find) return;
  const statutoryItems = find.itemList.filter(item => item.use)
  const find1 = legalItems?.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.legalIsExempt === '1') {
    // 免征：免征费用=应收法定金额，应收法定金额=0
    formData.value.legalReduceFee = totalStatutoryAmount
    formData.value.legalShouldAmount = 0
  } else {
    // 不免征：免征费用=0，应收法定金额=总金额
    formData.value.legalReduceFee = 0
    formData.value.legalShouldAmount = totalStatutoryAmount
  }

  formData.value.legalServiceAmount = totalServiceAmount
}

/** 计算年度检查金额 */
const calculateYearAmounts = () => {
  const yearItems = checkItemList.value.filter(i => i.inspectionNature == PressurePipeCheckType.ANNUAL)
  if (!yearItems) return

  // 分离法定收费项目和服务收费项目
  const find = yearItems?.find(item => item.type === '1');
  if (!find) return;
  const statutoryItems = find.itemList.filter(item => item.use)
  const find1 = yearItems?.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.yearIsExempt === '1') {
    // 免征：免征费用=应收法定金额，应收法定金额=0
    formData.value.yearReduceFee = totalStatutoryAmount
    formData.value.yearShouldAmount = 0
  } else {
    // 不免征：免征费用=0，应收法定金额=总金额
    formData.value.yearReduceFee = 0
    formData.value.yearShouldAmount = totalStatutoryAmount
  }

  formData.value.yearServiceAmount = totalServiceAmount
}

const handleCheckItemFeeConfirm = () => {
  // 费用修改后重新计算金额
  calculateLegalAmounts()
  calculateYearAmounts()
}
/**
 * 根据任务列表长度展示项目
 * @param checkItem
 */
const showCheck = (checkItem) => {
  if (checkItem.inspectionNature == PressurePipeCheckType.REGULAR) {
    return formData.value.legalTaskList.length > 0
  }
  if (checkItem.inspectionNature == PressurePipeCheckType.ANNUAL) {
    return formData.value.yearTaskList.length > 0
  }
  return true
}

// 监听检验性质切换，按需查询项目
watch(() => formData.value.checkType, (newType, oldType) => {
  if (newType && newType !== oldType && !isOpening.value) {
    handleQueryCheckItemList(newType)
  }
})

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

// 根据检验类型获取设备数量
const getEquipCountByType = (type: string) => {
  if (type == 100) {
    return legalEquipCount.value
  } else if (type == 200) {
    return yearEquipCount.value
  }
  return 0
}

/** 更新 teamList */
const updateTeamList = (type) => {
  const checkerMap = {
    legal: legalSelectedCheckers,
    year: yearSelectedCheckers
  }

  const teamListMap = {
    legal: 'legalTeamList',
    year: 'yearTeamList',
  }

  // 按 groupTeamId 分组
  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 checkItemListCache = ref<Record<string, any[]>>({})
const isOpening = ref(false) // 标记弹窗是否正在打开，防止watch在数据未就绪时触发查询
const handleQueryCheckItemList = async (checkType?: string) => {
  const targetType = checkType || formData.value.checkType
  // 如果已缓存，直接使用缓存数据
  if (checkItemListCache.value[targetType]) {
    checkItemList.value = [
      ...checkItemList.value.filter(i => i.inspectionNature != targetType),
      ...checkItemListCache.value[targetType]
    ]
    return
  }

  // 校验所有选中的任务列表中的设备类型是否一致
  const allTasks = [
    ...formData.value.legalTaskList,
    ...formData.value.yearTaskList
  ]

  if (allTasks.length > 0) {
    const firstType = allTasks[0].pipeCategory
    const firstUnit = allTasks[0].unitId
    const hasDifferentType = allTasks.some(task => task.pipeCategory !== firstType)
    const hasDifferentUnit = allTasks.some(task => task.unitId !== firstUnit)

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

    if (hasDifferentUnit) {
      ElMessage.error('请选择同一单位设备')
      dialogVisible.value = false
      return
    }
    if (firstUnit){
      ClientUnitApi.getClientUnit(firstUnit).then(res => {
        formData.value.yearIsExempt = res.isExempt
        formData.value.legalIsExempt = res.isExempt
      })
    }
  }

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

  const type = Number(targetType) || targetType
  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: '300',
    nature: type
  })
  const inType = inspectionNatureType.list[0].type
  const newItems: any[] = []
  newItems.push({
    inspectionNatureName: PressurePipeCheckTypeMap[type] + " 法定收费项目",
    inspectionNature: type,
    type: '1',
    isExpanded: inType == 1,
    itemList: (queryResult || []).map((item) => (
      {
        ...item,
        isAutoAmount: '0',
        inspectionNature: type,
        type: '1',
        use: inType == 1 ? item.name === "一览表" ? true : item.use : false
      }
    ))
  });
  newItems.push({
    inspectionNatureName: PressurePipeCheckTypeMap[type] + " 服务收费项目",
    inspectionNature: type,
    type: '2',
    isExpanded: inType == 2,
    itemList: (queryResult || []).map((item) => (
      {
        ...item,
        isAutoAmount: '0',
        inspectionNature: type,
        type: '2',
        use: inType == 2 ? item.name === "一览表" ? true : item.use : false
      }
    ))
  });

  // 缓存当前类型的结果
  checkItemListCache.value[type] = newItems
  // 合并到 checkItemList
  checkItemList.value = [
    ...checkItemList.value.filter(i => i.inspectionNature != type),
    ...newItems
  ]
}

/** 切换检验项目展开/收缩状态 */
const toggleCheckItemCollapse = (checkItem: any) => {
  checkItem.isExpanded = !checkItem.isExpanded
}

/** 打开弹窗 */
const open = async (selectedLegalList?: EquipPipeSchedulingVO[], selectedYearList?: EquipPipeSchedulingVO[],checkType?) => {
  //console.log('open', props.selectedRows)
  isOpening.value = true
  dialogVisible.value = true


  // 重置所有检验员选择
  legalSelectedCheckers.value = []
  yearSelectedCheckers.value = []

  nextTick(() => {
    checkerLegalRef.value?.resetValidation()
    checkerYearRef.value?.resetValidation()
  })

  // 重置表单数据
  formData.value = {
    checkType: checkType || '100',
    // 定期检验
    legalDate: '',
    legalTeamList: [],
    legalTaskList: [],
    legalIsOrderConfirm: true,
    legalChargeType: '1',
    legalIsExempt: '0',
    legalShouldAmount: 0,
    legalServiceAmount: 0,
    legalReduceFee: 0,
    // 年度检查
    yearDate: '',
    yearTeamList: [],
    yearTaskList: [],
    yearIsOrderConfirm: true,
    yearChargeType: '1',
    yearIsExempt: '0',
    yearShouldAmount: 0,
    yearServiceAmount: 0,
    yearReduceFee: 0,
  }

  // 初始化 taskList
  formData.value.legalTaskList = selectedLegalList
  formData.value.yearTaskList = selectedYearList

  // 清空缓存和项目列表，只查询当前检验性质
  checkItemList.value = []
  checkItemListCache.value = {}
  await handleQueryCheckItemList(formData.value.checkType)
  isOpening.value = false

  // 初始化金额计算（等待checkItemList加载完成）
  setTimeout(() => {
    calculateLegalAmounts()
    calculateYearAmounts()
  }, 100)
}

/** 取消操作 */
const handleCancel = () => {
  dialogVisible.value = false
  checkItemList.value = []
  checkItemListCache.value = {}
  emit('close')
}

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

  submitLoading.value = true
  try {
    //验证（检验员改为非必选，任务单阶段才必选，故移除 CheckerSelect 的 validate 校验）
    await form.validate()

    // 组装新的数据结构
    const submitData: { taskList: any[]; source: number } = {
      taskList: [],
      source: props.source === 'pressure' ? 100 : 200
    }

    console.log("formData.value.legalTaskList", formData.value.yearTaskList)

    const legalUnitList = formData.value.legalTaskList.reduce((acc, item) => {
      const key = item.unitId;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(item)
      return acc;
    }, {})

    const yearUnitList = formData.value.yearTaskList.reduce((acc, item) => {
      const key = item.unitId;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(item)
      return acc;
    }, {})

    //console.log(Object.values(legalUnitList))

    console.log(formData.value.checkType);
    if (formData.value.checkType == '100') {
      Object.values(legalUnitList).forEach(item => {

        // 处理定期检验
        if (formData.value.legalDate && formData.value.legalTaskList.length > 0) {
          let actualAmount = 0
          checkItemList.value.find(i => i.inspectionNature == PressurePipeCheckType.REGULAR).itemList.filter(i => i.use).forEach(i => {
            actualAmount += i.fee
          })
          submitData.taskList.push({
            equipIds: item.map(item => item.equipPipeId).join(','),
            type: '100',
            hasOrderConfirm: isFrontDesk.value ? false : formData.value.legalIsOrderConfirm,
            date: formData.value.legalDate,
            teamList: formData.value.legalTeamList,
            pipeDetailList: item,
            chargeType: formData.value.legalChargeType,
            isExempt: formData.value.legalIsExempt,
            shouldAmount: formData.value.legalShouldAmount,
            serviceAmount: formData.value.legalServiceAmount,
            reduceFee: formData.value.legalReduceFee,
            actualAmount: actualAmount,
            checkItemList: [...checkItemList.value.filter(i => i.inspectionNature == PressurePipeCheckType.REGULAR)[0].itemList.filter(i => i.use).map(
              i => {
                return {
                  //reportId: i.templateId,
                  reportId: i.connectId,
                  newAmount: i.fee,
                  type: i.type,
                  feeCalculateJson: i.feeCalculateJson || '',
                  defaultCount: i.defaultCount || 1,
                  sort: i.sort || 0,
                }
              }
            ), ...checkItemList.value.filter(i => i.inspectionNature == PressurePipeCheckType.REGULAR)[1].itemList.filter(i => i.use).map(
              i => {
                return {
                  //reportId: i.templateId,
                  reportId: i.connectId,
                  newAmount: i.fee,
                  type: i.type,
                  feeCalculateJson: i.feeCalculateJson || '',
                  defaultCount: i.defaultCount || 1,
                  sort: i.sort || 0,
                }
              }
            )]
          })
        }
      })
    }
    if (formData.value.checkType == '200') {
      Object.values(yearUnitList).forEach(item => {
        // 处理年度检查
        if (formData.value.yearDate && formData.value.yearTaskList.length > 0) {
          let actualAmount = 0
          checkItemList.value.find(i => i.inspectionNature == PressurePipeCheckType.ANNUAL).itemList.filter(i => i.use).forEach(i => {
            actualAmount += i.fee
          })
          submitData.taskList.push({
            equipIds: item.map(item => item.equipPipeId).join(','),
            type: '200',
            hasOrderConfirm: isFrontDesk.value ? false : formData.value.yearIsOrderConfirm,
            date: formData.value.yearDate,
            teamList: formData.value.yearTeamList,
            pipeDetailList: item,
            chargeType: formData.value.yearChargeType,
            isExempt: formData.value.yearIsExempt,
            shouldAmount: formData.value.yearShouldAmount,
            serviceAmount: formData.value.yearServiceAmount,
            reduceFee: formData.value.yearReduceFee,
            actualAmount: actualAmount,
            checkItemList: [...checkItemList.value.filter(i => i.inspectionNature == PressurePipeCheckType.ANNUAL)[0].itemList.filter(i => i.use).map(
              i => {
                return {
                  //reportId: i.templateId,
                  reportId: i.connectId,
                  newAmount: i.fee,
                  type: i.type,
                  feeCalculateJson: i.feeCalculateJson || '',
                  defaultCount: i.defaultCount || 1,
                  sort: i.sort || 0,
                }
              }
            ), ...checkItemList.value.filter(i => i.inspectionNature == PressurePipeCheckType.ANNUAL)[1].itemList.filter(i => i.use).map(
              i => {
                return {
                  //reportId: i.templateId,
                  reportId: i.connectId,
                  newAmount: i.fee,
                  type: i.type,
                  feeCalculateJson: i.feeCalculateJson || '',
                  defaultCount: i.defaultCount || 1,
                  sort: i.sort || 0,
                }
              }
            )]

          })
        }
      })
    }

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


/**
 * 禁用内部日期
 * @param time
 * @return true 禁用 false 不禁用
 */
const disabledDatePlan = (time: Date) => {
  return time.getTime() > dayjs(legalLatestTime.value).valueOf();
}

// 向父组件暴露方法
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;
    }
  }
}

.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);
  cursor: pointer;
  user-select: none;
  transition: background-color 0.3s;

  &:hover {
    background-color: var(--el-color-primary-light-8);
  }

  .collapse-icon {
    margin-right: 8px;
    transition: transform 0.3s;
    font-size: 14px;

    &.is-collapsed {
      transform: rotate(-90deg);
    }
  }

  &::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;
  }
}
</style> 
