<template>
  <CustomDialog
    :model-value="modelValue"
    title="选择检验项目"
    width="80%"
    :before-close="handleClose"
    class="AddOrEditCheckItemForEquipmentDialog"
  >
    <el-tabs v-model="activeName">
      <el-tab-pane label="选择检验项目" name="selectCheckItem">
        <el-form :model="queryParams" ref="queryFormRef" class="view-info-form">
          <el-form-item label="设备类型" prop="equipmentCategory">
            <span class="info-text">{{ PressureBoilerEquipTypeMap[String(queryParams.equipmentCategory)] || '-' }}</span>
          </el-form-item>
          <el-form-item label="检验性质" prop="inspectionNature">
            <span class="info-text">{{ 
              Array.isArray(queryParams.inspectionNature) 
                ? queryParams.inspectionNature
                    .map(val => filterPressureBoilerCheckTypeMap[String(val)])
                    .filter(Boolean)
                    .join('、')
                : (filterPressureBoilerCheckTypeMap[String(queryParams.inspectionNature)] || '-')
            }}</span>
          </el-form-item>
          <el-form-item label="新增费用">

            <div class="flex items-center gap-4 mb-2">
              <span class="text-gray-600">应收法定金额: {{ formData.shouldAmount }}</span>
              <span class="text-gray-600">服务收费金额: {{ formData.serviceAmount }}</span>
              <span class="text-gray-600">免征费用: {{ formData.reduceFee }}</span>
            </div>
          </el-form-item>
        </el-form>
        <div class="checkItemContentWrapper" v-loading="checkItemListLoading">
          <div
            class="checkItemContent"
            v-for="checkItem in checkItemList"
            :key="checkItem.inspectionNature"
          >
            <div class="content-title">
              {{ checkItem.inspectionNatureName }}
            </div>
            <div class="inspection-grid">
              <!-- 标题行 -->
              <div class="grid-header">检验项目</div>
              <template v-if="checkItem.itemList.length > 0">
                <!-- Grid 容器 -->
                <div
                  class="grid-container"
                  :style="{
                    'grid-template-columns':
                      checkItem.itemList.length < 5
                        ? `repeat(${checkItem.itemList.length}, 1fr)`
                        : `repeat(5, 1fr)`
                  }"
                >
                  <!-- 循环渲染子项（模拟数据） -->
                  <div class="grid-item" v-for="(item, index) in checkItem.itemList" :key="index">
<!--                    <el-checkbox-->
<!--                      :disabled="selectedIds.includes(item.templateId) && item.reportType === 100"-->
<!--                      v-model="item.use"-->
<!--                      @change="(val) => handleCheckItemSelectedChange(item, val)"-->
<!--                    />-->
                    <el-checkbox
                      :disabled="item.isMainProject === '1'"
                      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>
                    <template
                      v-if="
                        true
                      "
                    >
                      (
                      <el-button link type="primary" @click="() => handleInputCalcField(item)"
                      >费用：{{ getCheckItemFeeType(item) }}</el-button
                      >
                      )
                    </template>
                  </div>
                </div>
              </template>
              <el-empty v-else :description="`暂无【${checkItem.inspectionNatureName}】检验项目`" />
            </div>
          </div>
        </div>
        <div class="checker-box">
          检验员：
          <span>{{
              !currentSelectedChecker ? '-' : currentSelectedChecker?.member?.nickname
            }}</span>
          <el-button type="primary" link @click="handleSelectedNewChecker">请选择</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="检验意见通知书" name="checkNotice">
        <div class="checkItemContentWrapper" v-loading="checkItemListLoading">
          <div class="checkItemContent">
            <div class="inspection-grid">
              <div class="grid-header">检验意见通知书</div>
              <template v-if="reportCheckNoticeTemplateList.length > 0">
                <div
                  class="grid-container"
                  :style="{
                    'grid-template-columns':
                      reportCheckNoticeTemplateList.length < 5
                        ? `repeat(${reportCheckNoticeTemplateList.length}, 1fr)`
                        : `repeat(5, 1fr)`
                  }"
                >
                  <div
                    class="grid-item"
                    v-for="(item, index) in reportCheckNoticeTemplateList"
                    :key="item.id + index"
                  >
                    <el-checkbox
                      :disabled="item.disabled"
                      v-model="item.use"
                      @change="(val) => handleJobGuideSelectedChange(item, val)"
                    />
                    <span>{{ item.reportName }}</span>
                  </div>
                </div>
              </template>
              <el-empty v-else :description="`暂无【检验意见通知书】`" />
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="作业指导书" name="jobGuide">
        <div class="checkItemContentWrapper" v-loading="checkItemListLoading">
          <div class="checkItemContent">
            <div class="inspection-grid">
              <div class="grid-header">作业指导书</div>
              <template v-if="jobGuideList.length > 0">
                <div
                  class="grid-container"
                  :style="{
                    'grid-template-columns':
                      jobGuideList.length < 5
                        ? `repeat(${jobGuideList.length}, 1fr)`
                        : `repeat(5, 1fr)`
                  }"
                >
                  <!-- 循环渲染子项（模拟数据） -->
                  <div
                    class="grid-item"
                    v-for="(item, index) in jobGuideList"
                    :key="item.id + index"
                  >
                    <el-checkbox
                      :disabled="item.disabled"
                      v-model="item.use"
                      @change="(val) => handleJobGuideSelectedChange(item, val)"
                    />
                    <span>{{ item.reportName }}</span>
                  </div>
                </div>
              </template>
              <el-empty v-else :description="`暂无【作业指导书】`" />
            </div>
          </div>
        </div>
      </el-tab-pane>
<!--      <el-tab-pane label="检验方案" name="checkScheme">-->
<!--        <div class="checkItemContentWrapper" v-loading="checkItemListLoading">-->
<!--          <div class="checkItemContent">-->
<!--            <div class="inspection-grid">-->
<!--              <div class="grid-header">检验方案</div>-->
<!--              <template v-if="checkSchemeList.length > 0">-->
<!--                <div-->
<!--                  class="grid-container"-->
<!--                  :style="{-->
<!--                    'grid-template-columns':-->
<!--                      checkSchemeList.length < 5-->
<!--                        ? `repeat(${checkSchemeList.length}, 1fr)`-->
<!--                        : `repeat(5, 1fr)`-->
<!--                  }"-->
<!--                >-->
<!--                  &lt;!&ndash; 循环渲染子项（模拟数据） &ndash;&gt;-->
<!--                  <div-->
<!--                    class="grid-item"-->
<!--                    v-for="(item, index) in checkSchemeList"-->
<!--                    :key="item.id + index"-->
<!--                  >-->
<!--                    <el-checkbox-->
<!--                      :disabled="item.disabled"-->
<!--                      v-model="item.use"-->
<!--                      @change="(val) => handleJobGuideSelectedChange(item, val)"-->
<!--                    />-->
<!--                    <span>{{ item.reportName }}</span>-->
<!--                  </div>-->
<!--                </div>-->
<!--              </template>-->
<!--              <el-empty v-else :description="`暂无【检验方案】`" />-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </el-tab-pane>-->
    </el-tabs>
    <template #footer>
      <el-button type="primary" :loading="loading" @click="handleConfirm">确认</el-button>
      <el-button @click="handleClose">取消</el-button>
    </template>
  </CustomDialog>
  <Teleport to="body">
    <!-- 费用计算弹窗 -->
    <calcCheckItemFee
      v-if="showCalcCheckItemFeeDialog"
      v-model="showCalcCheckItemFeeDialog"
      :equipmentId="equipmentIds.length === 1 ? equipmentIds[0] : ''"
      :templateInfo="calcTemplateInfo"
      :isBatch="isBatch"
      @save="handleSaveCalcFee"
    />
  </Teleport>

  <!-- 检验员选择弹窗 -->
  <CustomDialog
    v-if="checkerSelectVisible"
    v-model="checkerSelectVisible"
    title="选择检验员"
    append-to-body
    width="600px"
    class="AddOrEditCheckItemForEquipmentDialog"
  >
    <CheckerSelect
      v-model="currentSelectedCheckerIds"
      :max="1"
      @change="handleInspectionItemCheckerChange"
    />
    <template #footer>
      <el-button @click="checkerSelectVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmCheckerSelect">确定</el-button>
    </template>
  </CustomDialog>
</template>
<script setup lang="ts">
import CustomDialog from '@/components/CustomDialog/index.vue'
import calcCheckItemFee from './calcCheckItemFee.vue'
import CheckerSelect from '@/views/pressure2/equipboilerscheduling/components/CheckerSelect.vue'
import { PressureBoilerCheckTypeMap, PressureReportType } from '@/utils/constants'
import { ReportItemVO, BoilerTaskOrderApi } from '@/api/pressure2/boilertaskorder'
import { useUserStore } from '@/store/modules/user'
import { is, isEmpty } from '@/utils/is'
import {
  getCheckSchemeList,
  getPressureReportTemplateListNoLimit
} from '@/api/pressure2/reportTemplate' // 承压报告模板
import { ElForm } from 'element-plus'
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";

const { queryCheckItemList } = BoilerTaskOrderApi

//锅炉类型
const PressureBoilerEquipType = {
  BOILER: 300
}
const PressureBoilerEquipTypeMap = {
  [PressureBoilerEquipType.BOILER]: '锅炉'
}

const userStore = useUserStore()
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  orderInfo: {
    type: Object as PropType<Recordable>,
    default: () => ({})
  },
  selectedIds: {
    type: Array,
    default: () => []
  },
  equipmentIds: {
    type: Array as PropType<string[]>,
    default: () => []
  },
  orderItemIds: {
    type: Array as PropType<string[]>,
    default: () => []
  },
  taskOrderItem: {
    type: Object,
    default: () => ({})
  },
  reportList: {
    type: Array as PropType<(ReportItemVO & OtherParams)[]>,
    default: () => [] as (ReportItemVO & OtherParams)[]
  },
  allReportList: {
    type: Array as PropType<(ReportItemVO & OtherParams)[]>,
    default: () => [] as (ReportItemVO & OtherParams)[]
  },
  // 任务单批量添加
  isBatch: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'refresh'])
type ActiveName = 'selectCheckItem' | 'checkNotice' | 'jobGuide' | 'checkScheme' | 'subProject'
const activeName = ref<ActiveName>('selectCheckItem')

const formData = ref({
  shouldAmount:0,
  serviceAmount:0,
  reduceFee:0
})

const filterPressureBoilerCheckTypeMap = computed(() => {
  return Object.fromEntries(
    Object.entries(PressureBoilerCheckTypeMap).filter(([value, label]) => {
      return value
    })
  )
})
// 是否为检验录入页面
//const isCheckInputPage = computed(() => route.name === 'CheckerTaskDetail')

const currentSelectedCheckerIds = ref<string[]>([])
// 查询参数
const queryParams = ref<Recordable>({
  equipmentCategory: 300,
  inspectionNature: []
})

const subProjectFormRef = ref<InstanceType<typeof ElForm>>()
const subProjectParams = ref<Recordable>({
  subcontractedName: '',
  fee: undefined,
  fileList: []
})

const isSubProjectAddChecker = ref(false)

const checkItemList = ref<any[]>([])
const selectedCheckItem = ref<any[]>([])
const getCheckItemFeeType = computed(() => {
  return ({ isAutoAmount, fee }) => {
    if (is(fee, 'Number')) return fee
    else if (is(fee, 'Null') && isAutoAmount === '1') return '录入计算'
    else return '无'
  }
})
// 复选框的变化
const handleCheckItemSelectedChange = (checkItem, selected) => {
  if (
    selected &&
    selectedCheckItem.value.findIndex((item) => item.templateId === checkItem.templateId) < 0
  ) {
    selectedCheckItem.value.push(checkItem)
  } else if (
    !selected &&
    selectedCheckItem.value.findIndex((item) => item.templateId === checkItem.templateId) >= 0
  ) {
    const index = selectedCheckItem.value.findIndex(
      (item) => item.templateId === checkItem.templateId
    )

    selectedCheckItem.value.splice(index, 1)
  }
  calculateAmounts()
}

const checkItemListLoading = ref(false)
// 查询项目列表
const handleQueryCheckItemList = async (checkType) => {
  // 获取统一的设备类型，如果列表为空则设为 undefined
  const equipType = props.orderInfo.orderItems?.length > 0 ? props.orderInfo?.orderItems[0].type : props.taskOrderItem.type
  const params = {
    orderId: props.orderInfo?.id,
    itemIds: props.equipmentIds,
    equipmentCategory: queryParams.value.equipmentCategory,
    inspectionNature: [checkType],
    equipType:equipType
  }
  const queryResult = await queryCheckItemList(params)
  //console.log(queryResult)
  checkItemList.value.push({
    inspectionNatureName: filterPressureBoilerCheckTypeMap.value[checkType] + " 法定收费项目",
    inspectionNature: checkType,
    type: '1',
    itemList: (queryResult || []).map((item) => ({
      ...item,
      isAutoAmount: props.isBatch ? '0' : item.isAutoAmount,
      inspectionNature: checkType,
      // use: props.equipmentIds.length > 1 ? false : props.selectedIds.includes(item.templateId) && item.reportType === 100
      //use: props.selectedIds.includes(item.templateId)
      use:false,
      type: '1'
    }))
  })
  checkItemList.value.push({
    inspectionNatureName: filterPressureBoilerCheckTypeMap.value[checkType] + " 服务收费项目",
    inspectionNature: checkType,
    type: '2',
    itemList: (queryResult || []).map((item) => ({
      ...item,
      isAutoAmount: props.isBatch ? '0' : item.isAutoAmount,
      inspectionNature: checkType,
      // use: props.equipmentIds.length > 1 ? false : props.selectedIds.includes(item.templateId) && item.reportType === 100
      //use: props.selectedIds.includes(item.templateId)
      use:false,
      type: '2'
    }))
  })
}

// 获取检验意见通知书模板内容
const reportCheckNoticeTemplateList = ref<any[]>([])
const getReportCheckNoticeTemplateList = async () => {
  const params = {
    type: '3',
    pageNo: 1,
    pageSize: 100,
    status: 200,
    reportType : 400
  }
  getPressureReportTemplateListNoLimit(params)
    .then((res) => {
      reportCheckNoticeTemplateList.value = res.map((item) => ({
        ...item,
        reportName: item.tbName,
        disabled: props.selectedIds.includes(item.id),
        use: props.selectedIds.includes(item.id)
      }))
    })
    .catch(() => {
      reportCheckNoticeTemplateList.value = []
      console.log('获取检验意见通知书模板内容失败')
    })
}

// 获取检验方案列表
const orderReportIdList = ref<string[]>([])
const getCheckSchemeData = async () => {
  const params = {
    taskStatus: 800,
    orderId: props.orderInfo?.id
  }
  getCheckSchemeList(params)
    .then((res) => {
      const { list = [] } = res
      // console.log('list:log', list)
      // 已经存在的检验方案主键id
      // console.log('orderReportIdList', props)
      // orderReportIdList.value = (props.allReportList
      //   .filter((x) => x.reportType === PressureReportType['INSPECTIONPLAN'] && x.orderReportId)
      //   .map((item) => item.orderReportId) as string[])
      checkSchemeList.value = list
        .filter((x) => x.reportType === PressureReportType['INSPECTIONPLAN'])
        .map((v) => {
          return {
            ...v,
            disabled: props.selectedIds.includes(v.templateId),
            use: props.selectedIds.includes(v.templateId)
          }
        })
    })
    .catch(() => {
      reportCheckNoticeTemplateList.value = []
      console.log('获取检验意见通知书模板内容失败')
    })
}

watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      getReportCheckNoticeTemplateList()
      getCheckSchemeData()
    }
  },
  {
    immediate: true
  }
)

watch(
  () => [props.orderInfo, props.equipmentIds],
  ([orderInfo, equipmentIds]: [Recordable, string[]]) => {
    if (!Object.keys(orderInfo).length || !equipmentIds.length) return
    queryParams.value.inspectionNature = [orderInfo?.checkType]
  },
  {
    immediate: true
  }
)

// 检验性质发生改变之后，获取检验项目列表
watch(
  () => queryParams.value.inspectionNature,
  async (inspectionNature) => {
    checkItemList.value = []
    if (inspectionNature.length === 0) {
      return
    }
    checkItemListLoading.value = true
    for (const checkType of inspectionNature) {
      await handleQueryCheckItemList(checkType)
    }
    checkItemListLoading.value = false
  },
  {
    immediate: true
  }
)

// 计算费用弹窗
const showCalcCheckItemFeeDialog = ref(false)
const calcTemplateInfo = ref({})
const handleInputCalcField = (item) => {
  showCalcCheckItemFeeDialog.value = true
  calcTemplateInfo.value = item
}
// 保存费用计算回调
const handleSaveCalcFee = (templateInfo) => {
  for (const checkItem of checkItemList.value) {
    if (checkItem.inspectionNature !== templateInfo.inspectionNature) continue
    for (const item of checkItem.itemList) {
      if (item.templateId !== templateInfo.templateId) continue
      item.fee = templateInfo.fee
    }
  }
  calculateAmounts()
}

const calculateAmounts = () => {

  // 分离法定收费项目和服务收费项目
  const find = checkItemList?.value.find(item => item.type === '1');
  if (!find) return;
  const statutoryItems = find.itemList.filter(item => item.use)
  const find1 = checkItemList?.value.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 * (item.quantity || 1) || 0), 0)
  // 计算服务收费金额总和
  const totalServiceAmount = serviceItems.reduce((sum, item) => sum + (item.fee * (item.quantity || 1) || 0), 0)

  if (props.orderInfo.feeNature === '1') {
    // 免征：免征费用=应收法定金额，应收法定金额=0
    formData.value.reduceFee = totalStatutoryAmount
    formData.value.shouldAmount = 0
  } else {
    // 不免征：免征费用=0，应收法定金额=总金额
    formData.value.reduceFee = 0
    formData.value.shouldAmount = totalStatutoryAmount
  }

  formData.value.serviceAmount = totalServiceAmount
}

// 选择检验员
const checkerSelectVisible = ref(false)
const currentSelectedChecker = ref<any>(null)
const tempSaveCheckerInfo = ref(null)
const handleInspectionItemCheckerChange = (checkerInfo) => {
  //console.log('checkerInfo:log', checkerInfo)
  // tempSaveCheckerInfo.value = checkerInfo?.[0]?.member
  tempSaveCheckerInfo.value = checkerInfo?.[0]
}

const handleSelectedNewChecker = () => {
  checkerSelectVisible.value = true
}

const confirmCheckerSelect = () => {
  // 分包项目进行区分
  if (isSubProjectAddChecker.value) {
    subProjectParams.value.subSelectedChecker = tempSaveCheckerInfo.value
  } else {
    currentSelectedChecker.value = tempSaveCheckerInfo.value
  }
  isSubProjectAddChecker.value = false
  checkerSelectVisible.value = false
}

// [PressureReportType['WORKINSTRUCTION'], PressureReportType['INSPECTIONPLAN']]
// 作业指导书列表
type OtherParams = { use: boolean; disabled: boolean; orderReportId?: string }
const jobGuideList = ref<(ReportItemVO & OtherParams)[]>([])
const handleJobGuideSelectedChange = (item, val) => {}
// 检验方案列表
const checkSchemeList = ref<(ReportItemVO & OtherParams)[]>([])
watch(
  () => [props.allReportList, props.selectedIds],
  ([allReportList, selectedIds]: [ReportItemVO[], string[]]) => {
    //@ts-ignore
    jobGuideList.value = allReportList
      .filter((x) => x.reportType === PressureReportType['WORKINSTRUCTION'])
      .map((v) => ({
        ...v,
        disabled: selectedIds.includes(v.templateId || v.id),
        use: selectedIds.includes(v.templateId || v.id)
      }))
  },
  {
    immediate: true
  }
)

onMounted(() => {
  currentSelectedChecker.value = userStore.getUser
})

// 关闭弹窗
const handleClose = () => {
  emit('update:modelValue', false)
}
const checkNoticeBookConfirm = () => {
  const addRows = reportCheckNoticeTemplateList.value
    .filter((x) => x.use)
    .filter((v) => !props.selectedIds.includes(v.id))
  if (!addRows.length) return handleClose()
  const itemList = props.orderItemIds
    .map((orderItemId) => {
      return addRows.map((x) => ({
        templateId: x.id,
        orderItemId
      }))
    })
    .flat(Infinity)

  const params = {
    itemList
  }
  loading.value = true
  //BoilerTaskOrderApi.addReportV2(params)
  BoilerTaskOrderApi.addReportV3(params)
    .then((res) => {
      ElMessage.success(`添加成功`)
      emit('refresh')
      handleClose()
    })
    .finally(() => {
      loading.value = false
    })
    .catch(() => {
      ElMessage.error('添加失败')
    })
}
// 检验意见通知书/意见指导书/检验方案提交
const jobGuideOrCheckSchemeConfirm = () => {
  if (activeName.value === 'checkNotice') {
    // 检验意见通知书提交
    return checkNoticeBookConfirm()
  }
  const list =
    activeName.value === 'jobGuide'
      ? jobGuideList.value
      : activeName.value === 'checkScheme'
        ? checkSchemeList.value
        : []

  if (activeName.value === 'jobGuide') {
    const addRows = list
      .filter((x) => x.use)
      .filter((v) => !props.selectedIds.includes(v.templateId || v.id))
    if (!addRows.length) return handleClose()
    loading.value = true
    BoilerTaskOrderApi.cancelReportRollbackStatus({ ids: addRows.map((x) => x.id) })
      .then(() => {
        ElMessage.success(`添加成功`)
        emit('refresh')
        handleClose()
      })
      .finally(() => {
        loading.value = false
      })
      .catch(() => {
        ElMessage.error('添加失败')
      })
  } else if (activeName.value === 'checkScheme') {
    const addRows = list
      .filter((x) => x.use)
      .filter((v) => !unref(orderReportIdList).includes(v.id))
    if (!addRows.length) return handleClose()
    loading.value = true
    const params = {
      itemList: addRows.map((x) => ({
        templateId: x.templateId || x.id,
        orderItemId: props.orderItemIds[0],
        orderReportId: x.id
      }))
    }

    loading.value = true
    //BoilerTaskOrderApi.addReportV2(params)
    BoilerTaskOrderApi.addReportV3(params)
      .then((res) => {
        ElMessage.success(`添加成功`)
        emit('refresh')
        handleClose()
      })
      .finally(() => {
        loading.value = false
      })
  }
}

const subProjectConfirm = () => {
  subProjectFormRef.value?.validate().then(async (validate) => {
    const { subSelectedChecker, fileList, fee, subcontractedName } = subProjectParams.value
    const uploadFileInfo = fileList[0]
    const manualUrl = uploadFileInfo.response.data
    const fileExt = uploadFileInfo.name.split('.').pop()?.toLowerCase()
    const fileTypeMap = { docx: '0', pdf: '1' }
    if (isEmpty(fileTypeMap[fileExt])) return ElMessage.error('请上传docx或pdf文件')
    const params: Recordable = {
      itemList: props.orderItemIds.map((orderItemId) => {
        return {
          fee,
          subcontractedName,
          manualUrl,
          orderItemId,
          fileType: fileTypeMap[fileExt],
          reportType: '900'
        }
      })
    }
    if (subSelectedChecker) {
      params.checkId = subSelectedChecker?.member?.id
      params.groupTeamId = subSelectedChecker?.groupTeamId //小组id
      params.type = subSelectedChecker.isLeader ? 100 : 200 //是否为组长
    }
    loading.value = true
    //BoilerTaskOrderApi.addReportV2(params)
    BoilerTaskOrderApi.addReportV3(params)
      .then((res) => {
        ElMessage.success(`添加成功`)
        emit('refresh')
        handleClose()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const loading = ref(false)
// 提交
const handleConfirm = async () => {
  if (activeName.value === 'subProject') {
    return subProjectConfirm()
  }
  if (activeName.value !== 'selectCheckItem') {
    return jobGuideOrCheckSchemeConfirm()
  }
  try {
    const itemList = props.orderItemIds
      .map((orderItemId) => {
        return selectedCheckItem.value.map((x,index) => ({
          templateId: x.templateId,
          connectId: x.connectId,
          fee: x.fee,
          type: x.type,
          orderItemId
        }))
      })
      .flat(Infinity)
    if (!itemList.length) {
      handleClose()
      return
    }
    const params = {
      checkId: currentSelectedChecker.value?.member?.id,
      groupTeamId: currentSelectedChecker.value?.groupTeamId, //小组id
      type: currentSelectedChecker.value.isLeader ? 100 : 200, //是否为组长
      itemList,
    }
    loading.value = true
    //console.log(params)
    //const result = await BoilerTaskOrderApi.addReportV2(params)
    const result = await BoilerTaskOrderApi.addReportV3(params)
    loading.value = false
    if (result) {
      ElMessage.success(`添加成功`)
      emit('refresh')
      handleClose()
    }
  } catch (error) {
    loading.value = false
    ElMessage.error('添加检验项目失败')
  }
}
</script>
<style lang="scss" scoped>
.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);
  }
}
.customClass {
  background-color: #f60;
  :deep(.el-dialog__footer) {
    text-align: center;
  }
}

/* 外层容器 */
.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;
  }
}

/* 闪电图标样式（模拟，实际可替换为 SVG/Iconfont） */
.icon-lightning {
  width: 24px;
  height: 24px;
  background-color: #ffd700; /* 金色背景 */
  mask: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M17 12h-2v3h-3v2h3v3h2v-3h3v-2h-3z"/></svg>')
  no-repeat center / contain;
  -webkit-mask: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M17 12h-2v3h-3v2h3v3h2v-3h3v-2h-3z"/></svg>')
  no-repeat center / contain;
}

/* 复选框样式优化（可选） */
.grid-item input[type='checkbox'] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.checker-box {
  display: flex;
  align-items: center;
  padding: 16px;
  .el-button {
    margin-left: 6px;
  }
}

:deep(.el-input-number) {
  width: 100%;
  .el-input__inner {
    text-align: left;
  }
}

// 查看信息表单样式优化
.view-info-form {
  background: #f5f7fa;
  padding: 16px 20px;
  border-radius: 4px;
  margin-bottom: 16px;
  
  :deep(.el-form-item) {
    margin-right: 32px;
    margin-bottom: 0;
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }
  
  .info-text {
    color: #303133;
    font-size: 14px;
    line-height: 1.5;
    word-break: break-all;
  }
}
</style>
<style lang="scss">
.AddOrEditCheckItemForEquipmentDialog {
  .el-dialog__footer {
    text-align: center;
  }
}
</style>
