<template>
  <div class="app-container">
    <!-- 顶部切换 -->
    <el-radio-group v-model="tabPosition" style="margin: 5px">
      <el-radio-button label="first">物资柜位置</el-radio-button>
      <el-radio-button label="second">物资柜列表</el-radio-button>
    </el-radio-group>

    <!-- 物资柜位置地图 -->
    <div
      v-show="tabPosition === 'first'"
      class="map-container"
    >
      <!-- 缩放容器 -->
      <div
        ref="mapContainer"
        :style="{
          transform: `scale(${scaleFactor})`,
          transformOrigin: 'top left',
          width: '1250px',
          height: '700px',
          position: 'relative',
        }"
      >
        <img
          :style="{ width: jobconfig.width + 'px', height: jobconfig.height + 'px' }"
          :src="jobconfig.imageUrl"
          alt="地图"
        />

        <!-- 岗位和物资柜图标 -->
        <div v-for="item in jobconfigPoint" :key="item.id">
          <div
            class="deptXLG"
            :style="{ left: item.x + 'px', top: item.y + 'px' }"
          >
            {{ item.entityName }}
          </div>

          <!-- 物资柜图标 -->
          <img
            v-for="(cabinet, index) in TicketListPage[item.entityId] || []"
            :key="cabinet.id"
            :style="{
              width: '35px',
              height: '35px',
              position: 'absolute',
              cursor: 'pointer',
              top: (item.y - 40) + 'px',
              left: (
                item.x -
                ((TicketListPage[item.entityId] ? TicketListPage[item.entityId].length * 35 : 0) - 53) / 2 +
                index * 40
              ) + 'px'
            }"
            :src="imageMap[cabinet.status]"
            alt="物资柜"
            @click="handleCabinetClick(cabinet)"
          />
        </div>

        <!-- 异常信息图标 -->
        <img
          style="width: 40px; height: 40px; position: absolute; top: 2%; right: -4%;cursor: pointer;"
          :src="ExceptionTableImage"
          alt="异常"
          @click="showExTable"
        />

        <!-- 异常信息表格 -->
        <div
          v-if="exceptionTableVisible"
          class="exception-table"
        >
          <div class="exception-header">
            <img :src="ExceptionTableImage2" style="width: 20px; height: 20px; margin: 10px" alt=""/>
            <span style="margin: 10px">异常信息</span>
          </div>

          <el-table :data="exceptionTable">
            <el-table-column label="物资柜" prop="loanFromName"/>
            <el-table-column label="异常类型" prop="exceptionType"/>
            <el-table-column label="异常信息" prop="status"/>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 物资柜列表 -->
    <div v-if="tabPosition === 'second'" class="CabinetListcon">
      <el-row :gutter="20">
        <!-- 左侧岗位树 -->
        <el-col :span="4" :xs="24">
          <ContentWrap class="h-1/1">
            <WorkstationTree @nodeClick="handleDeptNodeClick" />
          </ContentWrap>
        </el-col>

        <el-col :span="20" :xs="24">
          <!-- 搜索 -->
          <ContentWrap>
            <el-form
              class="-mb-15px"
              :model="queryParams"
              ref="queryFormRef"
              :inline="true"
              label-width="100px"
            >
<!--              <el-form-item label="物资柜编号" prop="id">-->
<!--                <el-input-->
<!--                  v-model="queryParams.id"-->
<!--                  placeholder="请输入物资柜编号"-->
<!--                  clearable-->
<!--                  @keyup.enter="handleQuery"-->
<!--                  class="!w-240px"-->
<!--                />-->
<!--              </el-form-item>-->
              <el-form-item label="物资柜名称" prop="cabinetName">
                <el-input
                  v-model="queryParams.cabinetName"
                  placeholder="请输入物资柜名称"
                  clearable
                  @keyup.enter="handleQuery"
                  class="!w-240px"
                />
              </el-form-item>
              <el-form-item label="物资柜状态" prop="status">
                <el-select
                  v-model="queryParams.status"
                  placeholder="请选择物资柜状态"
                  clearable
                  class="!w-240px"
                >
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.CABINET_STATUS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
                <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
                <el-button
                  type="primary"
                  plain
                  @click="handleAdd"
                  v-hasPermi="['iscs:cabinet:create']"
                >
                  <Icon icon="ep:plus" /> 新增
                </el-button>
              </el-form-item>
            </el-form>
          </ContentWrap>

          <!-- 列表 -->
          <ContentWrap>
            <el-table v-loading="loading" :data="CabinetList">
              <el-table-column label="物资柜编号" align="center" key="id" prop="id" />
              <el-table-column
                label="物资柜名称"
                align="center"
                prop="cabinetName"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="所属区域"
                align="center"
                prop="workstationName"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="物资柜图片" prop="cabinetPicture" >
                <template #default="scope">
                  <div class="img-box" v-if="scope.row.cabinetPicture">
                    <el-image
                      style="width: 75px; height: 75px"
                      :preview-teleported="true"
                      class="images"
                      :hide-on-click-modal="true"
                      :src="scope.row.cabinetPicture"
                      :zoom-rate="1.2"
                      :preview-src-list="[scope.row.cabinetPicture]"
                      :initial-index="1"
                    />
                    <i class="el-icon-zoom-in" id="eyeicon"></i>
                  </div>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column label="物资柜状态" key="status">
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.CABINET_STATUS" :value="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column label="异常类型" prop="exReason" >
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.EXCEPTION_REASON" :value="scope.row.exReason" />
                </template>
              </el-table-column>
              <el-table-column label="查看" align="center" >
                <template #default="scope">
                    <el-button
                      type="primary"
                      link
                      @click="handleLook(scope.row)"
                    >
                      <Icon icon="ep:view" />查看
                    </el-button>

                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" >
                <template #default="scope">
                  <div class="flex items-center justify-center">
                    <el-button
                      type="primary"
                      link
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['iscs:cabinet:update']"
                    >
                      <Icon icon="ep:edit" />编辑
                    </el-button>
                    <el-button
                      type="primary"
                      link
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['iscs:cabinet:delete']"
                    >
                      <Icon icon="ep:edit" />删除
                    </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>
        </el-col>
      </el-row>
    </div>

    <!-- 表单弹窗：添加/修改 -->
    <CabinetForm ref="formRef" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { handleTree } from '@/utils/tree'
import * as CabinetApi from '@/api/material/lockers'
import * as MarsDeptApi from '@/api/system/marsdept'
import * as MaterialsApi from '@/api/material/information'
import * as doorExceptionApi from '@/api/material/doorException/index'
import * as MapConfigApi from '@/api/basic/mapconfig'
import * as MapPointApi from '@/api/basic/mappoint'
import * as ConfigurationApi from '@/api/basic/configuration'
import CabinetForm from './CabinetForm.vue'
import WorkstationTree from "./lockerTree.vue"

// 响应式数据
const loading = ref<boolean>(true)
const tabPosition = ref<string>('first')
const CabinetList = ref<[]>([])
const total = ref<number>(0)
const queryFormRef = ref()
const formRef = ref()
const mapContainer = ref()
const router = useRouter() // 路由
// 地图相关数据
const jobconfig = ref<any>({
  width: 0,
  height: 0,
  imageUrl: ''
})
const jobconfigPoint = ref<any>({ records: [] })
const scaleFactor = ref<number>(1)
const TicketListPage = ref<{ [key: string]: [] }>({})

// 异常相关数据
const exceptionTableVisible = ref<boolean>(false)
const exceptionTable = ref<[]>([])
const ExceptionTableImage = ref<string>('')
const ExceptionTableImage2 = ref<string>('')



// 图标映射
const imageMap = ref<any>({
  0: '', // 正常
  1: '', // 使用中
  2: ''  // 异常
})

// 查询参数
const queryParams = reactive<any>({
  pageNo: 1,
  pageSize: 10,
  workstationName: '',
  id: '',
  cabinetId: '',
  cabinetName: '',
  status: ''
})

// 监听查询参数变化
watch(() => queryParams.id, (newVal) => {
  if (newVal) {
    const data = {
      pageNo: 1,
      pageSize: -1,
      id: newVal
    }
    getList(data)
  }
})

// 监听tab切换
watch(() => tabPosition.value, (newVal) => {
  if (newVal) {
    getList()
  }
})

// 获取列表数据
const getList = async (params?: Partial<any>): Promise<void> => {
  loading.value = true

  try {
    const queryData = params || queryParams
    const response = await CabinetApi.listMaterialsCabinet(queryData)
    CabinetList.value = response.list
    total.value = response.total
    console.log(response, '所有物资柜')
  } catch (error) {
    console.error('获取列表数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取图标数据
const getIcons = async (): Promise<void> => {
  try {
    const sysAttrKey1 = 'icon.cabinet.normal'
    const sysAttrKey2 = 'icon.cabinet.borrowed'
    const sysAttrKey3 = 'icon.cabinet.abnormal'
    const sysAttrKey4 = 'sys.exception.icon'
    const sysAttrKey5 = 'sys.exception2.icon'

    const responses = await Promise.all([
      ConfigurationApi.getIsSystemAttributeByKey(sysAttrKey1),
      ConfigurationApi.getIsSystemAttributeByKey(sysAttrKey2),
      ConfigurationApi.getIsSystemAttributeByKey(sysAttrKey3),
      ConfigurationApi.getIsSystemAttributeByKey(sysAttrKey4),
      ConfigurationApi.getIsSystemAttributeByKey(sysAttrKey5)
    ])

    imageMap.value[0] = responses[0].sysAttrValue // 正常
    imageMap.value[1] = responses[1].sysAttrValue // 使用中
    imageMap.value[2] = responses[2].sysAttrValue // 异常
    ExceptionTableImage.value = responses[3].sysAttrValue
    ExceptionTableImage2.value = responses[4].sysAttrValue

    console.log(imageMap.value, ExceptionTableImage.value, ExceptionTableImage2.value, 'imageMap')
  } catch (error) {
    console.error('获取图标失败:', error)
  }
}

// 获取异常数据
const getException = async (): Promise<void> => {
  try {
    // 获取所有物资信息
    const materialsResponse = await MaterialsApi.listMaterials({ pageNo: 1, pageSize: -1 })
    const materialsData = materialsResponse.list || []

    // 处理损坏、过期的物资
    const damagedOrExpiredMaterials = materialsData.filter((material: any) =>
      material.status === '1' || material.status === '2'
    )
    const damagedOrExpiredCabinets = Array.from(new Set(
      damagedOrExpiredMaterials.map((material: any) => material.cabinetName)
    ))

    // 处理归还异常的物资
    const misplacedMaterials = materialsData.filter((material: any) => material.status === '3')
    const misplacedCabinets = Array.from(new Set(
      misplacedMaterials.map((material: any) => material.cabinetName)
    ))

    // 整合归还异常的柜子信息
    const misplacedCabinetDetails = misplacedCabinets.map(cabinet => ({
      loanFromName: cabinet,
      exceptionType: '物资放错柜子',
      status: `${misplacedMaterials.filter((material: any) => material.cabinetName === cabinet).length}件物资放错`
    }))

    // 整合损坏、过期的柜子信息
    const damagedOrExpiredCabinetDetails = damagedOrExpiredCabinets.map(cabinet => ({
      loanFromName: cabinet,
      exceptionType: '物资过期损坏',
      status: `${damagedOrExpiredMaterials.filter((material: any) => material.cabinetName === cabinet).length}件物资过期或损坏`
    }))

    // 获取柜门未关闭的数据
    const exceptionResponse = await doorExceptionApi.doorExceptionPage({
      pageNo: 1,
      pageSize: -1,
      exceptionType: 1,
      status: 0
    })

    const unClosedCabinets = exceptionResponse.list || []
    let unClosedCabinetDetails: [] = []

    if (unClosedCabinets.length > 0) {
      unClosedCabinetDetails = unClosedCabinets.map((cabinet: any) => ({
        loanFromName: cabinet.loanFromName,
        exceptionType: '超时未关柜门',
        status: `柜门超过${calculateTimeDifference(cabinet.occurTime)}未关`
      }))
    }

    // 合并所有结果
    const result = [
      ...misplacedCabinetDetails,
      ...damagedOrExpiredCabinetDetails,
      ...unClosedCabinetDetails
    ]

    exceptionTable.value = result.filter((item) => item.loanFromName !== null)
  } catch (error) {
    console.error('获取异常数据失败:', error)
  }
}

// 计算时间差
const calculateTimeDifference = (occurTime: string): string => {
  if (!occurTime) return '未知'

  const occurDate = new Date(occurTime)
  if (isNaN(occurDate.getTime())) {
    console.error('Invalid date format:', occurTime)
    return '未知'
  }

  const pageNoTime = new Date().getTime()
  const timeDifference = (pageNoTime - occurDate.getTime()) / (1000 * 60) // 转换为分钟

  if (timeDifference < 1) {
    return `${(timeDifference * 60).toFixed(0)}秒`
  } else if (timeDifference < 60) {
    return `${timeDifference.toFixed(1)}分钟`
  } else {
    const hours = Math.floor(timeDifference / 60)
    const minutes = (timeDifference % 60).toFixed(0)
    return `${hours}小时${minutes}分钟`
  }
}
// 岗位树节点点击事件
const handleDeptNodeClick = (data): void => {
  queryParams.workstationId = data.id
  queryParams.workstationName = data.workstationName
  getList()
}
// 获取其他数据
const getOtherList = async (): Promise<void> => {
  const data = {
    pageNo: 1,
    pageSize: -1
  }

  try {
    // 获取所有物资柜
    const cabinetResponse = await CabinetApi.listMaterialsCabinet(data)
    console.log(cabinetResponse, '所有物资柜')

    let cabinetByWorkstation: { [key: string]: [] } = {}
    cabinetResponse.list.forEach((cabinet: any) => {
      if (!cabinetByWorkstation[cabinet.workstationId]) {
        cabinetByWorkstation[cabinet.workstationId] = []
      }
      cabinetByWorkstation[cabinet.workstationId].push(cabinet)
    })

    TicketListPage.value = cabinetByWorkstation
    console.log(TicketListPage.value,'TicketListPage.value')

    // 获取物资柜地图
    const sysAttrKey = 'sys.map.cabinet'
    const mapResponse = await ConfigurationApi.getIsSystemAttributeByKey(sysAttrKey)
    console.log(mapResponse, '获取物资柜底图')

    const mapId = mapResponse.sysAttrValue
    const mapConfigResponse = await MapConfigApi.selectIsMapById(mapId)
    console.log(mapConfigResponse, '作业票地图 图片数据')
    jobconfig.value = mapConfigResponse

    // 获取地图点位信息
    const mapPointData = {
      pageNo: 1,
      pageSize: -1,
      mapId: mapResponse.sysAttrValue
    }
    const mapPointResponse = await MapPointApi.getIsMapPointPage(mapPointData)
    console.log(mapPointResponse, '作业票地图岗位位置信息接口')
    jobconfigPoint.value = mapPointResponse.list
  } catch (error) {
    console.error('获取其他数据失败:', error)
  }
}


// 显示异常表格
const showExTable = (): void => {
  exceptionTableVisible.value = !exceptionTableVisible.value
}

// 物资柜点击事件
const handleCabinetClick = (cabinet: any): void => {
  router.push({
    path: '/material/lockers/DetailsIndex',
    query: {
      cabinetId: cabinet.id,
      cabinetName: cabinet.cabinetName
    }
  })
  console.log(cabinet, '地图跳转详情拿到的')
}

// 查看详情
const handleLook = (row: any): void => {
  router.push({
    path: '/material/lockers/DetailsIndex',
    query: {
      cabinetId: row.id,
      cabinetName: row.cabinetName
    }
  })
  console.log('列表详情')
}

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

// 重置按钮操作
const resetQuery = (): void => {
  queryParams.cabinetId = ''
  queryParams.cabinetName = ''
  queryParams.status = ''
  queryFormRef.value?.resetFields()
  handleQuery()
}



// 新增按钮操作
const handleAdd = (): void => {
  formRef.value?.open('create')
}

// 修改按钮操作
const handleUpdate = async (row: any): Promise<void> => {
  formRef.value?.open('update', row.id)
}

// 删除按钮操作
const handleDelete = async (row: any): Promise<void> => {
  try {
    await ElMessageBox.confirm('是否确认删除所选数据项？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await CabinetApi.deleteMaterialsCabinet(row.id)
    ElMessage.success('删除成功')
    await getList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 初始化
onMounted(async () => {
  await Promise.all([
    getList(),
    getOtherList(),
    getException(),
    getIcons()
  ])
})
</script>

<style lang="scss" scoped>
.deptXLG {
  position: absolute;
  width: 65px;
  height: 25px;
  background: #70b26f;
  line-height: 25px;
  text-align: center;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
}

.map-container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  background: white;
  height: 80vh;
}

.exception-table {
  width: 430px;
  height: 300px;
  position: absolute;
  top: 2%;
  right: 0;
  background: white;
}

.exception-header {
  display: flex;
}

.img-box {
  width: 75px;
  height: 75px;
  position: relative;

  #eyeicon {
    display: none;
  }
}

.img-box:hover {
  background: #000;

  .images {
    opacity: 0.6;
  }

  #eyeicon {
    display: block;
    position: absolute;
    top: 40%;
    left: 40%;
    z-index: 100;
    color: white;
    pointer-events: none;
  }
}

.app-container {
  width: 100%;
  height: 100%;
}
</style>
