<template>
  <!-- 单位基本信息 -->
  <div class="plan-section mb-4">
    <div class="section-title">
      <span>受检单位基本信息</span>
    </div>
    <el-descriptions :column="3" border>
      <el-descriptions-item label="单位名称">{{ unitInfo.unitName }}</el-descriptions-item>
      <el-descriptions-item label="单位地址">{{ unitInfo.unitAddress }}</el-descriptions-item>
      <!-- <el-descriptions-item label="使用单位联系人">{{ unitInfo.contact }}</el-descriptions-item>
        <el-descriptions-item label="使用单位联系电话">{{ unitInfo.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="区域">{{ unitInfo.equipDistrictName }}</el-descriptions-item>
        <el-descriptions-item label="街道">{{ unitInfo.equipStreetName }}</el-descriptions-item> -->
    </el-descriptions>
  </div>

  <div class="plan-section mb-4">
    <div class="section-title">
      <span>设备信息</span>
    </div>

    <!-- 搜索工作栏 -->
    <ContentWrap>
      <section class="flex gap-2">
        <el-form
          class="flex-1"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="135px"
        >
          <!-- 基本信息查询部分 -->
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item class="!w-full !mr-0px" label="区域" prop="equipDistrict">
                <AreaSelect
                  v-model="queryParams.equipDistrict"
                  placeholder="请选择区域"
                  class="!w-full area-select"
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  :clearable="true"
                  :area-type="queryParams.areaType"
                  @clear="handleAreaClear"
                  @change="handleAreaChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item class="!w-full !mr-0px" label="街道" prop="equipStreet">
                <StreetSelect
                  v-model="queryParams.equipStreet"
                  :district-ids="queryParams.equipDistrict"
                  placeholder="请选择街道"
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  :clearable="true"
                  @clear="handleStreetClear"
                  @change="handleStreetChange"
                />
              </el-form-item>
            </el-col>
<!--            <el-col :span="8">-->
<!--              <el-form-item class="!w-full !mr-0px" label="设备注册代码" prop="equipCode">-->
<!--                <el-input-->
<!--                  v-model="queryParams.equipCode"-->
<!--                  placeholder="请输入设备注册代码"-->
<!--                  clearable-->
<!--                  @keyup.enter="handleQuery"-->
<!--                />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <!-- <el-col :span="8">
                <el-form-item
                  class="!w-full !mr-0px"
                  label="社会统一信用代码"
                  prop="socialCreditCode"
                >
                  <el-input
                    class="!w-full"
                    v-model="queryParams.socialCreditCode"
                    placeholder="请输入社会统一信用代码"
                    clearable
                  />
                </el-form-item>
              </el-col> -->
            <!-- <el-col :span="8">
                <el-form-item class="!w-full !mr-0px" label="使用证编号" prop="useCertCode">
                  <el-input
                    class="!w-full"
                    v-model="queryParams.useCertCode"
                    placeholder="请输入使用证编号"
                    clearable
                  />
                </el-form-item>
              </el-col> -->
            <ElCollapseTransition v-if="isSearchExpanded">
              <el-col :span="8">
                <el-form-item class="!w-full !mr-0px" label="临检时间" prop="checkDate">
                  <div class="w-full flex gap-10px">
                    <el-select v-model="datePickerType" class="!w-[100px]">
                      <el-option label="时间段" value="daterange" />
                      <el-option label="月份" value="month" />
                    </el-select>
                    <el-date-picker
                      v-if="datePickerType === 'daterange'"
                      v-model="daterange"
                      type="daterange"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      class="flex-1"
                    />
                    <!-- @change="handleDateChange" -->
                    <el-date-picker
                      v-else
                      v-model="month"
                      type="month"
                      value-format="YYYY-MM"
                      placeholder="选择月份"
                      class="flex-1"
                    />
                    <!-- @change="handleMonthChange" -->
                  </div>
                </el-form-item>
              </el-col>
            </ElCollapseTransition>
            <ElCollapseTransition v-if="isSearchExpanded">
              <el-col :span="8">
                <el-form-item class="!w-full !mr-0px" label="部门" prop="relateDepartment">
                  <DeptSelect
                    class="!w-full"
                    v-model="queryParams.relateDepartment"
                    placeholder="请选择部门"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </ElCollapseTransition>
            <ElCollapseTransition v-if="isSearchExpanded">
              <el-col :span="8">
                <el-form-item class="!w-full !mr-0px" label="使用状态" prop="useStatus">
                  <el-select
                    v-model="queryParams.useStatus"
                    placeholder="选择使用状态"
                    clearable
                    collapse-tags
                    collapse-tags-tooltip
                    disabled
                  >
                    <el-option
                      v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_EQUIP_BOILER_STATUS)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </ElCollapseTransition>
            <ElCollapseTransition v-if="isSearchExpanded">
              <el-col :span="12">
                <el-form-item class="!w-full !mr-0px" label="管道归类" prop="typeList">
                  <el-checkbox-group
                    v-model="queryParams.typeList"
                    class="flex flex-wrap gap-2"
                    @change="handleTypeListChange"
                  >
                    <el-checkbox
                      v-for="dict in containerTypeOptions"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </ElCollapseTransition>
          </el-row>
        </el-form>
        <div class="flex-[0_0_260px] flex items-start">
          <!-- 操作按钮 -->
          <el-button type="primary" @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" /> 搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> 重置
          </el-button>
          <el-button link class="!h-[32px] flex" @click="isSearchExpanded = !isSearchExpanded">
            <el-icon>
              <ArrowUp v-if="isSearchExpanded" />
              <ArrowDown v-else />
            </el-icon>
            {{ isSearchExpanded ? '收起' : '展开' }}
          </el-button>
        </div>
      </section>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-row class="mb-2">
        <!--        <el-button
                  type="primary"
                  @click="() => handleBatchSchedule('regular')"
                  :disabled="selectedRows.length === 0"
                >
                  <Icon icon="ep:calendar" class="mr-5px" /> 定期约检
                </el-button>
                <el-button
                  type="primary"
                  @click="() => handleBatchSchedule('year')"
                  :disabled="selectedRows.length === 0"
                >
                  <Icon icon="ep:calendar" class="mr-5px" /> 年度约检
                </el-button>
                <el-button
                  type="primary"
                  @click="() => handleBatchSchedule('expired')"
                  :disabled="selectedRows.length === 0"
                >
                  <Icon icon="ep:calendar" class="mr-5px" /> 超年限约检
                </el-button>
                <el-button
                  type="primary"
                  @click="() => handleBatchSchedule('')"
                  :disabled="selectedRows.length === 0"
                >
                  <Icon icon="ep:calendar" class="mr-5px" /> 批量排期
                </el-button>-->
        <el-button
          type="primary"
          @click="() => handleBatchSchedule('')"
          :disabled="selectedRows.length === 0"
        >约检
        </el-button>
        <el-button type="primary" @click="handleBatchEditFn" :disabled="selectedRows.length === 0">
          <Icon icon="ep:edit" class="mr-5px" /> 批量修改约检联系人
        </el-button>
        <el-button type="primary" @click="() => handleToRoute('AcceptOrder1')">约检单</el-button>
        <el-button type="primary" @click="() => handleToRoute('TaskOrder')">任务单</el-button>
      </el-row>
      <el-table
        v-loading="loading"
        ref="mainTableRef"
        :data="list"
        border
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        :row-key="(row) => row.id"
        :row-class-name="getMainRowClassName"
        @row-click="handleMainRowClick"
        @expand-change="handleExpandChange"
        :expand-row-keys="expandRowKeys"
      >
        <el-table-column type="selection" width="50" fixed="left"/>
        <el-table-column type="expand">
          <template #default="props">
            <div class="ml-15px mr-15px">

              <el-table
                :data="props.row.pipes" border
                :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
                :ref="(el) => setDetailTableRef(el, props.row.id)"
                @selection-change="(selection) => handleDetailSelectionChange(selection, props.row)"
                :row-class-name="getRowClassName"
                class="inner-table"
                @row-click="handleRowClick"
              >
                <el-table-column type="selection" width="50" fixed="left"/>
                <el-table-column type="index" label="序号" width="60" align="center" :index="indexMethod1" />
                <el-table-column label="注册代码" prop="pipeRegCode" min-width="120" show-overflow-tooltip/>
                <el-table-column label="管道名称" prop="pipeName" min-width="120" show-overflow-tooltip/>
                <el-table-column label="管道编号" prop="pipeNo" min-width="120" show-overflow-tooltip/>
                <el-table-column label="管道级别" prop="pipeLevel" min-width="120" show-overflow-tooltip/>
                <el-table-column label="管道品种" prop="pipeType" min-width="120" show-overflow-tooltip/>
                <el-table-column label="长度" prop="pipeLength" min-width="100" show-overflow-tooltip/>
                <el-table-column label="管道材质" prop="pipeMaterial" min-width="120" show-overflow-tooltip/>
                <el-table-column label="材料标准" prop="materialStandard" min-width="120" show-overflow-tooltip/>
                <el-table-column label="定期安全状况等级" prop="legalSafetyStatusLevel" min-width="130" show-overflow-tooltip/>
                <el-table-column label="年度安全状况等级" prop="yearSafetyStatusLevel" min-width="130" show-overflow-tooltip/>
                <el-table-column label="下次定期检验" prop="nextLegalCheckDate"   align="center" min-width="160" show-overflow-tooltip>
                  <template #default="{ row }">
                    <div>
                      <div v-if="row.nextLegalCheckDate">
                        <span
                          class="text-xs">{{
                            formatDate(row.nextLegalCheckDate, 'YYYY-MM-DD')
                          }}</span>
                        <div v-if="row.planLegalCheckDate" class="text-xs text-[#2D5FBD]">
                          （排期时间：{{ row.planLegalCheckDate }}）
                        </div>
                      </div>
                      <span v-else>-</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="下次年度检查" prop="nextYearCheckDate"   align="center" min-width="160"
                                 show-overflow-tooltip>
                  <template #default="{ row }">
                    <div>
                      <div v-if="row.nextYearCheckDate">
                        <span
                          class="text-xs">{{
                            formatDate(row.nextYearCheckDate, 'YYYY-MM-DD')
                          }}</span>
                        <div v-if="row.planYearCheckDate" class="text-xs text-[#2D5FBD]">
                          （排期时间：{{ row.planYearCheckDate }}）
                        </div>
                      </div>
                      <span v-else>-</span>
                    </div>
                  </template>
                </el-table-column>

              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="60" align="center" :index="indexMethod" />
        <el-table-column
          label="工程号"
          align="center"
          prop="projectNo"
          min-width="120"
        >
          <template #default="{ row }">
            <div
              v-if="row.projectNo"
              class="cursor-pointer"
              @click.stop="toggleExpand(row)"
            >
              <div class="flex items-center justify-center gap-1 schedule-link">
                <span class="text-xs color-blue">{{row.projectNo}}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="工程名称"
                         align="center"
                         prop="projectName"
                         min-width="120"
                         show-overflow-tooltip
        />
        <el-table-column
          label="下次定期检验"
          align="center"
          prop="nextLegalCheckDate"
          min-width="140"
          sortable="custom"
        >
          <template #default="{ row }">
            <div
              v-if="row.nextLegalCheckDate"
            >
              <!--              class="cursor-pointer">-->
              <!--              @click="handleSingleSchedule(row, 'year')" > -->
              <!--              <div class="flex items-center justify-center gap-1 schedule-link">-->
              <div class="flex items-center justify-center gap-1">
                <span class="text-xs">{{formatDate(row.nextLegalCheckDate, 'YYYY-MM-DD')}}</span>
                <!--                <Icon icon="ep:calendar" class="text-xs" />-->
              </div>
              <!--              <div v-if="row.yearRefuseReasonDict || row.yearRefuseReason" class="text-xs text-red-500 mt-1">
                              （拒绝检验：{{
                                getRefuseResonText(row.yearRefuseReasonDict, row.yearRefuseReason)
                              }}）
                            </div>
                            <div v-else-if="row.yearAcceptDate" class="text-xs text-[#3D9E5F] mt-1">
                              （已受理：{{ formatArrayDate(row.yearAcceptDate) }}）
                            </div>
                            <div v-else-if="row.yearAppointmentDate" class="text-xs text-[#FF9A3D] mt-1">
                              （待约检：{{ formatArrayDate(row.yearAppointmentDate) }}）
                            </div>-->
              <div v-if="row.planLegalCheckDate" class="text-xs text-[#2D5FBD] mt-1">
                （排期时间：{{ row.planLegalCheckDate }}）
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          label="下次年度检查"
          align="center"
          prop="nextYearCheckDate"
          min-width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            <div
              v-if="row.nextYearCheckDate"
            >
              <!--              class="cursor-pointer"> -->
              <!--              @click="handleSingleSchedule(row, 'expired')" > -->
              <!--              <div class="flex items-center justify-center gap-1 schedule-link">-->
              <div class="flex items-center justify-center gap-1">
                <span class="text-xs">{{ formatDate(row.nextYearCheckDate, 'YYYY-MM-DD') }}</span>
                <!--                <Icon icon="ep:calendar" class="text-xs" />-->
              </div>
              <!--              <div v-if="row.expiredReasonDict || row.expiredRefuseReason" class="text-xs text-red-500 mt-1">-->
              <!--                （拒绝检验：{{-->
              <!--                  getRefuseResonText(row.expiredReasonDict, row.expiredRefuseReason)-->
              <!--                }}）-->
              <!--              </div>-->
              <!--              <div v-else-if="row.expiredAcceptDate" class="text-xs text-[#3D9E5F] mt-1">-->
              <!--                （已受理：{{ formatArrayDate(row.expiredAcceptDate) }}）-->
              <!--              </div>-->
              <!--              <div v-else-if="row.expiredAppointmentDate" class="text-xs text-[#FF9A3D] mt-1">-->
              <!--                （待约检：{{ formatArrayDate(row.expiredAppointmentDate) }}）-->
              <!--              </div>-->
              <div v-if="row.planYearCheckDate" class="text-xs text-[#2D5FBD] mt-1">
                （排期时间：{{ row.planYearCheckDate }}）
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- 区域 -->
        <el-table-column
          label="区域/街道"
          align="center"
          prop="pipeStreet"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span class="text-xs">{{ row.equipStreetName ?? row.equipDistrictName}}</span>
          </template>
        </el-table-column>
        <!-- 管道类别 -->
        <el-table-column label="管道类别" align="center" prop="pipeCategory">
          <template #default="scope">
            {{ containerTypeOptions.find(i => i.value == scope.row.pipeCategory)?.label }}
          </template>
        </el-table-column>

        <el-table-column
          label="约检联系人"
          align="center"
          prop="contact"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="约检联系人电话"
          align="center"
          prop="contactPhone"
          min-width="140"
          show-overflow-tooltip
        />
      </el-table>

      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </ContentWrap>
  </div>
  <!-- 约检弹窗 -->
  <PlanScheduleEquipPipeDialog
    ref="planScheduleEquipPipeDialogRef"
    :source="200"
    :equip-list="selectedRows"
    :equip-detail-list="selectedDetailRows"
    :unitInfo="unitInfo"
    @success="handleScheduleSuccess"
  />
  <PipeBatchEditForm ref="formRef" @success="handleScheduleSuccess" />
</template>

<script setup lang="ts" name="PlanNewDetail">
import {DICT_TYPE, getStrDictOptions, StringDictDataType} from '@/utils/dict'
import {useMessage} from '@/hooks/web/useMessage'
import {PlanNewPageVO} from '@/api/pressure/planScheduling'
import AreaSelect from '../../system/equipcontainer/components/AreaSelect.vue'
import StreetSelect from '../../system/equipcontainer/components/StreetSelect.vue'
import DeptSelect from './components/DeptSelect.vue'
import dayjs from 'dayjs'
import {useUserStore} from '@/store/modules/user'
import {formatArrayDate, formatDate} from '@/utils/formatTime'
import PipeBatchEditForm from './components/PipeBatchEditForm.vue'
import {cloneDeep} from 'lodash-es'
import {isEmpty} from '@/utils/is'
import {useRouter} from 'vue-router'
import {usePlanNewStore} from '@/store/modules/planNew'
import {ArrowDown, ArrowUp} from '@element-plus/icons-vue'
import {EquipBoilerSchedulingEquipVO} from "@/api/pressure2/equipboilerscheduling";
import {
  PipeEquipmentApi,
  PipeEquipmentDetailVO,
  PipeEquipmentVO
} from "@/api/pressure2/pipeequipment";
import PlanScheduleEquipPipeDialog
  from "./components/PlanScheduleEquipPipeDialog.vue";
import {EquipPipeSchedulingApi, PipePlanSchedulingVO} from "@/api/pressure2/pipescheduling";
import PlanScheduleBoilerDialog
  from "@/views/pressure2/planNew/components/PlanScheduleEquipBoilerDialog.vue";
import {ref} from "vue";

const router = useRouter()

const props = defineProps({
  source: {
    type: String as PropType<string>,
    default: 'pressure'
  }
})
const currentDefaultYear = [
  dayjs().startOf('year').format('YYYY-MM-DD HH:mm:ss'),
  dayjs().endOf('year').format('YYYY-MM-DD HH:mm:ss')
]
const message = useMessage()
const userStore = useUserStore()
const datePickerType = ref<'daterange' | 'month'>('month') // 修改时间选择类型定义
const daterange = ref<string[]>([]) // 日期选择值
const month = ref<string>('') // 月份选择值
const areaStreetMap = ref(new Map<number, number[]>()) // 记录每个区域下已选择的街道

const loading = ref(false) // 列表的加载中
const equipIds = ref<string[]>([]) // 设备ID列表
const list = ref<PipeEquipmentVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const selectedRows = ref<PipeEquipmentVO[]>([]) // 选中的行
const selectedDetailRows = ref<PipeEquipmentDetailVO[]>([]) // 选中的行
const planScheduleEquipPipeDialogRef = ref<InstanceType<typeof PlanScheduleEquipPipeDialog>>() // 计划排期弹窗引用
const selectedTypeList = ref<StringDictDataType[]>([]) // 选中的容器归类

const formRef = ref()
// 单位基本信息
const unitInfo = ref({
  unitId: '',
  unitName: '',
  unitAddress: '',
  contact: '',
  contactPhone: '',
  equipDistrictName: '',
  equipStreetName: ''
})

const equipTypeMap = {
  1: '容器'
}

const mainTableRef = ref()

// 拒绝原因
const refuseInspectedCategoryOptions = getStrDictOptions('refuseInspectedCategory')
const getRefuseResonText = (dictCode: string, value: string) => {
  const resonObj = refuseInspectedCategoryOptions.find((item) => item.value === dictCode)
  return value || resonObj?.label || dictCode
}

const queryParams = ref<Recordable>({
  pageNo: 1,
  pageSize: 20,
  equipCode: undefined as string | undefined,
  productNo: undefined as string | undefined,
  relateDepartment: undefined as string | string[] | undefined,
  equipDistrict: undefined as number[] | undefined,
  equipStreet: undefined as number[] | undefined,
  typeList: [] as string[],
  nextDate: [] as string[],
  useStatus: '100',
  areaType: 'all' as 'all' | 'gz'
})

const queryFormRef = ref() // 搜索的表单

// 添加容器类型字典选项变量
const containerTypeOptions = getStrDictOptions(DICT_TYPE.PIPE_TYPE)

// 单条/批量排期相关
const currentEquip = ref<PipeEquipmentVO>()
const currentCheckType = ref<scheduleType>('')
const expandedRowsCache = ref<Map<string, { pipes: any[], selectedIds: Set<string> }>>(new Map())
// 标志位：防止展开时恢复选中状态触发 handleDetailSelectionChange 覆盖缓存
const isRestoringSelection = ref(false)
// 存储所有子表引用的对象
const detailTableRefs = ref<Record<string, any>>({})
const setDetailTableRef = (el: any, parentId: string) => {
  if (el) {
    detailTableRefs.value[parentId] = el;
  }
}
const getDetailTableRef = (parentId: string) => {
  return detailTableRefs.value[parentId];
}

const getMainRowClassName = ({row}) => {
  const isSelected = mainTableRef.value?.getSelectionRows().some((item) =>
    item.id === row.id
  )
  return isSelected ? 'selected-row' : ''
}
const getRowClassName = ({row}) => {
  // 找到当前行所在的分组，从 Map 中获取对应的表格实例
  const tableRef = getDetailTableRef(row.equipPipeId)
  if (tableRef) {
    const isSelected = tableRef.getSelectionRows().some((item) =>
      item.id === row.id
    )
    return isSelected ? 'selected-row' : ''
  }

  return ''
}
/** 处理行点击勾选 */
const handleMainRowClick = (row) => {
  mainTableRef.value?.toggleRowSelection(row)
}

const handleRowClick = (row, event, column) => {
  // 如果点击的是选择列，不处理
  if (column.type === 'selection') {
    return
  }
  // 找到当前行所在的分组，从 Map 中获取对应的表格实例
  const tableRef = getDetailTableRef(row.equipPipeId)
  if (tableRef && tableRef.toggleRowSelection) {
    tableRef.toggleRowSelection(row)
  }
}

const handleExpandChange = (row, expandedRows: any[]) => {
  const rowId = row.id
  const isExpanded = expandedRows.some((r) => r.id === rowId)

  if (isExpanded) {
    // 展开时，从缓存中恢复或初始化
    if (!expandedRowsCache.value.has(rowId)) {
      // 首次展开，初始化缓存
      expandedRowsCache.value.set(rowId, {
        pipes: row.pipes || [],
        selectedIds: new Set<string>()
      })
    }
    // 恢复选中状态
    nextTick(() => {
      const cache = expandedRowsCache.value.get(rowId)
      const tableRef = getDetailTableRef(rowId)
      if (cache && tableRef && cache.pipes.length > 0) {
        // 设置标志位，防止触发 handleDetailSelectionChange
        isRestoringSelection.value = true

        cache.pipes.forEach((pipe) => {
          if (cache.selectedIds.has(pipe.id)) {
            tableRef.toggleRowSelection(pipe, true)
          }
        })

        // 恢复完成后，延迟重置标志位
        nextTick(() => {
          isRestoringSelection.value = false
        })
      }
    })
  } else {
    // 收起时，保存当前选中状态
    const tableRef = getDetailTableRef(rowId)
    if (tableRef) {
      const currentSelection = tableRef.getSelectionRows()
      const selectedIds = new Set(currentSelection.map((item: any) => item.id))
      expandedRowsCache.value.set(rowId, {
        pipes: row.pipes || [],
        selectedIds: selectedIds
      })
    }
  }

  // 更新展开的行 key 列表
  expandRowKeys.value = expandedRows.map((r) => r.id)
}

/** 打开弹窗 */
const open = async (row: PlanNewPageVO) => {
  equipIds.value = [...new Set([row.equipIds, row.yearEquipIds, row.expiredEquipIds])]
    .filter((id) => id) // 过滤掉 null、undefined、空字符串
    .join(',')
    .split(',')

  // 设置单位信息
  unitInfo.value = {
    unitId: row.unitId || '',
    unitName: row.unitName || '',
    unitAddress: row.unitAddress || '',
    contact: row.contact || '',
    contactPhone: row.contactPhone || '',
    equipDistrictName: row.equipDistrictName || '',
    equipStreetName: row.equipStreetName || ''
  }

  // 初始化查询参数
  queryParams.value = {
    ...queryParams.value,
    unitCode: row.unitCode,
    unitName: row.unitName || '',
    unitId: row.unitId || '',
  }

  // 查询设备列表
  await handleQuery()
}

const indexMethod = (index: number) => {
  return index + 1
}

const indexMethod1 = (index: number) => {
  return index + 1
}

/**获取查询参数 */
const getQueryParams = () => {
  const params = cloneDeep({
    scene: 0,
    pageNo: queryParams.value.pageNo,
    pageSize: queryParams.value.pageSize,
    unitCode: queryParams.value.unitCode,
    // unitName: queryParams.value.unitName,
    unitId: queryParams.value.unitId,
    // equipIds: equipIds.value,
    equipCode: queryParams.value.equipCode,
    relateDepartment: queryParams.value.relateDepartment,
    productNo: queryParams.value.productNo,
    equipDistrict: queryParams.value.equipDistrict,
    equipStreet: queryParams.value.equipStreet,
    pipeCategory: queryParams.value.typeList?.length === 1 ? queryParams.value.typeList[0] : undefined,
    pipeCategorys: queryParams.value.typeList || [],
    typeList: queryParams.value.typeList || [],
    nextDate: (queryParams.value.nextDate || []).map((item) => dayjs(item).valueOf()),
    useStatus: queryParams.value.useStatus ? [+queryParams.value.useStatus] : []
  })
  if (datePickerType.value === 'daterange') {
    params.nextDate = daterange.value ? daterange.value.map((item) => dayjs(item).valueOf()) : []
  } else if (datePickerType.value === 'month') {
    params.nextDate = month.value
      ? [dayjs(month.value).startOf('month').valueOf(), dayjs(month.value).endOf('month').valueOf()]
      : []
  }
  // 移除空值
  Object.keys(params).forEach((key) => {
    if (isEmpty(params[key])) {
      delete params[key]
    }
  })
  return params
}
const isSearchExpanded = ref(false)
/** 搜索按钮操作 */
const handleQuery = async () => {
  loading.value = true
  try {
    // 关闭所有已展开的行
    // expandRows.value.forEach(row => {
    //   tableRef.value?.toggleRowExpansion(row, false)
    // })
    // 清空展开行记录
    expandRowKeys.value = []
    expandRows.value = []

    selectedRows.value = []
    selectedDetailRows.value = []

    const params = getQueryParams()
    // 调用后端API获取数据
    const res = await EquipPipeSchedulingApi.getPlanSchedulingPipesList(params)
    console.log(res)
    list.value = res.list
    total.value = res.total
  } finally {
    loading.value = false
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()

  // 重置页码
  queryParams.value.pageNo = 1

  // 清空选中的容器归类对象
  selectedTypeList.value = []

  // 重置日期值
  datePickerType.value = 'daterange'
  // daterange.value = [dayjs().startOf('year').format('YYYY-MM-DD HH:mm:ss'), dayjs().endOf('year').format('YYYY-MM-DD HH:mm:ss')]
  daterange.value = []
  month.value = ''
  // 重新查询
  handleQuery()
}
/** 处理子表选择变化 */
const handleDetailSelectionChange = (selection: any[], mainRow: any) => {
  // 如果正在恢复选中状态，不更新缓存（避免展开时 toggleRowSelection 触发此函数覆盖缓存）
  if (isRestoringSelection.value) {
    return
  }

  const rowId = mainRow.id

  // 更新缓存中的选中状态（如果缓存不存在则创建）
  if (!expandedRowsCache.value.has(rowId)) {
    // 如果该行还未展开，初始化缓存
    expandedRowsCache.value.set(rowId, {
      pipes: mainRow.pipes || [],
      selectedIds: new Set<string>()
    })
  }
  const cache = expandedRowsCache.value.get(rowId)!
  cache.selectedIds = new Set(selection.map((item: any) => item.id))

  // 更新全局选中的子表数据
  selectedDetailRows.value = selectedDetailRows.value.filter((item) => item.equipPipeId !== mainRow.id)
  selectedDetailRows.value = [...selectedDetailRows.value.filter(row => !selection.some(sel => sel.id === row.id)), ...selection]

  // 如果子表有选中项，则自动选中主表行；否则取消选中主表行
  nextTick(() => {
    if (selection.length > 0) {
      // 子表有选中项，选中主表行
      mainTableRef.value.toggleRowSelection(mainRow, true);
    } else if (!selectedDetailRows.value.map(row => row.equipPipeId).includes(mainRow.id)) {
      const currentlySelected = selectedRows.value.some(row => row.id === mainRow.id);
      if (currentlySelected && selection.length === 0) {
        // 只有当主行当前是选中状态且子表没有任何选中项时才取消主行选择
        mainTableRef.value.toggleRowSelection(mainRow, false);
      }
    }
  });
}

/** 表格选择框变化 */
const handleSelectionChange = async (selection: any[]) => {
  // 计算取消选择的行
  const deselectedRows = selectedRows.value.filter(
    item => !selection.includes(item)
  );
  selectedRows.value = selection

  // 清除取消选中行的子表选择（包括展开的和收起的）
  deselectedRows.forEach(item => {
    const rowId = item.id
    // 如果该行是展开状态，直接清除表格选中
    const tableRef = getDetailTableRef(rowId)
    if (tableRef) {
      tableRef.clearSelection()
    }

    // 无论是否展开，都清除缓存中的选中状态
    if (expandedRowsCache.value.has(rowId)) {
      expandedRowsCache.value.get(rowId)!.selectedIds.clear()
    }

    // 从全局选中的子表数据中移除
    selectedDetailRows.value = selectedDetailRows.value.filter(
      detailRow => detailRow.equipPipeId !== rowId
    )
  })
}

type scheduleType = 'regular' | 'year' | ''
/** 处理单条记录排期 */
const handleSingleSchedule = (row: PipeEquipmentVO, type: scheduleType) => {
  currentEquip.value = row
  currentCheckType.value = type
  planScheduleEquipPipeDialogRef.value?.open()
}

/** 处理批量排期 */
const handleBatchSchedule = (type: scheduleType) => {
  if (selectedDetailRows.value.length === 0) {
    message.warning('请至少选择一条记录')
    return
  }
  currentCheckType.value = type
  planScheduleEquipPipeDialogRef.value?.open(type)
}
/** 处理批量修改 */
const handleBatchEditFn = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请至少选择一条记录')
    return
  }
  formRef.value.open(selectedRows.value, '1')
}

/** 约检单/任务单 跳转查询 */
const handleToRoute = (routeName: 'AcceptOrder1' | 'TaskOrder') => {
  const { unitName } = unref(currentCheckData) || {}
  router.push({
    name: routeName,
    query: {
      unitName: unitName,
      filterCancel: '400'
    }
  })
}

/** 排期成功处理 */
const handleScheduleSuccess = () => {
  selectedRows.value = []
  handleQuery()
}

/** 处理容器归类变化 */
const handleTypeListChange = (values: string[]) => {
  selectedTypeList.value = containerTypeOptions.filter((dict) => values.includes(dict.value))
}

/** 处理表格排序 */
const handleSortChange = ({ prop, order }) => {
  if (!prop || !order) {
    list.value.sort((a, b) => 0) // 重置排序
    return
  }

  list.value.sort((a, b) => {
    const aValue = a[prop] || ''
    const bValue = b[prop] || ''

    if (order === 'ascending') {
      return aValue > bValue ? 1 : -1
    } else {
      return aValue < bValue ? 1 : -1
    }
  })
}

/** 处理区域变化 */
const handleAreaChange = (areas: number[]) => {
  // 获取移除的区域（通过比较之前的区域列表和现在的区域列表）
  const prevAreas = Array.from(areaStreetMap.value.keys())
  const removedAreas = prevAreas.filter((area) => !areas.includes(area))

  // 移除取消选择的区域下的街道
  if (removedAreas.length > 0) {
    const currentStreets = queryParams.value.equipStreet || []
    removedAreas.forEach((areaId) => {
      const streetsToRemove = areaStreetMap.value.get(areaId) || []
      // 从当前选中的街道中移除这些街道
      queryParams.value.equipStreet = currentStreets.filter(
        (streetId) => !streetsToRemove.includes(streetId)
      )
      // 从映射中移除该区域
      areaStreetMap.value.delete(areaId)
    })
  }
}

/** 处理区域清空 */
const handleAreaClear = () => {
  // 清空所有选中的街道
  queryParams.value.equipStreet = []
  // 清空区域-街道映射
  areaStreetMap.value.clear()
}

/** 处理街道变化 */
const handleStreetChange = (streets: number[], areaId: number) => {
  // 更新区域-街道映射
  if (queryParams.value.equipDistrict?.includes(areaId)) {
    areaStreetMap.value.set(areaId, streets)
  }
}

/** 处理街道清空 */
const handleStreetClear = () => {
  // 清空所有区域下的街道选择
  areaStreetMap.value.clear()
}

/** 处理日期变化 */
const handleDateChange = (val: [string, string] | null) => {
  daterange.value = val || []
  queryParams.value.nextDate = val
    ? [
      dayjs(val[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs(val[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    ]
    : []
}

/** 处理月份变化 */
const handleMonthChange = (val: string | null) => {
  if (!val) {
    queryParams.value.nextDate = []
    return
  }

  const date = dayjs(val)
  queryParams.value.nextDate = [
    date.startOf('month').format('YYYY-MM-DD HH:mm:ss'),
    date.endOf('month').format('YYYY-MM-DD HH:mm:ss')
  ]
  month.value = val
}

// 已展开行
const expandRowKeys = ref<string[]>([])
const expandRows = ref([])
const toggleExpand = async (row: any) => {
  const key = row.id
  // 第一次点击展开，第二次点击同一行收起
  if (expandRowKeys.value.includes(key)) {
    expandRowKeys.value = expandRowKeys.value.filter((key) => key !== key)
    expandRows.value = expandRows.value.filter((row) => row.id !== key)
    selectedDetailRows.value = selectedDetailRows.value.filter((row) => row.equipPipeId !== key)
    tableRef.value.toggleRowExpansion(row, false)
    tableRef.value.toggleRowSelection(row, false)
  } else {
    expandRowKeys.value.push(key)
    expandRows.value.push(row)
    tableRef.value.toggleRowExpansion(row, true)
    await EquipPipeSchedulingApi.getPipeEquipmentDetailListByPipeEquipmentId( key,{equipIds:[]}).then((res) => {
      let find = list.value.find(item => item.id === key);
      find.detailSaveReqVOS = res.list
    })
  }

}

// 监听日期类型变化
watch(datePickerType, (newVal) => {
  // 清空日期相关字段
  // daterange.value = newVal === 'daterange' ? daterange.value = cloneDeep(currentDefaultYear) : []
  daterange.value = []
  month.value = ''
  queryParams.value.nextDate = []
})
const { getPlanNewData } = usePlanNewStore()
const currentCheckData = ref<PlanNewPageVO>()
onMounted(() => {
  const { id } = (router.currentRoute.value.query || {}) as unknown as { id: string }
  const data = getPlanNewData(id)
  if (data) {
    currentCheckData.value = data
    open(data)
  }
})

defineExpose({
  open
})
</script>

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

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

.schedule-link {
  color: var(--el-color-primary);

  &:hover {
    color: var(--el-color-primary-light-3);
  }
}
:deep(.area-select) {
  .area-cascader {
    flex: 1;
  }
}

:deep(.inner-table .el-checkbox__input.is-checked .el-checkbox__inner),
:deep(.inner-table .el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #67c23a; // 绿色
  border-color: #67c23a;
}

:deep(.selected-row){
  background-color: #ecf5ff !important;
}

// 子表选中行特殊背景色（浅绿色）
:deep(.inner-table .selected-row) {
  background-color: #e8f5e9 !important;
}
</style>
