<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <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-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="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="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择任务状态"
          clearable
          class="!w-240px"
        >
          <el-option label="全部" value="all" />
          <el-option v-for="(item, key) in filteredTaskStatusMap" :key="key" :label="item" :value="key"/>
        </el-select>
      </el-form-item>
      <el-form-item label="受理单提交人" prop="submitIds">
        <el-select
          class="!w-240px"
          v-model="queryParams.submitIds"
          readonly
          clearable
          placeholder="请选择受理单提交人"
          multiple
          popper-class="user-select-popper"
          @click.stop.prevent="() => handleOpenUserDialog(recheckStrIdsOpts, 'submitIds')"
        >
          <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="submitTime">
        <el-date-picker
          v-model="queryParams.submitTime"
          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>
        <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-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-button type="primary" @click="handleBatchConfirmationFn" :disabled="selectedRows.length === 0">批量办结确认</el-button>
    <el-table ref="tableRef" v-loading="loading" :data="list" :stripe="true" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="40" />
      <el-table-column label="任务单号" align="center" prop="orderNo" min-width="150px" />
      <el-table-column label="使用单位" align="center" prop="unitName" min-width="150px" />
      <el-table-column label="检验性质" align="center" prop="checkType" min-width="120px">
        法定检验
      </el-table-column>
      <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 label="设备数量" align="center" prop="equipNum" min-width="150px"/>
      <el-table-column label="任务单状态" align="center" prop="taskStatus" min-width="150px">
        <template #default="scope">
          <el-tag :type="getTypeColor(scope.row.taskStatus)">{{ PressureTaskOrderTaskStatusMap[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 : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="检验员" align="center" prop="appoinmentUser" min-width="150px">
        <template #default="scope">
          <div v-if="scope.row.appoinmentUser && scope.row.appoinmentUser.length > 0">
            <div v-for="user in scope.row.appoinmentUser" :key="user.id">
              {{ user.nickname }} ({{ user.employeeNo }})
            </div>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="收费方式" align="center" prop="feeType" min-width="100px">
        <template #default="scope">
          {{ PressureFeeTypeMap[scope.row.feeType] }}
        </template>
      </el-table-column>
      <el-table-column label="合同编号" align="center" prop="contractNo" min-width="150px">
        <template #default="scope">
          {{ scope.row.contractNo ? scope.row.contractNo : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="变更记录" align="center" prop="changeLogCount" min-width="100px">
        <template #default="scope">
          <div v-if="scope.row.changeLogCount > 0">
            <el-link type="primary" @click="showChangeLog(scope.row)">{{ scope.row.changeLogCount }}</el-link>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180px" fixed="right">
        <template #default="scope">
          <!-- 认领 -->
          <el-button
            v-if="scope.row.taskStatus === PressureTaskOrderTaskStatus.WAIT_CONFIRM"
            link
            type="primary"
            @click="handleConfirm(scope.row.id,formatArrayDate(scope.row.checkDate))"
          >
            认领
          </el-button>

          <!-- 取消认领 -->
          <el-button
            v-if="scope.row.taskStatus === PressureTaskOrderTaskStatus.CONFIRMED"
            link
            type="primary"
            :disabled="scope.row.manager?.id !== userStore?.user?.id"
            @click="handleCancelConfirm(scope.row.id)"
          >
            取消认领
          </el-button>

          <!-- 办结确认 -->
          <el-button
            link
            type="primary"
            v-if="scope.row.taskStatus == 710"
            @click="handleConfirmationFn(scope.row.id)"
          >
            办结确认
          </el-button>

          <el-button
            link
            type="primary"
            @click="handleEdit(scope.row.id)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 选择人员公共弹窗 -->
  <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>

  <!-- 设置主检项目并认领对话框 -->
  <el-dialog
    v-model="setPipeConfirmDialogVisible"
    title="选择主检管道"
    width="40%"
    :before-close="handleCancelSetPipeInfo"
  >
    <div class="mb-4">
      <el-select
        v-model="selectedOrderItemId"
        placeholder="请选择主检管道"
        clearable
        filterable
        style="width: 100%"
      >
        <el-option
          v-for="pipe in pipeOrderItemList"
          :key="pipe.id"
          :label="pipe.projectName"
          :value="pipe.id"
        />
      </el-select>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancelSetPipeInfo">取消</el-button>
        <el-button type="primary" @click="handleConfirmSetPipeInfo"> 确认认领 </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { formatArrayDate } from '@/utils/formatTime'
import { PipeTaskOrderApi, PipeTaskOrderVO } from '@/api/pressure2/pipetaskorder'
import {
  PressureFeeTypeMap,
  PressureTaskOrderTaskStatusMap,
  PressureTaskOrderTaskStatus,
  PressurePipeCheckTypeMap
} from '@/utils/constants'
import {ElMessageBox, ElMessage, ElTable,  dayjs} from 'element-plus'
import { useRouter } from 'vue-router'
// 在script部分
import { getUserPage } from '@/api/system/user'
import SmartTable from "@/components/SmartTable/SmartTable";
import { getUserList } from '@/api/common/user'
import {useUserStore} from "@/store/modules/user";

// 定义用户搜索相关的响应式变量
const userOptions = ref([])
const userSearchLoading = ref(false)

const router = useRouter()
const tableRef = ref<InstanceType<typeof ElTable>>()
const selectedRows = ref<PipeTaskOrderVO[]>([]) // 选中的行

const setPipeConfirmDialogVisible = ref(false)
const pipeOrderItemList = ref([])
const selectedOrderItemId = ref('')
const selectedOrderId = ref('')

// 通过输入的值查询对应受理单提交人名字
// 远程搜索用户方法
const remoteSearchUsers = (query) => {
  if (query) {
    userSearchLoading.value = true
    getUserPage({
      pageNo: 1,
      pageSize: 10,
      nickName: query
    }).then(response => {
      const users = response.list || []
      userOptions.value = users.map(user => ({
        value: user.id,         // 值是用户ID
        label: user.nickname,   // 显示的是用户昵称
        key: user.id            // 用于v-for的key
      }))
    }).finally(() => {
      userSearchLoading.value = false
    })
  } else {
    userOptions.value = []
  }
}

// 剔除查询模块中不需要的选项
const filteredTaskStatusMap = computed(() => {
  const result = {};

  // 需要剔除的状态
  const excludeStatus = [
    PressureTaskOrderTaskStatus.RECORD_INPUT,   // 记录录入 500
    PressureTaskOrderTaskStatus.RECORD_CHECK,   // 记录校核 510
    PressureTaskOrderTaskStatus.REPORT_INPUT,   // 报告编制 520
    PressureTaskOrderTaskStatus.REPORT_AUDIT,   // 报告审核 600
    PressureTaskOrderTaskStatus.REPORT_APPROVE  // 报告审批 700
  ];

  // 只保留不在排除列表中的状态
  Object.entries(PressureTaskOrderTaskStatusMap).forEach(([key, value]) => {
    if (!excludeStatus.includes(Number(key))) {
      result[key] = value;
    }
  });

  return result;
});

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';
}

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

const loading = ref(true)
const list = ref<PipeTaskOrderVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  orderNo: undefined,
  unitName: undefined,
  checkType: undefined,
  checkDate: [],
  checkUserIds: [],
  submitIds:[],
  contractNo: undefined,
  taskStatus: 'all',
  submitTime: []
})
const queryFormRef = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const params = { ...queryParams }
    if (params.taskStatus === 'all') {
      params.taskStatus = undefined
    }
    const data = await PipeTaskOrderApi.getPipeTaskOrderPage(params)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

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

// 修改后的编辑/查看详情操作
const handleEdit = (id: string) => {
  router.push({
    name: 'PipeTaskOrderView',
    query: {
      id,
      type: 'checker'
    }
  })
}

// 变更记录
const showChangeLog = (row: PipeTaskOrderVO) => {
  console.log('ChangeLog:', row)
}

// 认领
const handleConfirm = async (id: string,checkDate: string) => {

  // 检查检验日期是否在三天内
  // if (checkDate) {

  //   if (checkDate) {
  //     const inspectionStartDate = dayjs(checkDate);
  //     const now = dayjs();
  //     const daysDiff = now.diff(inspectionStartDate, 'day', true); // 精确计算天数差（包含小数）

  //     // 如果当前时间不在检验日期开始后的 3 天内，则不允许认领
  //     if (daysDiff < 0 || daysDiff > 3) {
  //       ElMessage.warning('只能在检验日期开始后的 3 天内进行认领操作');
  //       return;
  //     }
  //   }
  // }

  try {
    await ElMessageBox.confirm('是否认领该任务单？', '认领提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await PipeTaskOrderApi.confirmTaskOrder({ id, "confirm": true })
    ElMessage.success('认领成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('认领失败')
      console.error('Confirm error:', error)
    }
  }

  // selectedOrderId.value = id
  // selectedOrderItemId.value = ''
  // //获取管线
  // const params = {
  //   orderId: selectedOrderId.value
  // }
  // const response = await PipeTaskOrderApi.getPipeByOrderId(params)
  // pipeOrderItemList.value = response || []
  // setPipeConfirmDialogVisible.value = true

}

// 取消认领
const handleCancelConfirm = async (id: string) => {
  try {
    await ElMessageBox.confirm('是否取消认领该任务单？', '取消认领提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await PipeTaskOrderApi.confirmTaskOrder({ id, "confirm": false })
    ElMessage.success('取消认领成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消认领失败')
      console.error('Cancel confirm error:', error)
    }
  }
}

// 批量办结确认
const handleBatchConfirmationFn = async () => {
  const list = tableRef?.value?.getSelectionRows()
  if (list.length === 0) {
    ElMessage.warning('请选择需要办结确认的任务！')
    return
  }
  const flag = list.every(
    (item) => item.taskStatus === PressureTaskOrderTaskStatus.REPORT_CONFIRMATION
  )
  if (!flag) {
    ElMessage.warning('请选择状态为办结确认的任务！')
    return
  }
  const ids = list.map((item) => item.id)
  try {
    await ElMessageBox.confirm('确认要批量办结确认吗？此操作不可撤销。', '办结确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const submitResult = await PipeTaskOrderApi.finishApi({
      ids
    })

    if (submitResult) {
      ElMessage.success('办结确认成功！')
      // 清除所有选择
      tableRef?.value?.clearSelection()
      getList()
    }
  } catch (err) {
    ElMessage.info('已取消办结确认操作')
  }
}

//办结确认
const handleConfirmationFn = async (id: string) => {
  try {
    await ElMessageBox.confirm('确认要办结确认该任务吗？此操作不可撤销。', '办结确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = [id]
    const submitResult = await PipeTaskOrderApi.finishApi({
      ids
    })

    if (submitResult) {
      ElMessage.success('办结确认成功！')
      // 清除所有选择
      tableRef?.value?.clearSelection()
      getList()
    }
  } catch (err) {
    ElMessage.info('已取消办结确认操作')
  }
}

// 人员选择弹窗 start
const userTableRef = ref()
const userStore = useUserStore()
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()
}

const handleCancelSetPipeInfo = () => {
  setPipeConfirmDialogVisible.value = false
  selectedOrderItemId.value = ''
  selectedOrderId.value = ''
}

const handleConfirmSetPipeInfo = async () => {

  if (!selectedOrderItemId.value) {
    ElMessage.warning('请选择主检管道')
    return
  }

  try {
    const params = {
      id : selectedOrderId.value,
      confirm: true,
      orderItemId: selectedOrderItemId.value
    }
    await PipeTaskOrderApi.confirmTaskOrder(params)
    ElMessage.success('认领成功')
    setPipeConfirmDialogVisible.value = false
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('认领失败')
      console.error('Confirm error:', error)
    }
  }
}

// 人员选择弹窗 end

/** 表格选择框变化 */
const handleSelectionChange = (selection: PipeTaskOrderVO[]) => {
  selectedRows.value = selection
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>

</style>
