<template>
  <el-card class="hl-card">
    <template #header>
      <span>手动插活方案</span>
    </template>
    <ContentWrap class="borderxx">
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="110px"
      >
        <el-form-item label="负责人" prop="twoDimOwner">
          <el-select class="!w-265px" v-model="queryParams.twoDimOwner" clearable filterable>
            <el-option
              v-for="dict in userInit"
              :key="dict.id"
              :label="dict.nickname"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="beginTime">
          <el-date-picker
            v-model="queryParams.beginTime"
            value-format="YYYY-MM-DD"
            type="date"
            clearable
            @change="changeBeginDate()"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="!w-280px"
          />
        </el-form-item>
        <el-form-item label="项目编号" prop="code">
          <el-input
            v-model="queryParams.code"
            placeholder="请输入项目编号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="子项目名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入子项目名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>

        <el-form-item label="设计类型" prop="subType">
          <el-select v-model="queryParams.subType" placeholder="类型" clearable class="!w-240px">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.HELI_CH_PROCESS_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" type="primary"
            ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
          >
          <!-- <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button> -->
          <el-button @click="saveForm" type="warning">保存</el-button>
          <el-button @click="addForm" type="success">新增</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table
        v-loading="loading"
        :data="list"
        :show-overflow-tooltip="true"
        class="hl-table"
        border
      >
        <el-table-column fixed label="序号" type="index" width="70" align="center" />
        <el-table-column fixed label="项目编码" align="center" prop="code" min-width="130" />
        <el-table-column fixed label="项目简码" align="center" prop="projectNameSim" min-width="130" />
        <el-table-column fixed label="子项目名称" align="center" prop="name" min-width="180" />
        <el-table-column min-width="110px" align="center">
          <template #header>设计类型</template>
          <template #default="{ row, $index }">
            <el-form-item :prop="`${$index}.subType`" class="mb-0px!">
              <el-select
                v-model="row.subType"
                clearable
                filterable
                :disabled="row.userFlag == false"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.HELI_CH_PROCESS_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="200px" align="center">
          <template #header>负责人</template>
          <template #default="{ row, $index }">
            <el-form-item :prop="`${$index}.twoDimOwner`" class="mb-0px!">
              <el-select
                class="!w-265px"
                v-model="row.twoDimOwner"
                clearable
                filterable
                :disabled="row.flag == 0"
              >
                <el-option
                  v-for="dict in userInit"
                  :key="dict.id"
                  :label="dict.username + ' ' + dict.nickname"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="180px" align="center">
          <template #header>开始日期</template>
          <template #default="{ row, $index }">
            <el-form-item :prop="`${$index}.startTwoDimDate`" class="mb-0px!">
              <el-date-picker
                v-model="row.startTwoDimDate"
                type="date"
                @change="change1(row, 0)"
                value-format="x"
                placeholder="开始日期"
                :disabled="row.flag == 0"
                :disabled-date="disabledFutureDates"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="180px" align="center">
          <template #header>结束日期</template>
          <template #default="{ row, $index }">
            <el-form-item :prop="`${$index}.twoDimDate`" class="mb-0px!">
              <el-date-picker
                v-model="row.twoDimDate"
                type="date"
                @change="change1(row, 1)"
                value-format="x"
                placeholder="结束日期"
                :disabled="row.flag == 0"
                :disabled-date="disabledFutureDates"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="设计天数" align="center" prop="designNum" min-width="100" />
        <el-table-column label="时间段顺序" align="center" prop="seqNo" min-width="110" />
        <el-table-column label="是否新增" align="center" prop="seqNo" min-width="100">
          <template #default="scope">
            {{ scope.row.isAdd == 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" min-width="190">
          <template #default="scope">
            <el-button link type="primary" @click="addItemRow(scope.row)"> 新增 </el-button>
            <el-button link type="success" @click="modification(scope.row)"> 修改 </el-button>
            <el-button link @click="handleDelete(scope.row)" type="danger"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
  </el-card>

  <!----插活弹框-->
  <!-- 插活弹窗 -->
  <el-dialog v-model="dialogVisible" width="100%" :close-on-click-modal="false">
    <div class="dialog-content" style="display: flex; gap: 20px">
      <!-- 左侧插活前列表 -->
      <div style="flex: 1">
        <div class="status-title" style="margin-bottom: 15px">
          <h3>{{
            '当前子项目' +
            currentRow.name +
            '：' +
            formatDate(currentRow?.startTwoDimDate, 'YYYY-MM-DD') +
            '至' +
            formatDate(currentRow?.twoDimDate, 'YYYY-MM-DD')
          }}</h3>
          <h3>{{ '插活前' }}</h3>
        </div>
        <!-- 表格 -->
        <el-table
          v-loading="loading2"
          :data="beforeList"
          :show-overflow-tooltip="true"
          class="hl-table"
          border
          max-height="400"
        >
          <el-table-column fixed label="子项目名称" align="center" prop="name" min-width="120px" />

          <el-table-column min-width="50px" align="center">
            <template #header>设计类型</template>
            <template #default="{ row }">
              <span>{{ getDictLabel(DICT_TYPE.HELI_CH_PROCESS_TYPE, row.subType) }}</span>
            </template>
          </el-table-column>

          <el-table-column min-width="55px" align="center">
            <template #header>负责人</template>
            <template #default="{ row }">
              <span>{{ getUserNickname(row.twoDimOwner) }}</span>
            </template>
          </el-table-column>

          <el-table-column min-width="60px" align="center">
            <template #header>开始日期</template>
            <template #default="{ row }">
              <span>{{ formatDate(row.startTwoDimDate, 'YYYY-MM-DD') }}</span>
            </template>
          </el-table-column>

          <el-table-column min-width="60px" align="center">
            <template #header>结束日期</template>
            <template #default="{ row }">
              <span>{{ formatDate(row.twoDimDate, 'YYYY-MM-DD') }}</span>
            </template>
          </el-table-column>

          <el-table-column label="设计天数" align="center" prop="designNum" min-width="50px" />
          <el-table-column label="时间段顺序" align="center" prop="seqNo" min-width="60px" />
        </el-table>
      </div>

      <!-- 右侧插活后列表 -->
      <div style="flex: 1">
        <div class="status-title" style="margin-bottom: 15px">
          <h3>{{
            '当前子项目' +
            currentRow.name +
            '：' +
            formatDate(currentRow?.startTwoDimDate, 'YYYY-MM-DD') +
            '至' +
            formatDate(currentRow?.twoDimDate, 'YYYY-MM-DD')
          }}</h3>

          <h3>{{ '插活后' }}</h3>
        </div>
        <!-- 表格 -->
        <el-table
          v-if="dialogTitle == '插活后'"
          v-loading="loading2"
          :data="insertList"
          :show-overflow-tooltip="true"
          class="hl-table"
          border
          max-height="400"
        >
          <el-table-column fixed label="子项目名称" align="center" prop="name" min-width="120px" />

          <el-table-column min-width="50px" align="center">
            <template #header>设计类型</template>
            <template #default="{ row }">
              <span>{{ getDictLabel(DICT_TYPE.HELI_CH_PROCESS_TYPE, row.subType) }}</span>
            </template>
          </el-table-column>

          <el-table-column min-width="55px" align="center">
            <template #header>负责人</template>
            <template #default="{ row }">
              <span>{{ getUserNickname(row.twoDimOwner) }}</span>
            </template>
          </el-table-column>

          <el-table-column min-width="60px" align="center">
            <template #header>开始日期</template>
            <template #default="{ row }">
              <span>{{ formatDate(row.startTwoDimDate, 'YYYY-MM-DD') }}</span>
            </template>
          </el-table-column>

          <el-table-column min-width="60px" align="center">
            <template #header>结束日期</template>
            <template #default="{ row }">
              <span>{{ formatDate(row.twoDimDate, 'YYYY-MM-DD') }}</span>
            </template>
          </el-table-column>

          <el-table-column label="设计天数" align="center" prop="designNum" min-width="50px" />
          <el-table-column label="时间段顺序" align="center" prop="seqNo" min-width="60px" />
        </el-table>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancelDialog">取消</el-button>
        <el-button v-if="dialogTitle == '插活前'" type="warning" @click="handleInsert"
          >插活</el-button
        >
        <el-button v-else type="primary" @click="handleConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog :close-on-click-modal="false" v-model="addDialogVisible" title="新增" width="80%">
    <!-- 查询条件 -->
    <el-form inline class="mb-4">
      <el-form-item label="项目编码">
        <el-input v-model="addQueryParams.projectCode" placeholder="请输入项目编码" />
      </el-form-item>
      <el-form-item label="子项目名称">
        <el-input v-model="addQueryParams.projectSubName" placeholder="请输入子项目名称" />
      </el-form-item>
      <el-form-item label="客户简称">
        <el-input v-model="addQueryParams.customerBrief" placeholder="请输入客户简称" />
      </el-form-item>
      <el-button type="primary" @click="handleAddQuery">查询</el-button>
    </el-form>

    <!-- 新增 -->
    <el-table
      :data="addList"
      v-loading="loading3"
      highlight-current-row
      ref="multipleTableRef"
      @select="handlerSelect"
      @selection-change="handleSelectionChange"
      @row-click="rowClickHandle"
      :row-key="(row) => row.id"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="70" align="center" />
      <el-table-column prop="projectName" label="项目名称" min-width="180" />
      <el-table-column prop="code" label="项目编码" min-width="150" />
      <el-table-column prop="name" label="子项目名称" min-width="180" />
      <el-table-column prop="customerBrief" label="客户简称" min-width="150" />
      <el-table-column prop="planNo" label="生产计划" min-width="150" />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="addtotal"
      v-model:page="addQueryParams.pageNo"
      v-model:limit="addQueryParams.pageSize"
      @pagination="handleAddQuery"
    />
    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer" style="margin-left: 45%">
        <el-button @click="handleAddCancel">取消</el-button>
        <el-button type="primary" @click="handleAddConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>


<script setup lang="ts">
defineOptions({ name: 'Interrupt' })
import * as PlansubdetailApi from '@/api/heli/plansubdetail'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { ref, reactive, onMounted } from 'vue' // 确保导入 onMounted
import * as UserApi from '@/api/system/user'
import routeParamsCache from '@/utils/routeParamsCache';
import * as PlanSubApi from '@/api/heli/plansub'
import { formatDate } from '@/utils/formatTime'
import * as shopCalendarApi from '@/api/heli/shopCalendar'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const reload = inject('reload')
const userInit = ref()
const loading = ref(false)
const loading2 = ref(false)
const loading3 = ref(false)
const list = ref([])
const total = ref(0)
const multipleTableRef = ref()
const addtotal = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  twoDimOwner: undefined,
  subType: undefined,
  beginTime: undefined,
  startTime: undefined,
  code: undefined,
  name: undefined
})
const queryFormRef = ref()
const changeBeginDate = () => {
  if (!queryParams.beginTime) {
    queryParams.startTime = undefined
  }
}
// 获取字典标签
const getDictLabel = (dictType, value) => {
  const options = getStrDictOptions(dictType)
  const option = options.find((item) => item.value === value)
  return option ? option.label : value
}

// 根据用户ID获取昵称
const getUserNickname = (userId) => {
  const user = userInit.value.find((item) => item.id === userId)
  return user ? user.nickname : ''
}

//弹框新增逻辑：
const addDialogVisible = ref(false)
const addList = ref([])
const addQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  projectCode: '',
  projectSubName: '',
  customerBrief:''
})
const selectedAddRow = ref([])
const rowClickHandle = (row) => {
  const selectData = selectedAddRow.value
  multipleTableRef.value.clearSelection()
  // if( selectData.length == 1 ) {
  //       selectData.forEach(item => {
  //           // 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
  //           if (item == row) {
  //             multipleTableRef.value.toggleRowSelection(row, false);
  //           }
  //           // 不然就让当前的一行勾选
  //           else {
  //             multipleTableRef.value.toggleRowSelection(row, true);
  //           }
  //       })
  //   }
  //   else {
  //     multipleTableRef.value.toggleRowSelection(row, true);
  //   }
  if (selectData && selectData.length == 1) {
    const [item] = selectData
    const shouldSelect = item !== row
    multipleTableRef.value.toggleRowSelection(row, shouldSelect)
  } else {
    multipleTableRef.value.toggleRowSelection(row, true)
  }
}
// 当用户手动勾选数据行的 Checkbox 时触发的事件
const handlerSelect = (selection, row) => {
  // 清除 所有勾选项
  multipleTableRef.value.clearSelection()
  if (selection.length == 0) return
  multipleTableRef.value.toggleRowSelection(row, true)
}
// 当选择项发生变化时会触发该事件
const handleSelectionChange = (val) => {
  console.log('表格的选中 可以获得当前选中的数据', val)
  selectedAddRow.value = val
}
// 新增按钮方法
const addForm = () => {
  resetAddForm()
  // getAddList()
  addDialogVisible.value = true
}

// 重置新增表单
const resetAddForm = () => {
  addQueryParams.projectCode = ''
  addQueryParams.projectSubName = ''
  selectedAddRow.value = null
}

// 获取可选项目列表
const getAddList = async () => {
  try {
    loading3.value = true
    const params = {
      projectCode: addQueryParams.projectCode,
      projectSubName: addQueryParams.projectSubName,
      customerBrief:addQueryParams.customerBrief,
      pageNo:addQueryParams.pageNo,
      pageSize:addQueryParams.pageSize
    }
    const res = await PlansubdetailApi.pageAddList(params)
    console.log(res)
    addList.value = res.list
    addtotal.value = res.total
  } catch (error) {
    message.error('获取项目列表失败：' + error.message)
  } finally {
    loading3.value = false
  }
}

// 行选择处理
const handleRowSelect = (row) => {
  selectedAddRow.value = row
}

// 取消新增
const handleAddCancel = () => {
  ElMessageBox.confirm('是否退出新增？', '提示', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'warning'
  })
    .then(() => {
      addDialogVisible.value = false
        selectedAddRow.value = []
  multipleTableRef.value.clearSelection()
    })
    .catch(() => {})
}

// 确认新增
const handleAddConfirm = () => {
  for (var i = 0; i < list.value.length; i++) {
    var item = list.value[i]
    if (!item.id) {
      message.warning('列表中存在未保存数据，请确认！')
      return
    }
  }
  if (!selectedAddRow.value) {
    message.warning('请先选择要添加的项目')
    return
  }
  selectedAddRow.value[0].twoDimDate = null
    selectedAddRow.value[0].projectPlanSubId = null
  selectedAddRow.value[0].startTwoDimDate = null
  selectedAddRow.value[0].twoDimOwner = null
  selectedAddRow.value[0].subType = null
  selectedAddRow.value[0].designNum = null
  selectedAddRow.value[0].seqNo = null
  selectedAddRow.value[0].isAdd = 1
  selectedAddRow.value[0].flag = 1
  selectedAddRow.value[0].userFlag = true
  selectedAddRow.value[0].id = null
  list.value.unshift(selectedAddRow.value[0])
  addDialogVisible.value = false
  selectedAddRow.value = []
  multipleTableRef.value.clearSelection()
  message.success('项目添加成功')
}

// 查询按钮操作
const handleAddQuery = () => {
  getAddList()
}

// 添加一个标志位防止无限循环
let isProcessingChange = false
// 检查是否为新增行
const isNewRow = (row) => {
  return row.isAdd === 1
}
const saveForm = async () => {
  try {
    if (list.value) {
      loading.value = true
      for (var i = 0; i < list.value.length; i++) {
        var item = list.value[i]
        if (item.isOverProcess) {
          item.isOverProcess = 1
        } else {
          item.isOverProcess = 0
        }
        if (!item.id) {
          console.log(item)
          var type =
            'BLUEPRINT_WORKBLANK' == item.subType
              ? '毛坯'
              : 'BLUEPRINT_2D' == item.subType
              ? '2D'
              : 'BLUEPRINT_3D' == item.subType
              ? '3D'
              : '新增数据'

          message.error(
            '该子项目' +
              item.name +
              (type == '新增数据' ? '新增数据' : '设计类型：' + type) +
              ' ，没有保存请确认！'
          )
          return
        }
      }
      // 调用后端接口
      const updateReqVO = {
        list: list.value
      }
      const res = await PlansubdetailApi.operate(updateReqVO)
      if (res) {
        message.success('保存成功')
      }
    } else {
      message.error('失败：当前页面无数据可供保存')
    }
    getList()
  } catch (error) {
    // message.error('失败：' + error.message)
  } finally {
    loading.value = false
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    if (queryParams.beginTime) {
      queryParams.startTime = queryParams.beginTime + ' 00:00:00'
    }
    const data = await PlansubdetailApi.getPlanSubDetailPage(queryParams)
    list.value = data.list
    list.value.forEach((item) => {
      item.isAdd = 0
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}
// 添加弹窗相关变量
const dialogVisible = ref(false)
const dialogTitle = ref('插活前')
const currentRow = ref(null)
const insertList = ref([])
const beforeList = ref([])
const modification = async (row) => {
  if (row.subType==null|| row.subType==''){
    message.error('设计类型不能为空')
    return
  }
  if (row.twoDimOwner==null|| row.twoDimOwner==''){
    message.error('负责人不能为空')
    return
  }
beforeList.value = []
  var data = row as unknown as PlansubdetailApi.PlanSubDetailVO
  const res = await PlansubdetailApi.modificationPlanSubDetail(data)
  if (res.list) {
    //弹框
    currentRow.value = row
    res.list.forEach(item =>{
      beforeList.value.push(item)
    })
    insertList.value = res.list
    dialogVisible.value = true
    dialogTitle.value = '插活前'
  } else {
    getList()
    message.success('修改成功')
  }
}

// 新增行方法
const addItemRow = (row) => {
  if (row.id) {
     for (var i = 0; i < list.value.length; i++) {
        var item = list.value[i]
        if (item.isOverProcess) {
          item.isOverProcess = 1
        } else {
          item.isOverProcess = 0
        }
        if (!item.id) {

          var type =
            'BLUEPRINT_WORKBLANK' == item.subType
              ? '毛坯'
              : 'BLUEPRINT_2D' == item.subType
              ? '2D'
              : 'BLUEPRINT_3D' == item.subType
              ? '3D'
              : '新增数据'

          message.error(
            '该子项目' +
              item.name +
              (type == '新增数据' ? '新增数据' : '设计类型：' + type) +
              ' ，没有保存请确认！'
          )
          return
        }
      }
    // 创建新行数据，复制当前行的所有属性
    const newRow = {
      ...row,
      // 清空或重置特定字段
      id: null, // 新增行id为空
      startTwoDimDate: undefined, // 开始日期为空
      twoDimDate: undefined, // 结束日期为空
      designNum: undefined, // 设计天数为空
      seqNo: undefined, // 时间段顺序为空
      isAdd: 1, // 标记为新增行
      flag: 1, // 标记为可编辑状态
      userFlag: true
    }
    const currentIndex  =   list.value.findIndex(item=> item === row);
    if(currentIndex !== -1){
      list.value.splice(currentIndex+1,0,newRow);
    }else{
      list.value.unshift(newRow)
    }


    //message.success('新增行成功')
  } else {
    message.error('该数据未保存，请确认')
  }
}

const getSearchRlTs = async (row, startDateTime: string, endDateTime: string) => {
  let data = await PlanSubApi.getSearchRlTsS(
    formatDate(startDateTime, 'YYYY-MM-DD'),
    formatDate(endDateTime, 'YYYY-MM-DD')
  )
  row.designNum = data
}

const handleCancelDialog = () => {
  ElMessageBox.confirm('是否退出插活？', '提示', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'warning'
  })
    .then(() => {
      dialogVisible.value = false
    })
    .catch(() => {
      // 用户点击否，不做任何操作
    })
}
const handleInsert = async () => {
  loading2.value = true
  // 这里可以添加插活后的逻辑
  if (currentRow.value) {
    const newRow = { ...currentRow.value }
    newRow.id = null // 设置id为空
    insertList.value.push(newRow)
    insertList.value.forEach((item) => {
      if (item.isOverProcess) {
        item.isOverProcess = 1
      } else {
        item.isOverProcess = 0
      }
    })
    try {
      const updateReqVO = {
        list: insertList.value
      }
      // 调用后端接口
      const res = await PlansubdetailApi.chahuoPlanSubDetail(updateReqVO)
      insertList.value = res.list
      dialogTitle.value = '插活后'
      // if (res) {
      //   message.success('插活成功')
      //   dialogVisible.value = false
      //   reload() // 刷新列表
      // }
    } catch (error) {
      message.error('插活失败：' + error.message)
    } finally {
      loading2.value = false
    }
  }
}

// 确认操作
const handleConfirm = async () => {
  // 这里添加确认逻辑
  try {
    loading2.value = true
    const updateReqVO = {
      list: insertList.value
    }
    // 调用后端接口
    const res = await PlansubdetailApi.savechahuoPlanSubDetail(updateReqVO)
    if (res) {
      message.success('插活成功')
      dialogVisible.value = false
      await getList()
    }
  } catch (error) {
    message.error('插活失败：' + error.message)
      await getList()
  } finally {
    loading2.value = false
  }

  dialogVisible.value = false
  message.success('插活成功')
}
// 禁用过去日期
const disabledFutureDates = (time) => {
  // const today = new Date()
  // today.setHours(0, 0, 0, 0)
  // return time.getTime() < today.getTime()
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 计算一周前的日期
  const oneWeekAgo = new Date(today);
  oneWeekAgo.setDate(today.getDate() - 7);

  // 禁用一周前的日期（允许选择一周前到以后的所有日期）
  return time.getTime() < oneWeekAgo.getTime();
}
// 修改删除方法，处理新增行的删除
const handleDelete = async (row) => {
  if (row.isAdd === 1) {
    // 新增行直接从列表中移除
    const index = list.value.findIndex((item) => item === row)
    if (index !== -1) {
      list.value.splice(index, 1)
      message.success('删除成功')
    }
    return
  }

  // 原有行的删除逻辑
  var today = new Date().toLocaleDateString('en-CA')
  var startDate = new Date(row.startTwoDimDate).toLocaleDateString('en-CA')
  if (today > startDate) {
    message.error('当前日期>开始日期，不允许删除')
    return
  }

  try {
    await PlansubdetailApi.deletePlanSubDetail(row.id)
    message.success('删除成功')
    getList() // 刷新列表
  } catch (e) {
    console.error('删除失败:', e)
  }
}
const change1 = async (row: any, type: number) => {
  if (isProcessingChange) return // 防止重复处理
  isProcessingChange = true

  try {
    if (row.twoDimOwner == null || row.twoDimOwner == '') {
      setTimeout(() => {
        message.error('负责人不能为空')
      }, 100)
      if (type === 0) {
        row.startTwoDimDate = undefined
      } else {
        row.twoDimDate = undefined
      }
      return
    }
    if (row.startTwoDimDate && row.twoDimDate) {
      const startTime = new Date(row.startTwoDimDate).getTime()
      const endTime = new Date(row.twoDimDate).getTime()
      getSearchRlTs(row, row.startTwoDimDate, row.twoDimDate)
      if (startTime > endTime) {
        // 使用 setTimeout 避免在渲染过程中直接调用 message.error
        setTimeout(() => {
          message.error('开始日期不能大于结束日期,请确认!')
        }, 100)

        if (type === 0) {
          row.startTwoDimDate = undefined
        } else {
          row.twoDimDate = undefined
        }
        return
      }
    }

    const time = type === 0 ? new Date(row.startTwoDimDate) : new Date(row.twoDimDate)
    if (!time || isNaN(time.getTime()) || formatDate(time, 'YYYY-MM-DD') == '1970-01-01') return

    const data = await PlansubdetailApi.getSearchRlTsS(formatDate(time, 'YYYY-MM-DD'))
    row.time = time.getTime()
    if (data <= 0) {
      setTimeout(() => {
        message.error('选择的日期是节假日,请确认!')
      }, 100)

      if (type === 0) {
        row.startTwoDimDate = undefined
      } else {
        row.twoDimDate = undefined
      }
    }
    if (row.seqNo > 1) {
      const flag = await PlansubdetailApi.getSearchRlT(row)
      if (flag == 0) {
        setTimeout(() => {
          message.error('选择的日期不能小于等于上一段结束日期,请确认!')
        }, 100)

        if (type === 0) {
          row.startTwoDimDate = undefined
        } else {
          row.twoDimDate = undefined
        }
      }
    }
  } finally {
    isProcessingChange = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  if (!queryParams.twoDimOwner) {
    // 使用 setTimeout 避免渲染过程中直接调用 message.error
    setTimeout(() => {
      message.error('负责人为空,请确认')
    }, 100)
    return // 添加 return 防止继续执行
  }
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  // 不要在这里直接调用 handleQuery，避免循环
  queryParams.pageNo = 1
  Object.assign(queryParams, {
    twoDimOwner: undefined,
    subType: undefined,
    startTime: undefined,
    code: undefined,
    name: undefined
  })
  // getList()
}
const route = useRoute()
const routeValue = ref('')
/** 初始化 **/
onMounted(async () => {
  try {
    // 取消注释并正确初始化
    userInit.value = await UserApi.getDeptName('设计部')
      let params = routeParamsCache.get(route.path);
    routeValue.value = route.path
    if (params ) {
      Object.assign(queryParams, params);
    }
    routeValue.value = route.path
    if(queryParams.twoDimOwner){
          await getList()
    }

  } catch (error) {
    console.error('初始化失败:', error)
    setTimeout(() => {
      message.error('初始化数据失败')
    }, 100)
  }
})



onBeforeUnmount(() => {
   console.log(route.path)
  const plainParams = JSON.parse(JSON.stringify(queryParams));
  routeParamsCache.set(routeValue.value, plainParams);
});

window.addEventListener('beforeunload', () => {
  const plainParams = JSON.parse(JSON.stringify(queryParams));
  routeParamsCache.set(routeValue.value, plainParams);
});
</script>
<style scoped>
.dialog-content {
  padding: 20px 0;
}

.date-info {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.status-title {
  margin-top: -7%;
  margin-bottom: 20px;
  text-align: left;
}

.status-title h3 {
  margin: 0;
  color: #303133;
}

.dialog-footer {
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.dialog-footer .el-button {
  margin: 0 10px;
  min-width: 100px;
}
</style>
