<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    :width="'800px'"
    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="!isBatch && checkType === 'in' || isBatch" class="plan-section">
            <div class="section-title">
              <span>内部检验</span>
              <span class="section-info">
                选中设备数量: {{ inEquipCount }} &nbsp;&nbsp; 最近临期时间: {{ inLatestTime=='无'?inLatestTime:dayjs(inLatestTime).format('YYYY-MM-DD') }}
              </span>
            </div>
            <el-form-item label="内检日期" prop="inDate">
              <el-date-picker
                v-model="formData.inDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                :disabled="formData.inNoSchedule"
                :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
                class="!w-240px"
              />
              <el-checkbox 
                v-if="isBatch"
                v-model="formData.inNoSchedule"
                class="ml-4" 
                @change="handleInNoScheduleChange"
                :disabled="isBatch ? inEquipCount === 0 : checkType !== 'in'"
              >
                无需安排
              </el-checkbox>
              <el-checkbox
                v-model="formData.inIsOrderConfirm"
                class="ml-4"
                :disabled="formData.inNoSchedule || nextInCheckCount === 0"
              >
                由前台约检确认
              </el-checkbox>
            </el-form-item>
            
            <el-form-item label="检验员" prop="inTeamList">
              <div class="flex items-center gap-2" :class="{ 'opacity-50': formData.inNoSchedule }">
                <div v-if="inSelectedCheckers.length > 0" class="selected-checkers">
                  <el-tag
                    v-for="checker in inSelectedCheckers"
                    :key="checker.memberId"
                    class="mx-1"
                    closable
                    @close="removeInChecker(checker.memberId)"
                  >
                    <span v-if="checker.isLeader" class="leader-tag">组</span>
                    {{ checker.member?.nickname }}
                  </el-tag>
                </div>
                <el-button 
                  type="primary" 
                  link 
                  @click="openCheckerSelect('in')"
                  :disabled="formData.inNoSchedule"
                >
                  选择检验员
                </el-button>
              </div>
            </el-form-item>
          </div>

          <!-- 外部检验配置 -->
          <div v-if="!isBatch && checkType === 'out' || isBatch" class="plan-section">
            <div class="section-title">
              <span>外部检验</span>
              <span class="section-info">
                选中设备数量: {{ outEquipCount }} &nbsp;&nbsp; 最近临期时间: {{ outLatestTime=='无'?outLatestTime:dayjs(outLatestTime).format('YYYY-MM-DD') }}
              </span>
            </div>
            <el-form-item label="外检日期" prop="outDate">
              <el-date-picker
                v-model="formData.outDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                :disabled="formData.outNoSchedule"
                :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
                class="!w-240px"
              />
              <el-checkbox 
                v-if="isBatch"
                v-model="formData.outNoSchedule"
                class="ml-4" 
                @change="handleOutNoScheduleChange"
                :disabled="isBatch ? outEquipCount === 0 : checkType !== 'out'"
              >
                无需安排
              </el-checkbox>
              <el-checkbox
                v-model="formData.outIsOrderConfirm"
                class="ml-4"
                :disabled="formData.outNoSchedule || nextOutCheckCount === 0"
              >
                由前台约检确认
              </el-checkbox>
            </el-form-item>
            
            <el-form-item label="检验员" prop="outTeamList">
              <div class="flex items-center gap-2" :class="{ 'opacity-50': formData.outNoSchedule }">
                <div v-if="outSelectedCheckers.length > 0" class="selected-checkers">
                  <el-tag
                    v-for="checker in outSelectedCheckers"
                    :key="checker.memberId"
                    class="mx-1"
                    closable
                    @close="removeOutChecker(checker.memberId)"
                  >
                    <span v-if="checker.isLeader" class="leader-tag">组</span>
                    {{ checker.member?.nickname }}
                  </el-tag>
                </div>
                <el-button 
                  type="primary" 
                  link 
                  @click="openCheckerSelect('out')"
                  :disabled="formData.outNoSchedule"
                >
                  选择检验员
                </el-button>
              </div>
            </el-form-item>
          </div>

          <!-- 耐压检验配置 -->
          <div v-if="!isBatch && checkType === 'pre' || isBatch" class="plan-section">
            <div class="section-title">
              <span>耐压检验</span>
              <span class="section-info">
                选中设备数量: {{ preEquipCount }} &nbsp;&nbsp; 最近临期时间: {{ preLatestTime=='无'?preLatestTime:dayjs(preLatestTime).format('YYYY-MM-DD') }}
              </span>
            </div>
            <el-form-item label="耐压检验日期" prop="preDate">
              <el-date-picker
                v-model="formData.preDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                :disabled="formData.preNoSchedule"
                :disabled-date="(time) => time.getTime() < Date.now() - 8.64e7"
                class="!w-240px"
              />
              <el-checkbox 
                v-if="isBatch"
                v-model="formData.preNoSchedule"
                class="ml-4" 
                @change="handlepreNoScheduleChange"
                :disabled="isBatch ? preEquipCount === 0 : checkType !== 'pre'"
              >
                无需安排
              </el-checkbox>
              <el-checkbox
                v-model="formData.pressureIsOrderConfirm"
                class="ml-4"
                :disabled="formData.preNoSchedule || nextPreCheckCount === 0"
              >
                由前台约检确认
              </el-checkbox>
            </el-form-item>
            
            <el-form-item label="检验员" prop="preTeamList">
              <div class="flex items-center gap-2" :class="{ 'opacity-50': formData.preNoSchedule }">
                <div v-if="preSelectedCheckers.length > 0" class="selected-checkers">
                  <el-tag
                    v-for="checker in preSelectedCheckers"
                    :key="checker.memberId"
                    class="mx-1"
                    closable
                    @close="removePreChecker(checker.memberId)"
                  >
                    <span v-if="checker.isLeader" class="leader-tag">组</span>
                    {{ checker.member?.nickname }}
                  </el-tag>
                </div>
                <el-button 
                  type="primary" 
                  link 
                  @click="openCheckerSelect('pre')"
                  :disabled="formData.preNoSchedule"
                >
                  选择检验员
                </el-button>
              </div>
            </el-form-item>
          </div>


          <!-- 检验项目 -->
          <div
            class="checkItemContent"
            v-for="checkItem in checkItemList"
            v-show="showCheck(checkItem)"
            :key="checkItem.inspectionNature"
          >
            <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 < 2
                        ? `repeat(${checkItem.itemList.length}, 1fr)`
                        : `repeat(2, 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.inspectionNature,item.templateId)
                      }"
                      >费用：{{ item.fee || '无' }}</el-button
                      >
                      <!--                      >费用：{{ getCheckItemFeeType(item) }}</el-button-->
                      )
                    </span>
                  </div>

                </div>
              </template>
              <el-empty style="height: 200px;" v-else :description="`暂无【${checkItem.inspectionNatureName}】检验项目`" />
            </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>
    <!-- 费用计算弹窗 -->
    <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
      v-model="checkerSelectVisible"
      :title="checkerSelectTitle"
      append-to-body
      width="600px"
    >
      <CheckerSelect
        v-model="currentSelectedCheckers"
        @change="handleCheckerChange"
        :max="100"
      />
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="checkerSelectVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCheckerSelect">确定</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/components/CheckerSelect/index.vue'
import type { CheckerItem } from '@/views/pressure2/components/CheckerSelect'
import {BoilerPlanSchedulingEquipEditVO,EquipBoilerSchedulingApi} from "@/api/pressure2/equipboilerscheduling";
import dayjs from "dayjs";
import {PressureBoilerCheckType, PressureBoilerCheckTypeMap} from "@/utils/constants";
import {EquipBoilerApi} from "@/api/pressure2/equipboiler";
import {BoilerTaskOrderApi} from "@/api/pressure2/boilertaskorder";

const message = useMessage()

const props = defineProps({
  equipInfo: {
    type: Object as PropType<BoilerPlanSchedulingEquipEditVO>,
    required: false
  },
  equipList: {
    type: Array as PropType<BoilerPlanSchedulingEquipEditVO[]>,
    default: () => []
  },
  checkType: {
    type: String as PropType<'in' | 'out' | 'pre' | ''>,
    default: ''
  },
  isBatch: {
    type: Boolean,
    default: false
  }
})
const {querySchedulingCheckItemList } = BoilerTaskOrderApi
const emit = defineEmits(['success', 'close'])

const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const submitLoading = ref(false) // 提交按钮 loading

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

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

// 检验员选择弹窗相关
const checkerSelectVisible = ref(false)
const currentSelectType = ref('')  // 当前选择的检验类型: in/out/pre
const currentSelectedCheckers = ref<CheckerItem[]>([])
const tempSelectedCheckers = ref<CheckerItem[]>([])  // 临时存储选择的检验员

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

const checkerSelectTitle = computed(() => {
  const typeMap = {
    in: '内部检验',
    out: '外部检验',
    pre: '耐压检验'
  }
  return `选择${typeMap[currentSelectType.value]}检验员`
})

const formData = ref({
  // 内部检验
  inDate: '',
  inNoSchedule: false,
  inTeamList: [],
  inIsOrderConfirm: true,
  
  // 外部检验
  outDate: '',
  outNoSchedule: false,
  outTeamList: [],
  outIsOrderConfirm: true,
  
  // 耐压检验
  preDate: '',
  preNoSchedule: false,
  preTeamList: [],
  pressureIsOrderConfirm: true
})

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

// 计算内部检验设备数量和最近临检时间
const inEquipCount = computed(() => {
  if (!props.isBatch) return props.equipInfo?.nextInCheckDate ? 1 : 0
  return props.equipList.filter(item => item.nextInCheckDate).length
})

const inLatestTime = computed(() => {
  if (!props.isBatch) return props.equipInfo?.nextInCheckDate || '无'
  const dates = props.equipList
    .map(item => item.nextInCheckDate)
    .filter(date => date)
    .sort((a, b) => {
      const dateA = new Date(a)
      const dateB = new Date(b)
      return dateA.getTime() - dateB.getTime()
    })
  return dates.length > 0 ? dayjs(dates[0]).format('YYYY-MM-DD') : '无'
})

// 计算外部检验设备数量和最近临检时间
const outEquipCount = computed(() => {
  if (!props.isBatch) return props.equipInfo?.nextOutCheckDate ? 1 : 0
  return props.equipList.filter(item => item.nextOutCheckDate).length
})

const outLatestTime = computed(() => {
  if (!props.isBatch) return props.equipInfo?.nextOutCheckDate || '无'
  const dates = props.equipList
    .map(item => item.nextOutCheckDate)
    .filter(date => date)
    .sort((a, b) => {
      const dateA = new Date(a)
      const dateB = new Date(b)
      return dateA.getTime() - dateB.getTime()
    })
  return dates.length > 0 ? dayjs(dates[0]).format('YYYY-MM-DD') : '无'
})

// 计算耐压检验设备数量和最近临检时间
const preEquipCount = computed(() => {
  if (!props.isBatch) return props.equipInfo?.nextPressureCheckDate ? 1 : 0
  return props.equipList.filter(item => item.nextPressureCheckDate).length
})

const preLatestTime = computed(() => {
  if (!props.isBatch) return props.equipInfo?.nextPressureCheckDate || '无'
  const dates = props.equipList
    .map(item => item.nextPressureCheckDate)
    .filter(date => date)
    .sort((a, b) => {
      const dateA = new Date(a)
      const dateB = new Date(b)
      return dateA.getTime() - dateB.getTime()
    })
  return dates.length > 0 ? dayjs(dates[0]).format('YYYY-MM-DD') : '无'
})

/** 打开检验员选择弹窗 */
const openCheckerSelect = (type) => {
  currentSelectType.value = type
  checkerSelectVisible.value = true
  
  // 根据类型设置当前选中的检验员
  const checkerMap = {
    in: inSelectedCheckers,
    out: outSelectedCheckers,
    pre: preSelectedCheckers
  }
  tempSelectedCheckers.value = [...checkerMap[type].value]
  currentSelectedCheckers.value = [...tempSelectedCheckers.value]
}

/** 处理检验员变化 */
const handleCheckerChange = (checkers) => {
  tempSelectedCheckers.value = checkers
}

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

  let item = checkItemList.value.find(item => item.inspectionNature == inspectionNature).itemList.find(i => i.templateId == templateId)
  feeInspectionNature.value = inspectionNature
  feeTemplateId.value = templateId

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

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

/**
 * 根据无需安排展示项目
 * @param checkItem
 */
const showCheck = (checkItem) =>{
  if (checkItem.inspectionNature == PressureBoilerCheckType.IN){
    return !formData.value.inNoSchedule
  }
  if (checkItem.inspectionNature == PressureBoilerCheckType.OUT){
    return !formData.value.outNoSchedule
  }
  if (checkItem.inspectionNature == PressureBoilerCheckType.PRESSURE){
    return !formData.value.preNoSchedule
  }
  return true
}

// 查询项目列表
const handleQueryCheckItemList = async () => {
  const req = []
  if (props.equipList.length > 0){
    for (const item of props.equipList) {
      req.push(item.id)
    }
  }else {
    req.push(props.equipInfo.id)
  }
  const equipIds = await EquipBoilerApi.getNameByIds(req)
  checkItemList.value = []
  const checkTypes = [
    PressureBoilerCheckType.IN,
    PressureBoilerCheckType.OUT,
    PressureBoilerCheckType.PRESSURE
  ];

  for (const type of checkTypes) {
    const params = {
      orderId: "0",
      itemIds: equipIds.map(item => item.id),
      equipmentCategory: 300,
      inspectionNature: [type]
    };
    const queryResult = await querySchedulingCheckItemList(params);
    checkItemList.value.push({
      inspectionNatureName: PressureBoilerCheckTypeMap[type],
      inspectionNature: type,
      itemList: (queryResult || []).map((item) => (
        {
          ...item,
          isAutoAmount: '0', // 批量模式下默认为'0'
          inspectionNature: type,
          use: item.use
        }
      ))
    });
  }

}

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

watch(() => formData.value.outDate, (newDate) => {
  if (newDate && props.isBatch) {
    if (!formData.value.inDate && !formData.value.inNoSchedule) {
      formData.value.inDate = newDate
    }
    if (!formData.value.preDate && !formData.value.preNoSchedule) {
      formData.value.preDate = newDate
    }
  }
})

watch(() => formData.value.preDate, (newDate) => {
  if (newDate && props.isBatch) {
    if (!formData.value.inDate && !formData.value.inNoSchedule) {
      formData.value.inDate = newDate
    }
    if (!formData.value.outDate && !formData.value.outNoSchedule) {
      formData.value.outDate = newDate
    }
  }
})

/** 监听检验员变化 */
const syncCheckers = (sourceType: string, checkers: any[]) => {
  if (!props.isBatch) return
  
  const typeMap = {
    in: ['out', 'pre'],
    out: ['in', 'pre'],
    pre: ['in', 'out']
  }
  
  typeMap[sourceType].forEach(type => {
    const noScheduleKey = `${type}NoSchedule`
    const checkerMap = {
      in: inSelectedCheckers,
      out: outSelectedCheckers,
      pre: preSelectedCheckers
    }
    // 只有在未选择检验员且未勾选"无需安排"的情况下才自动同步
    if (!formData.value[noScheduleKey] && checkerMap[type].value.length === 0) {
      checkerMap[type].value = [...checkers]
      updateTeamList(type)
    }
  })
}

/** 修改 confirmCheckerSelect 方法 */
const confirmCheckerSelect = () => {
  const checkerMap = {
    in: inSelectedCheckers,
    out: outSelectedCheckers,
    pre: preSelectedCheckers
  }
  
  // 更新对应类型的检验员列表
  checkerMap[currentSelectType.value].value = [...tempSelectedCheckers.value]
  
  // 同步到其他类型（仅在批量模式下）
  if (props.isBatch) {
    syncCheckers(currentSelectType.value, tempSelectedCheckers.value)
  }
  
  // 更新 formData 中的 teamList
  const teamListMap = {
    in: 'inTeamList',
    out: 'outTeamList',
    pre: 'preTeamList'
  }
  
  // 按 groupTeamId 分组
  const groupedTeams = tempSelectedCheckers.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[currentSelectType.value]] = Object.values(groupedTeams)
  checkerSelectVisible.value = false
}

/** 移除检验员 */
const removeInChecker = (memberId) => {
  inSelectedCheckers.value = inSelectedCheckers.value.filter(c => c.memberId !== memberId)
  updateTeamList('in')
}

const removeOutChecker = (memberId) => {
  outSelectedCheckers.value = outSelectedCheckers.value.filter(c => c.memberId !== memberId)
  updateTeamList('out')
}

const removePreChecker = (memberId) => {
  preSelectedCheckers.value = preSelectedCheckers.value.filter(c => c.memberId !== memberId)
  updateTeamList('pre')
}

/** 更新 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 open = () => {
  dialogVisible.value = true
  
  // 使用 nextTick 确保获取到最新的 props 值
  nextTick(() => {
    // 重置所有检验员选择
    inSelectedCheckers.value = []
    outSelectedCheckers.value = []
    preSelectedCheckers.value = []
    handleQueryCheckItemList()
    // 重置表单数据
    formData.value = {
      inDate: '',
      inNoSchedule: false,
      inTeamList: [],
      inIsOrderConfirm: true,
      outDate: '',
      outNoSchedule: false,
      outTeamList: [],
      outIsOrderConfirm: true,
      preDate: '',
      preNoSchedule: false,
      preTeamList: [],
      pressureIsOrderConfirm: true
    }

    // 根据实际情况设置无需安排的状态
    if (props.isBatch) {
      formData.value.inNoSchedule = inEquipCount.value === 0
      formData.value.outNoSchedule = outEquipCount.value === 0
      formData.value.preNoSchedule = preEquipCount.value === 0
    } else {
      // 单设备模式下，根据检验类型来判断
      formData.value.inNoSchedule = props.checkType !== 'in'
      formData.value.outNoSchedule = props.checkType !== 'out'
      formData.value.preNoSchedule = props.checkType !== 'pre'
    }
  })
}

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

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

  submitLoading.value = true
  try {
    await form.validate()

    // 组装新的数据结构
    const submitData: { taskList: any[] } = {
      taskList: []
    }

    // 获取设备ID列表
    const inEquipIds = props.isBatch
      ? props.equipList.filter(item => item.nextInCheckDate).map(item => item.id).join(',')
      : props.equipInfo?.id
    
    const outEquipIds = props.isBatch
      ? props.equipList.filter(item => item.nextOutCheckDate).map(item => item.id).join(',')
      : props.equipInfo?.id
      
    const preEquipIds = props.isBatch
      ? props.equipList.filter(item => item.nextPressureCheckDate).map(item => item.id).join(',')
      : props.equipInfo?.id
    
    // 处理定期检验
    if (!formData.value.inNoSchedule && formData.value.inDate && inEquipIds) {
      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: inEquipIds,
        type: '100',
        hasOrderConfirm: formData.value.inIsOrderConfirm,
        date: formData.value.inDate,
        teamList: formData.value.inTeamList,
        actualAmount,
        checkItemList: checkItemList.value.find(i => i.inspectionNature == PressureBoilerCheckType.IN).itemList.filter(i => i.use).map(
          i => {
            return {
              //reportId: i.templateId,
              reportId: i.connectId,
              newAmount: i.fee
            }
          }
        )
      })
    }
    
    // 处理年度检查
    if (!formData.value.outNoSchedule && formData.value.outDate && outEquipIds) {
      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: outEquipIds,
        type: '200',
        hasOrderConfirm: formData.value.outIsOrderConfirm,
        date: formData.value.outDate,
        teamList: formData.value.outTeamList,
        actualAmount,
        checkItemList: checkItemList.value.find(i => i.inspectionNature == PressureBoilerCheckType.OUT).itemList.filter(i => i.use).map(
          i => {
            return {
              //reportId: i.templateId,
              reportId: i.connectId,
              newAmount: i.fee
            }
          }
        )
      })
    }
    
    // 处理超年限检验
    if (!formData.value.preNoSchedule && formData.value.preDate && preEquipIds) {
      let actualAmount = 0
      checkItemList.value.find(i => i.inspectionNature == PressureBoilerCheckType.PRESSURE).itemList.filter(i => i.use).forEach(i => {
        actualAmount += i.fee
      })
      submitData.taskList.push({
        equipIds: preEquipIds,
        type: '300',
        hasOrderConfirm: formData.value.pressureIsOrderConfirm,
        date: formData.value.preDate,
        teamList: formData.value.preTeamList,
        actualAmount,
        checkItemList: checkItemList.value.find(i => i.inspectionNature == PressureBoilerCheckType.PRESSURE).itemList.filter(i => i.use).map(
          i => {
            return {
              //reportId: i.templateId,
              reportId: i.connectId,
              newAmount: i.fee
            }
          }
        )
      })
    }

    //console.log(submitData)

    await EquipBoilerSchedulingApi.planSchedulingAssign(submitData)
    message.success('保存成功')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    message.error('保存失败')
  } finally {
    submitLoading.value = false
  }
}

// 处理"无需安排"变化
const handleInNoScheduleChange = (val: boolean) => {
  if (val) {
    formData.value.inDate = ''
    inSelectedCheckers.value = []
    formData.value.inTeamList = []
  }
}

const handleOutNoScheduleChange = (val: boolean) => {
  if (val) {
    formData.value.outDate = ''
    outSelectedCheckers.value = []
    formData.value.outTeamList = []
  }
}

const handlepreNoScheduleChange = (val: boolean) => {
  if (val) {
    formData.value.preDate = ''
    preSelectedCheckers.value = []
    formData.value.preTeamList = []
  }
}

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

.selected-checkers {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px;
  
  .el-tag {
    margin: 0;
    
    &:hover {
      cursor: default;
    }
  }
}

.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;
}


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