<template>
  <el-dialog
    v-model="dialogVisible"
    title="详情编辑"
    width="90%"
    append-to-body
  >
    <!-- 单位基本信息 -->
    <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>
        <el-form
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="80px"
        >
          <!-- 基本信息查询部分 -->
          <div class="flex flex-wrap items-start gap-x-2">
            <el-form-item label="设备代码" prop="equipCode">
            <el-input
                v-model="queryParams.equipCode"
                placeholder="请输入设备注册代码"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
            />
            </el-form-item>

            <el-form-item label="出厂编号" prop="equipCode">
              <el-input
                v-model="queryParams.equipCode"
                placeholder="请输入出厂编号"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>

            <el-form-item label="部门" prop="relateDepartment">
            <DeptSelect
                v-model="queryParams.relateDepartment"
                placeholder="请选择部门"
                clearable
                class="!w-210px"
            />
            </el-form-item>

            <!-- <el-form-item label="运行状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="选择运行状态"
                clearable
                multiple
                collapse-tags
                collapse-tags-tooltip
                class="!w-240px"
              >
                <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_EQUIP_CONTAINER_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
                />
              </el-select>
            </el-form-item> -->

            <el-form-item label="临检时间" prop="nextDate">
              <div class="flex items-center gap-x-2">
                <el-select v-model="datePickerType" class="!w-[90px]">
                <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"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="!w-[220px]"
                @change="handleDateChange"
                />
                <el-date-picker
                v-else
                v-model="month"
                type="month"
                value-format="YYYY-MM"
                placeholder="选择月份"
                class="!w-[140px]"
                @change="handleMonthChange"
                />
              </div>
            </el-form-item>

          </div>

          <!-- 区域和时间查询部分 -->
          <div class="flex flex-wrap items-start gap-x-2">
            <el-form-item label="区域" prop="equipDistrict">
              <AreaSelect 
                v-model="queryParams.equipDistrict" 
                placeholder="请选择区域" 
                class="!w-[240px]"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :clearable="true"
                :area-type="queryParams.areaType"
                @clear="handleAreaClear"
                @change="handleAreaChange"
              />
            </el-form-item>

            <el-form-item label="街道" prop="equipStreet">
              <StreetSelect 
                  v-model="queryParams.equipStreet" 
                  :district-ids="queryParams.equipDistrict"
                  placeholder="请选择街道" 
                  class="!w-[240px]"
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  :clearable="true"
                  @clear="handleStreetClear"
                  @change="handleStreetChange"
              />
            </el-form-item>
          </div>

          <!-- 管道相关查询条件 -->
          <div class="">
            <el-form-item label="管道归类" prop="typeList" class="mb-2">
              <div class="flex items-center flex-1">
                <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>
              </div>
            </el-form-item>
          </div>

          <!-- 操作按钮 -->
          <div class="flex justify-center">
              <el-form-item class="!mb-0">
              <el-button @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 
                  type="primary" 
                  @click="handleBatchSchedule" 
                  :disabled="selectedRows.length === 0"
              >
                  <Icon icon="ep:calendar" class="mr-5px" /> 批量排期
              </el-button>
                <el-button
                  type="primary"
                  @click="handleBatchConcat"
                  :disabled="selectedRows.length === 0"
                >
                  <Icon icon="ep:edit" class="mr-5px" /> 批量修改约检联系人
                </el-button>
              </el-form-item>
          </div>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table
          v-loading="loading"
          ref="tableRef"
          :data="list"
          stripe
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
          :row-key="(row) => row.id"
        >
          <el-table-column type="selection" width="50" fixed="left"/>
          <el-table-column type="expand" width="1">
            <template #default="props">
              <div class="ml-15px mr-15px">

                <el-table :data="props.row.detailSaveReqVOS" border
                          :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
                          :ref="(el) => setDetailTableRef(el, props.row.id)"
                          @selection-change="(selection) => handleDetailSelectionChange(selection, props.row)"

                >
                  <el-table-column type="selection" width="50" fixed="left"/>
                  <el-table-column type="index" label="序号" min-width="60" align="center" :index="indexMethod1" />
                  <el-table-column label="注册代码" prop="equipCode" 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="序号" min-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="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="useNo"-->
<!--            min-width="120"-->
<!--            show-overflow-tooltip-->
<!--          />-->
          <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"
      :equip-list="selectedRows"
      :equip-detail-list="selectedDetailRows"
      :unitInfo="unitInfo"
      :source="100"
      @success="handleScheduleSuccess"
    />
  </el-dialog>

  <PipeBatchEditForm ref="formRef" @success="handleScheduleSuccess" />

</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE, StringDictDataType } from '@/utils/dict'
import { useMessage } from '@/hooks/web/useMessage'
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 PipePlanScheduleEquipDialog from './components/PipePlanScheduleEquipDialog.vue'
import { EquipBoilerSchedulingApi, EquipBoilerSchedulingVO, BoilerPlanSchedulingEquipEditVO }
  from '@/api/pressure2/equipboilerscheduling'
import PipeBatchEditForm from '../planNew/components/PipeBatchEditForm.vue'
import {formatArrayDate, formatDate} from "@/utils/formatTime";
import {PipeEquipmentDetailVO, PipeEquipmentVO} from "@/api/pressure2/pipeequipment";
import {EquipPipeSchedulingApi} from "@/api/pressure2/pipescheduling";
import PipePlanScheduleDialog
  from "@/views/pressure2/pipescheduling/components/PipePlanScheduleDialog.vue";
import PlanScheduleEquipPipeDialog
  from "@/views/pressure2/planNew/components/PlanScheduleEquipPipeDialog.vue";

const message = useMessage()
const dialogVisible = ref(false)
//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 formRef = ref()
const loading = ref(true) // 列表的加载中
const equipIds = ref<string>('') // 设备ID列表
const list = ref<BoilerPlanSchedulingEquipEditVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const selectedRows = ref<BoilerPlanSchedulingEquipEditVO[]>([]) // 选中的行
const selectedDetailRows = ref<PipeEquipmentDetailVO[]>([]) // 选中的行
const planScheduleEquipPipeDialogRef = ref() // 计划排期弹窗引用
const selectedTypeList = ref<StringDictDataType[]>([]) // 选中的管道归类
// 添加锅炉类型字典选项变量
const containerTypeOptions = getStrDictOptions(DICT_TYPE.PIPE_TYPE)

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

const queryParams = ref({
  pageNo: 1,
  pageSize: 50,
  unitName: unitInfo.value.unitName,
  unitAddress: unitInfo.value.unitAddress,
  equipCode: 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[],
  status: [] as string[],
  areaType: 'gz'
})

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

// 单条/批量排期相关
const currentEquip = ref<BoilerPlanSchedulingEquipEditVO>()
const currentCheckType = ref<'legal' | 'year' |''>('')
const isBatchMode = ref(false)

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

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

/** 打开弹窗 */
const open = async (row: EquipBoilerSchedulingVO, indexQueryParams?: any) => {
  dialogVisible.value = true

  // 拼接设备ID
  equipIds.value = [row.legalEquipIds, row.yearEquipIds]
    .filter(id => id) // 过滤掉 null、undefined、空字符串
    .join(',')

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

  // 同步 BoilerConfirmOrderCityBureau.vue 的查询条件
  if (indexQueryParams) {
    // 同步基础查询条件
    queryParams.value = {
      ...queryParams.value,
      equipCode: indexQueryParams.equipCode,
      relateDepartment: indexQueryParams.relateDepartment,
      equipDistrict: indexQueryParams.equipDistrict,
      equipStreet: indexQueryParams.equipStreet,
      typeList: indexQueryParams.typeList || [],
      nextDate: indexQueryParams.nextDate || [],
      status: indexQueryParams.status || [],
      areaType: indexQueryParams.areaType
    }

    //console.log(queryParams)

    // 同步日期相关
    if (indexQueryParams.datePickerType) {
      datePickerType.value = indexQueryParams.datePickerType
      if (datePickerType.value === 'daterange') {
        daterange.value = indexQueryParams.nextDate || []
      } else {
        month.value = indexQueryParams.month || ''
      }
    }

    // 同步容器归类选中状态
    if (indexQueryParams.typeList?.length > 0) {
      selectedTypeList.value = containerTypeOptions.filter(dict => 
        indexQueryParams.typeList.includes(dict.value)
      )
    }
  }

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

/** 搜索按钮操作 */
const handleQuery = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: queryParams.value.pageNo,
      pageSize: queryParams.value.pageSize,
      equipIds: equipIds.value.split(','),
      equipCode: queryParams.value.equipCode,
      relateDepartment: queryParams.value.relateDepartment,
      equipDistrict: queryParams.value.equipDistrict,
      equipStreet: queryParams.value.equipStreet,
      typeList: queryParams.value.typeList || [],
      nextDate: queryParams.value.nextDate || [],
      status: queryParams.value.status || [],
      unitName: unitInfo.value.unitName,
      unitAddress: unitInfo.value.unitAddress,
    }

    // 关闭所有已展开的行
    expandRows.value.forEach(row => {
      tableRef.value?.toggleRowExpansion(row, false)
    })
    // 清空展开行记录
    expandRowKeys.value = []
    expandRows.value = []

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

    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === undefined || params[key] === null) {
        delete params[key]
      }
      // 处理空数组
      if (Array.isArray(params[key]) && params[key].length === 0) {
        delete params[key]
      }
    })

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  
  // 重置页码
  queryParams.value.pageNo = 1
  
  // 清空选中的容器归类对象
  selectedTypeList.value = []
  
  // 重新查询
  handleQuery()
}

/** 表格选择框变化 */
const handleSelectionChange = async (selection: BoilerPlanSchedulingEquipEditVO[]) => {
  // 计算取消选择的行
  const deselectedRows = selectedRows.value.filter(
    item => !selection.includes(item)
  );
  selectedRows.value = selection
  // 每一个勾选了主表的要找到对应的子表
  for (const item of selection) {
    // 如果没有子表,展开当前子表
    if (!expandRowKeys.value.includes(item.id)) {
      await toggleExpand(item)
    }
    // 如果没有勾选,勾选子表
    if (selectedDetailRows.value.findIndex(selectedDetailRow => selectedDetailRow.equipPipeId === item.id) === -1) {
      getDetailTableRef(item.id)?.toggleAllSelection(true)
    }
  }
  deselectedRows.forEach(item => {
    getDetailTableRef(item.id)?.clearSelection()
  })
}


/** 处理批量排期 */
const handleBatchSchedule = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请至少选择一条记录')
    return
  }
  isBatchMode.value = true
  planScheduleEquipPipeDialogRef.value?.open('all')
}

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

const tableRef = ref()
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 handleDetailSelectionChange = (selection: any[], mainRow: PipeEquipmentVO) => {
  selectedDetailRows.value = selectedDetailRows.value.filter((item) => item.equipPipeId !== mainRow.id)
  selectedDetailRows.value = [...selectedDetailRows.value, ...selection]
  // tableRef.value.toggleRowSelection(mainRow, true)
  // 如果子表有选中项，则自动选中主表行；否则取消选中主表行
  nextTick(() => {
    if (selection.length > 0) {
      // 子表有选中项，选中主表行
      tableRef.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) {
        // 只有当主行当前是选中状态且子表没有任何选中项时才取消主行选择
        tableRef.value.toggleRowSelection(mainRow,false);
      }
    }
  });
}
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)
  } 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
    })
  }

}

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

/** 处理表格排序 */
const handleSortChange = ({ prop, order }) => {
  if (!prop || !order) {
    list.value.sort(() => 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
}

// 监听日期类型变化
watch(datePickerType, () => {
  // 清空日期相关字段
  daterange.value = []
  month.value = ''
  queryParams.value.nextDate = []
})

/** 处理批量修改约检联系人 */
const handleBatchConcat = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请至少选择一条记录')
    return
  }
  formRef.value.open(selectedRows.value, 'scheduling')
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.plan-section {
  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;
  }
}

.schedule-link {
  color: var(--el-color-primary);
  
  &:hover {
    color: var(--el-color-primary-light-3);
  }
}
:deep(.el-table__expand-icon) {
  display: none !important;
}
</style>
