<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-row :gutter="20" class="flex-wrap" style="margin-right: 0">
        <el-form-item label="工程号" prop="projectNo">
          <el-input
            v-model="queryParams.projectNo"
            placeholder="请输入工程号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="主报告状态" prop="taskStatusList">
          <el-select
            multiple
            v-model="queryParams.taskStatusList"
            placeholder="请选择主报告状态"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="(item, key) in PressureCheckerMyTaskStatusMap"
              :key="key"
              :label="item"
              :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务单号" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入任务单号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="使用单位" prop="unitName">
          <el-input
            v-model="queryParams.unitName"
            placeholder="请输入使用单位"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-collapse-transition>
          <div v-show="isSearchExpanded">
            <el-form-item label="检验性质" prop="checkType">
              <el-select
                v-model="queryParams.checkType"
                placeholder="请选择检验性质"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="(item, key) in PressurePipeCheckTypeMap"
                  :key="key"
                  :label="item"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="检验时间" prop="checkDate">
              <el-date-picker
                v-model="queryParams.checkDate"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                class="!w-240px"
              />
            </el-form-item>
<!--            <el-form-item label="检验员" prop="inspectorName">-->
<!--              <el-input-->
<!--                v-model="queryParams.inspectorName"-->
<!--                placeholder="请输入检验员名称"-->
<!--                clearable-->
<!--                @keyup.enter="handleQuery"-->
<!--                class="!w-240px"-->
<!--              />-->
<!--            </el-form-item>-->
            <el-form-item label="检验员" prop="checkUserIds">
              <el-select
                class="!w-240px"
                v-model="queryParams.checkUserIds"
                readonly
                clearable
                placeholder="请选择检验员"
                multiple
                popper-class="user-select-popper"
                @click.stop.prevent="() => handleOpenUserDialog(recheckStrIdsOpts, 'checkUserIds')"
              >
                <el-option
                  v-for="child in recheckStrIdsOpts"
                  :key="child && child.id"
                  :label="child.nickName"
                  :value="child.id"
                />
              </el-select>
            </el-form-item>
<!--            <el-form-item label="排期人员" prop="manager">-->
<!--              <el-input-->
<!--                v-model="queryParams.manager"-->
<!--                placeholder="请输入排期人员"-->
<!--                clearable-->
<!--                @keyup.enter="handleQuery"-->
<!--                class="!w-240px"-->
<!--              />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="项目负责人" prop="manager">-->
<!--              <el-input-->
<!--                v-model="queryParams.manager"-->
<!--                placeholder="请输入项目负责人"-->
<!--                clearable-->
<!--                @keyup.enter="handleQuery"-->
<!--                class="!w-240px"-->
<!--              />-->
<!--            </el-form-item>-->
            <el-form-item label="项目负责人" prop="managerIds">
              <el-select
                class="!w-240px"
                v-model="queryParams.managerIds"
                readonly
                clearable
                placeholder="请选择项目负责人"
                multiple
                popper-class="user-select-popper"
                @click.stop.prevent="() => handleOpenUserDialog(recheckStrIdsOpts, 'managerIds')"
              >
                <el-option
                  v-for="child in recheckStrIdsOpts"
                  :key="child && child.id"
                  :label="child.nickName"
                  :value="child.id"
                />
              </el-select>
            </el-form-item>
            <!-- 出厂编号 -->
<!--            <el-form-item label="出厂编号" prop="remainingDays">-->
<!--              <el-input-->
<!--                v-model="queryParams.remainingDays"-->
<!--                placeholder="请输入出厂编号"-->
<!--                clearable-->
<!--                @keyup.enter="handleQuery"-->
<!--                class="!w-240px"-->
<!--              />-->
<!--            </el-form-item>-->
            <!-- 剩余期限 -->
<!--            <el-form-item label="剩余期限" prop="remainingDays">-->
<!--              <el-input-->
<!--                v-model="queryParams.remainingDays"-->
<!--                placeholder="请输入剩余期限"-->
<!--                clearable-->
<!--                @keyup.enter="handleQuery"-->
<!--                class="!w-240px"-->
<!--              />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="主检人" prop="mainCheckerIds">-->
<!--              <el-input-->
<!--                v-model="queryParams.mainCheckerIds"-->
<!--                placeholder="请选择"-->
<!--                clearable-->
<!--                @keyup.enter="handleQuery"-->
<!--                class="!w-240px"-->
<!--              />-->
<!--            </el-form-item>-->
            <el-form-item label="主检人" prop="mainCheckerIds">
              <el-select
                class="!w-240px"
                v-model="queryParams.mainCheckerIds"
                readonly
                clearable
                placeholder="请选择主检人"
                multiple
                popper-class="user-select-popper"
                @click.stop.prevent="() => handleOpenUserDialog(recheckStrIdsOpts, 'mainCheckerIds')"
              >
                <el-option
                  v-for="child in recheckStrIdsOpts"
                  :key="child && child.id"
                  :label="child.nickName"
                  :value="child.id"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-collapse-transition>
      </el-row>

      <!-- 按钮区保持不变 -->
      <el-row class="flex justify-end mt-2">
        <el-form-item>
          <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="showSettingDialog">
            <Icon icon="ep:user" class="mr-5px"/>
            审核配置
          </el-button>
          <el-button link @click="isSearchExpanded = !isSearchExpanded">
            <el-icon>
              <ArrowUp v-if="isSearchExpanded"/>
              <ArrowDown v-else/>
            </el-icon>
            {{ isSearchExpanded ? '收起' : '展开' }}
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>
<!--    <el-radio-group v-model="filterStatus" @change="handleStatusFilter" style="margin-top: 20px;">-->
<!--      <el-radio-button label="全部" value="all"/>-->
<!--      <el-radio-button label="已认领" value="claim"/>-->
<!--      <el-radio-button label="待认领" value="unclaim"/>-->
<!--    </el-radio-group>-->
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" ref="MyTaskTableListRef"
              border
              class-name="cursor-pointer" @row-dblclick="handleRowDblclick">
      <el-table-column type="selection" align="center" width="55"/>
      <el-table-column
        label="剩余期限 (工作日)"
        align="center"
        prop="remainingDays"
        min-width="140px"
      />
      <el-table-column label="任务单号" align="center" prop="orderNo" min-width="150px"/>
      <el-table-column label="工程号" align="center" prop="projectNoList" min-width="200px">
        <template #default="{ row }">
          <div class="project-info"
               v-for="(item, index) in row.projectNoList"
               :key="item?.id || index">
            <el-tag type="success" class="project-name-tag">{{ item }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="使用单位" align="center" prop="unitName" min-width="150px"/>
      <el-table-column label="检验性质" align="center" prop="checkType" min-width="120px">
        <template #default="scope">
          {{ PressurePipeCheckTypeMap[scope.row.checkType] }}
        </template>
      </el-table-column>

      <!-- 检验项目 -->
      <el-table-column align="center" prop="reportDOList" :min-width="200">
<!--        <template #default="scope">
          <div v-if="scope.row.reportDOList && scope.row.reportDOList.length > 0">
            <div class="reportDOList-item">
              &lt;!&ndash; 数据大于2条时，使用展开收起功能 &ndash;&gt;
              <div v-if="scope.row.reportDOList.length > 2">
                &lt;!&ndash; 始终显示的前2条数据 &ndash;&gt;
                <div
                  v-for="(item, index) in scope.row.reportDOList.slice(0, 2)"
                  :key="item?.id || index"
                  class="report-item"
                >
                  <div style="color: #015293">
                    {{ index + 1 }}、{{ item?.reportName }}
                  </div>
                  <div v-if="item?.fee" style="color: #015293">
                    (费用：{{ item?.fee }})
                  </div>
                </div>

                &lt;!&ndash; 可展开的剩余数据 &ndash;&gt;
                <div
                  class="expandable-content"
                  :style="{
                    maxHeight: isExpanded(scope.row)
                      ? `${(scope.row.reportDOList.length - 2) * 40}px`
                      : '0px',
                    transition: 'max-height 0.4s cubic-bezier(0.4, 0, 0.2, 1)',
                    overflow: 'hidden'
                  }"
                >
                  <div
                    v-for="(item, index) in scope.row.reportDOList.slice(2)"
                    :key="item?.id || `extra-${index}`"
                    class="report-item-animated"
                    :style="{
                      opacity: isExpanded(scope.row) ? 1 : 0,
                      transform: isExpanded(scope.row) ? 'translateY(0)' : 'translateY(-10px)',
                      transition: `all 0.3s ease ${index * 50}ms`,
                      padding: '2px 0'
                    }"
                  >
                    <div link type="primary" style="color: #015293">
                      {{ index + 3 }}、{{ item?.reportName }}
                    </div>
                    <div v-if="item?.fee" style="color: #015293">
                    (费用：{{ item?.fee }})
                  </div>
                  </div>
                </div>

                &lt;!&ndash; 展开收起按钮 &ndash;&gt;
                <div class="expand-control" style="text-align: center; margin-top: 8px">
                  <el-button
                    size="small"
                    link
                    type="primary"
                    @click="toggleExpand(scope.row)"
                    class="expand-button"
                    :style="{
                      transition: 'all 0.2s ease'
                    }"
                  >
                    <span style="margin-right: 4px">
                      {{
                        isExpanded(scope.row)
                          ? '收起'
                          : `查看更多(${scope.row.reportDOList.length - 2}条)`
                      }}
                    </span>
                    <el-icon
                      :style="{
                        width: '12px',
                        height: '12px',
                        display: 'inline-block',
                        transition: 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                        transform: isExpanded(scope.row) ? 'rotate(180deg)' : 'rotate(0deg)'
                      }"
                    >
                      <ArrowDown />
                    </el-icon>
                  </el-button>
                </div>
              </div>

              &lt;!&ndash; 数据小于等于2条时，直接显示所有数据 &ndash;&gt;
              <div v-else>
                <div
                  v-for="(item, index) in scope.row.reportDOList"
                  :key="item?.id || index"
                  class="report-item"
                >
                  <div style="color: #015293">
                    {{ index + 1 }}、{{ item?.reportName }}
                  </div>
                  <div v-if="item?.fee" style="color: #015293">
                   (费用：{{ item?.fee }})
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="empty-data">-</div>
        </template>-->
        <template #header>
          <span class="table-header-content">
            检验项目
            <el-tooltip placement="bottom" effect="light" popper-class="status-help-tooltip">
              <template #content>
                <div class="status-help-content">
                  <div class="help-title">状态说明</div>
                  <div class="status-list">
                    <div
                      v-for="item in statusList"
                      :key="item.status"
                      class="status-item"
                    >
                      <div class="color-dot" :style="{ backgroundColor: item.color }"></div>
                      <span class="status-label">{{ item.label }}</span>
                    </div>
                  </div>
                </div>
              </template>
              <el-icon class="help-icon">
                <QuestionFilled/>
              </el-icon>
            </el-tooltip>
          </span>
        </template>
        <template #default="scope">
          <PipeReportList :row="scope.row"/>
        </template>
      </el-table-column>

<!--      <el-table-column label="任务状态" align="center" prop="isClaim" min-width="150px">-->
<!--        <template #default="scope">-->
<!--          <el-tag :type="getTypeColor(scope.row.isClaim ? 400 : 100)">{{-->
<!--              PressureTaskOrderTaskStatusMap[scope.row.isClaim ? 400 : 100]-->
<!--            }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="主报告状态" align="center" prop="taskStatus" min-width="150px">
        <template #default="scope">
          <el-tag :type="getTypeColor(scope.row.taskStatus)">{{
              PressureCheckerMyTaskStatusMap[scope.row.taskStatus]
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="检验时间" align="center" prop="checkDate" min-width="120px">
        <template #default="scope">
          {{ formatArrayDate(scope.row.checkDate) }}
        </template>
      </el-table-column>
      <el-table-column label="项目负责人" align="center" prop="manager" min-width="120px">
        <template #default="scope">
          {{
            scope.row.manager
              ? scope.row.manager.nickname + ' (' + scope.row.manager.employeeNo + ')'
              : '-'
          }}
        </template>
      </el-table-column>
      <!-- 主检人 -->
      <el-table-column label="主检人" align="center" prop="mainInspector" min-width="120px">
        <template #default="scope">
          {{
            scope.row.mainCheckerUser
              ? scope.row.mainCheckerUser.nickname +
              ' (' +
              scope.row.mainCheckerUser.employeeNo +
              ')'
              : '-'
          }}
        </template>
      </el-table-column>
      <el-table-column label="检验员" align="center" prop="checkUsers" min-width="150px">
        <template #default="scope">
          <div v-if="scope.row.checkUsers && scope.row.checkUsers.length > 0">
            <div v-for="user in scope.row.checkUsers" :key="user.id">
              {{ user.nickname }} ({{ user.employeeNo }})
            </div>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <!--排期人员 -->
<!--      <el-table-column label="排期人员" align="center" prop="planCheckUsers" min-width="120px">-->
<!--        <template #default="scope">-->
<!--          {{-->
<!--            scope.row.planCheckUsers-->
<!--              ? scope.row.planCheckUsers.nickname +-->
<!--              ' (' +-->
<!--              scope.row.planCheckUsers.employeeNo +-->
<!--              ')'-->
<!--              : '-'-->
<!--          }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" min-width="150px" fixed="right">
        <template #default="scope">
          <div class="flex flex-col gap-1">
<!--            <el-button-->
<!--              v-if="!scope.row.mainCheckerUser"-->
<!--              link-->
<!--              type="primary"-->
<!--              @click="handleClaim(scope.row.id)"-->
<!--            >-->
<!--              认领-->
<!--            </el-button>-->
            <el-button 
              link 
              type="primary" 
              :disabled="!canCheckInput(scope.row)"
              @click="handleCheckInput(scope.row.id,scope.row.orderId)">
              检验录入
            </el-button>
            <el-button
              link
              type="primary"
              @click="printProject(scope.row.reportDOList)"
            >
              打印项目
            </el-button>
<!--            <el-button-->
<!--                v-if="scope.row.taskStatus == 400 && scope.row.isClaim == true && scope.row.mainCheckerUser && userStore.user.id === scope.row.mainCheckerUser.id"-->
<!--                link-->
<!--                type="primary"-->
<!--                @click="handleCancelClaim(scope.row.id)"-->
<!--              >-->
<!--                取消认领-->
<!--              </el-button>-->
            <el-button v-if="scope.row.mainCheckerUser && userStore.user.id === scope.row.mainCheckerUser.id" link type="primary" @click="handleFinishCheck(scope.row.id,scope.row.endCheckDate)">
              结束检验
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <SettingDialog ref="formRef" />

  <!-- 结束检验弹窗 -->
  <endCheckForm ref="endCheckFormRef" @success="handleScheduleSuccess" />

  <!-- 选择人员公共弹窗 -->
  <CustomDialog
    v-model="customUserDialogVisible"
    :dialogAttrs="{
      zIndex: 10006
    }"
    @confirm="handleUserConfirm"
  >
    <el-input
      v-model="userQueryData.nickName"
      clearable
      placeholder="请输入名称"
      @keyup.enter="handleFetchUserList"
      style="margin-bottom: 14px"
    >
      <template #append>
        <el-button @click="handleFetchUserList">
          <Icon icon="ep:search" />
        </el-button>
      </template>
    </el-input>

    <SmartTable
      ref="userTableRef"
      v-model:pageNo="userQueryData.pageNo"
      v-model:pagesize="userQueryData.pageSize"
      :total="userQueryData.total"
      v-model:columns="userColumns"
      :data="userTableList"
      :buttons="[]"
      :showSettingTools="false"
      :showSearch="false"
      :showRefresh="false"
      @on-page-size-change="onPageSizeChange"
      @on-page-no-change="onPageNoChange"
    />
  </CustomDialog>
  <CustomDialog
    v-model="printProjectDialogVisible"
    :close-on-click-modal="true"
  >
    <el-table
      :data="printProjectList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        align="center"
      />
      <el-table-column
        label="序号"
        width="60"
        align="center"
        type="index"
      />
      <el-table-column
        label="项目"
        align="center"
        prop="reportName"
      />
      <el-table-column
        label="项目状态"
        align="center"
        prop="taskStatus"
      >
        <template #default="scope">
          <el-tag :type="getTypeColor(scope.row.taskStatus)">
            {{ PressureTaskOrderTaskStatusMap[scope.row.taskStatus] }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button type="success" @click="handlePrint">打印</el-button>
      <el-button type="danger" @click="handleDownload">下载</el-button>
    </template>
  </CustomDialog>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, computed} from 'vue'
import {formatArrayDate} from '@/utils/formatTime'
//import SettingDialog from './components/SettingDialog.vue'
import {PipeTaskOrderApi, PipeTaskOrderOrderItemVO} from '@/api/pressure2/pipetaskorder'
import {
  PressureCheckerMyTaskStatus,
  PressureCheckerMyTaskStatusMap, PressurePipeCheckTypeMap,
  PressureTaskOrderTaskStatus, PressureTaskOrderTaskStatusMap
} from '@/utils/constants'
import {ElMessageBox, ElMessage} from 'element-plus'
import {useRoute, useRouter} from 'vue-router'
import {ArrowDown, ArrowUp, QuestionFilled} from "@element-plus/icons-vue";
import { useUserStore } from '@/store/modules/user'
import {useEmitt} from "@/hooks/web/useEmitt";
import endCheckForm from './components/endCheckForm.vue'
import SmartTable from "@/components/SmartTable/SmartTable";
import { getUserList } from '@/api/common/user'
import SettingDialog from "@/views/pressure/checker/components/SettingDialog.vue";
import {PipeInputApi} from "@/api/pressure2/pipeInput";
import 'https://printjs-4de6.kxcdn.com/print.min.js'
import PipeReportList from "@/views/pressure2/pipeReportPreparationList/PipeReportList.vue";
const { emitter } = useEmitt()
const router = useRouter()
const route = useRoute()

const userStore = useUserStore()
const loginUser = useUserStore().user;

const getTypeColor = (status: string | number) => {
  const statusMap = {
    [PressureTaskOrderTaskStatus.WAIT_CONFIRM]: 'primary',
    [PressureTaskOrderTaskStatus.CANCELLED]: 'info',
    [PressureTaskOrderTaskStatus.AUDITING_EDIT]: 'warning',
    [PressureTaskOrderTaskStatus.AUDITING_CANCEL]: 'warning',
    [PressureTaskOrderTaskStatus.AUDITING_TIME]: 'warning',
    [PressureTaskOrderTaskStatus.CONFIRMED]: 'success',
    [PressureTaskOrderTaskStatus.RECORD_INPUT]: 'warning',
    [PressureTaskOrderTaskStatus.RECORD_CHECK]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_INPUT]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_AUDIT]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_APPROVE]: 'warning',
    [PressureTaskOrderTaskStatus.REPORT_END]: 'success'
  }
  return statusMap[status] || 'info'
}

const statusList = [
  { status: PressureCheckerMyTaskStatus.CONFIRMED, label: '待录入', color: '#5B9BD5' },
  { status: PressureCheckerMyTaskStatus.RECORD_INPUT, label: '记录录入', color: '#70AD47' },
  { status: PressureCheckerMyTaskStatus.RECORD_CHECK, label: '记录校核', color: '#9973C2' },
  { status: PressureCheckerMyTaskStatus.REPORT_INPUT, label: '报告编制', color: '#FFC000' },
  { status: PressureCheckerMyTaskStatus.REPORT_AUDIT, label: '报告审核', color: '#ED7D31' },
  { status: PressureCheckerMyTaskStatus.REPORT_APPROVE, label: '报告审批', color: '#FF8DC7' },
  { status: PressureCheckerMyTaskStatus.REPORT_END, label: '报告办结', color: '#303133' }
]

/** 承压任务单 列表 */
defineOptions({name: 'PipeMyTask'})

const isSearchExpanded = ref(false)
// 状态筛选
const filterStatus = ref('all') // 默认选中全部
const loading = ref(true)
const list = ref<PipeTaskOrderOrderItemVO[]>([])
const total = ref(0)
const queryParams = reactive<Recordable>({
  pageNo: 1,
  pageSize: 10,
  unitCode: undefined,
  unitName: undefined,
  orderNo: undefined,
  checkType: undefined,
  checkDate: [],
  checkUserIds: [],
  mainCheckerIds: [],
  managerIds: [],
  isClaim: 'all',
  taskStatusList: undefined,
  remainingDays: undefined
})
const queryFormRef = ref()
const formRef = ref()
const endCheckFormRef = ref()

const showSettingDialog = () => {
  formRef.value.open()
}
const MyTaskTableListRef = ref() // table的实例

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const params: any = {...queryParams}
    const data = await PipeTaskOrderApi.getTaskOrderOrderItemPage(params)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取我的任务列表失败:', error)
    ElMessage.error('获取我的任务列表失败')
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

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

// 判断是否可以检验录入：当前用户是检验员或主检人
const canCheckInput = (row: PipeTaskOrderOrderItemVO) => {
  const userId = userStore.user.id
  // 检查是否是主检人
  if (row.mainCheckerUser && row.mainCheckerUser.id === userId) {
    return true
  }
  // 检查是否是检验员
  if (row.checkUsers && row.checkUsers.length > 0) {
    return row.checkUsers.some(user => user.id === userId)
  }
  return false
}

// 检验录入
const handleCheckInput = (id: string,orderId: string) => {
  router.push({ name: 'PipeCheckerTaskDetail', query: { id, orderId:orderId, type: 'PipeMyTask' } })
}

// 添加结束检验时间
const handleFinishCheck = (id: string,endCheckDate: any) => {
  endCheckFormRef.value.open(id,endCheckDate)
}

const printProjectDialogVisible = ref(false)
const printProjectList = ref([])
const selectionProject = ref([])
const printProject = (reportDOList) => {
  printProjectDialogVisible.value = true
  printProjectList.value = reportDOList
}

const handleSelectionChange = (selection) => {
  // 根据表格的序号重新排序 selection
  const sortedSelection = selection.map(item => {
    // 在原始数据中查找该项的索引
    const index = printProjectList.value.findIndex(v => v.id === item.id)
    return {
      ...item,
      _index: index // 临时存储原始索引
    }
  })
  
  // 按照索引排序
  sortedSelection.sort((a, b) => a._index - b._index)
  
  // 移除临时索引字段
  selectionProject.value = sortedSelection.map(({ _index, ...rest }) => rest)
}

const handleDownload = async () => {

  // 判空检查
  if (!selectionProject.value || selectionProject.value.length === 0) {
    ElMessage.warning('请先选择要下载的项目')
    return
  }

  let data: any[] = []
  console.log(selectionProject)
  selectionProject.value.forEach(
    (item) => {
      data.push({
        taskStatus: item.taskStatus,
        resultTemplateId: item.resultTemplateId,
        templateId: item.templateId,
        reportTemplateId: item.reportTemplateId,
        reportUrl: item.reportUrl,
        id: item.id,
      })
    }
  )

  let loadingInstance = ElLoading.service({
    lock: true,
    text: '正在下载...',
    spinner: 'el-icon-loading',
  })

  try {
    // 调用 API 获取 ZIP blob
    const zipBlob = await PipeInputApi.handleDownload(data)
    
    if (zipBlob) {
      // 创建临时 URL
      const zipUrl = URL.createObjectURL(zipBlob)
      
      // 创建隐藏的 a 标签触发下载
      const link = document.createElement('a')
      link.href = zipUrl
      link.download = '管道检测录入报告.zip'
      document.body.appendChild(link)
      link.click()
      
      // 清理 DOM 和 URL
      document.body.removeChild(link)
      URL.revokeObjectURL(zipUrl)
      
      ElMessage.success('下载成功')
    } else {
      ElMessage.error('获取下载文件失败')
    }
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  } finally {
    loadingInstance.close()
  }
}

const handlePrint = async () => {

  // 判空检查
  if (!selectionProject.value || selectionProject.value.length === 0) {
    ElMessage.warning('请先选择要打印的项目')
    return
  }

  let data: any[] = []
  selectionProject.value.forEach(
    (item) => {
      data.push({
        taskStatus: item.taskStatus,
        resultTemplateId: item.resultTemplateId,
        templateId: item.templateId,
        reportTemplateId: item.reportTemplateId,
        reportUrl: item.reportUrl,
        id: item.id,
      })
    }
  )
  let loadingInstance = ElLoading.service({
    lock: true,
    text: '正在打印...',
    spinner: 'el-icon-loading',
  })
  try {
    // 调用 API 获取 PDF blob
    const pdfBlob = await PipeInputApi.handlePrint(data)
    
    if (pdfBlob) {
      // 创建临时 URL
      const pdfUrl = URL.createObjectURL(pdfBlob)
      
      // 使用 printJS 打印
      printJS({
        printable: pdfUrl,
        type: 'pdf',
        showModal: false,
        onPrintDialogClose: () => {
          // 打印对话框关闭后释放 URL
          URL.revokeObjectURL(pdfUrl)
        }
      })
    } else {
      ElMessage.error('获取打印文件失败')
    }
  } catch (error) {
    console.error('打印失败:', error)
    ElMessage.error('打印失败')
  }finally {
    loadingInstance.close()
  }
}

/** 修改成功处理 */
const handleScheduleSuccess = () => {
  //通知父组件刷新数据
  getList()
}
const handleRowDblclick = (row: Record<string, any>) => {
  if (row.isClaim === false) {
    return
  }
  router.push({ name: 'PipeCheckerTaskDetail', query: { id: row.id, type: 'PipeReportPreparationList' } })
}

const handleClaim = (id: string) => {
  ElMessageBox.confirm('是否确认认领?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      PipeTaskOrderApi.claim({id: id}).then(() => {
        ElMessage.success('认领成功')
        getList()
      })
    })
    .catch(() => {
    })
}

//取消认领
const handleCancelClaim = (id: string) => {
  ElMessageBox.confirm('是否取消认领?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      PipeTaskOrderApi.cancelClaim({id: id}).then(() => {
        ElMessage.success('取消认领成功')
        getList()
      })
    })
    .catch(() => {
    })
}

/** 处理状态筛选 */
const handleStatusFilter = () => {
  // 设置状态筛选
  queryParams.isClaim = filterStatus.value
  // 重置页码并触发查询
  queryParams.pageNo = 1
  getList()
}

// 存储展开状态的响应式数据
const expandedRows = ref(new Set())
// 判断行是否展开
const isExpanded = (row) => {
  return expandedRows.value.has(row.id || JSON.stringify(row))
}
// 切换展开状态
const toggleExpand = (row) => {
  const rowKey = row.id || JSON.stringify(row)
  if (expandedRows.value.has(rowKey)) {
    expandedRows.value.delete(rowKey)
  } else {
    expandedRows.value.add(rowKey)
  }
}

// 人员选择弹窗
const userTableRef = ref()
const userInfo = computed(() => userStore.user)
const fieldKey = ref('')
const customUserDialogVisible = ref(false)
const checkFormOptions = ref<any[]>([])
interface UserListQuery {
  nickName: string
  pageNo: number
  pageSize: number
  total?: number
}
const userQueryData = reactive<UserListQuery>({
  nickName: '',
  pageNo: 1,
  pageSize: 10,
  total: 0
})
const recheckStrIdsOpts = ref<any[]>([
  { id: userInfo.value.id, nickName: userInfo.value?.nickname }
])
const userTableList = ref<any[]>([])
const userColumns = ref<any[]>([
  {
    type: 'selection',
    width: '50px'
  },
  {
    label: '工号',
    prop: 'employeeNo'
  },
  {
    label: '姓名',
    prop: 'nickname'
  },
  {
    label: '部门',
    prop: 'deptName'
  }
])

const handleUserConfirm = () => {
  const selectRows = userTableRef.value.getTableRef().getSelectionRows()
  // 过滤组合合成options
  const currOptions = checkFormOptions.value.map((item) => item.id) || []
  selectRows
    .filter((item) => !currOptions.includes(item.id))
    .forEach((item) => {
      checkFormOptions.value.push({
        id: item.id,
        nickName: item.nickname,
        employeeNo: item.employeeNo
      })
    })
  queryParams[fieldKey.value] = [
    ...new Set([...queryParams[fieldKey.value], ...selectRows.map((row) => row.id)])
  ]
  customUserDialogVisible.value = false
}
// 打开用户选择框
const handleOpenUserDialog = (options: any, key: string) => {
  checkFormOptions.value = options
  userQueryData.nickName = ''
  fieldKey.value = key
  userQueryData.pageNo = 1
  userQueryData.pageSize = 10
  handleFetchUserList()
}

// 获取用户信息
const handleFetchUserList = async () => {
  const queryParams: UserListQuery = {
    ...userQueryData
  }
  delete queryParams.total
  const result = await getUserList(queryParams)
  userTableList.value = result.list
  userQueryData.total = result.total
  customUserDialogVisible.value = true
}

const onPageSizeChange = (val) => {
  userQueryData.pageSize = val
  handleFetchUserList()
}
const onPageNoChange = (val) => {
  userQueryData.pageNo = val
  handleFetchUserList()
}

watch(() => route.path, async () => {
  if (route.path === '/gdjy/my-task/pipe') {
    await getList()
  }
})

/** 初始化 **/
onMounted(() => {
  getList()
  emitter.on('refresh-my-task-pipe', ()=> {
    getList();
  })
})
onUnmounted(() => {
  emitter.off('refresh-my-task-pipe')
})

</script>

<style lang="scss" scoped>
.project-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.project-no {
  width: 100%;
  text-align: center;
  margin-bottom: 2px;
}

.project-name-tag {
  max-width: 100%;
  display: inline-flex;

  .project-name-text {
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 180px;
  }
}

.status-help-content {
  padding: 16px;
  min-width: 180px;
}

.help-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
}

.status-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 6px 8px;
  border-radius: 6px;
  transition: background-color 0.2s ease;
}

.status-item:hover {
  background-color: #f5f7fa;
}

.color-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
  flex-shrink: 0;
}

.status-label {
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
}
.report-name-list {
  position: relative;
  .collapsed::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 15px;
    background: linear-gradient(transparent, rgba(255, 255, 255, 0.9));
    pointer-events: none;
  }
}
</style>
