<template>
  <ContentWrap class="device-overview-wrap" :body-style="{ padding: '0' }">
    <div class="device-overview">
      <div class="device-image-panel">
        <div class="device-image-frame" @click="imagePreview(defaultPicUrl)">
          <el-image :src="defaultPicUrl" class="device-image" fit="cover" />
          <div class="image-preview-mask">
            <Icon icon="ep:zoom-in" />
            <span>{{ t('action.preview') }}</span>
          </div>
        </div>
      </div>
      <div class="device-summary">
        <div class="device-heading">
          <div class="device-heading__main">
            <div class="device-title-row">
              <h1 class="device-title">{{ formData.deviceName || '-' }}</h1>
              <el-tag effect="light" round>
                {{ getDictLabel(DICT_TYPE.PMS_DEVICE_STATUS, formData.deviceStatus) || '-' }}
              </el-tag>
            </div>
            <div class="device-code">
              <Icon icon="ep:postcard" />
              <span>{{ t('iotDevice.code') }}：{{ formData.deviceCode || '-' }}</span>
            </div>
          </div>
          <div class="asset-badge">
            <Icon icon="ep:collection-tag" />
            <span>
              {{ getDictLabel(DICT_TYPE.PMS_ASSET_PROPERTY, formData.assetProperty) || '-' }}
            </span>
          </div>
        </div>

        <div class="summary-grid">
          <div class="summary-item">
            <span class="summary-item__label">{{ t('iotDevice.yfCode') }}</span>
            <strong>{{ formData.yfDeviceCode || '-' }}</strong>
          </div>
          <div class="summary-item">
            <span class="summary-item__label">{{ t('iotDevice.brand') }}</span>
            <strong>{{ formData.brandName || '-' }}</strong>
          </div>
          <div class="summary-item">
            <span class="summary-item__label">{{ t('iotDevice.dept') }}</span>
            <strong>{{ formData.deptName || '-' }}</strong>
          </div>
          <div class="summary-item">
            <span class="summary-item__label">{{ t('info.deviceClass') }}</span>
            <strong>{{ formData.assetClassName || '-' }}</strong>
          </div>
          <div class="summary-item">
            <span class="summary-item__label">{{ t('deviceForm.model') }}</span>
            <strong>{{ formData.model || '-' }}</strong>
          </div>
          <div class="summary-item">
            <span class="summary-item__label">{{ t('devicePerson.rp') }}</span>
            <strong>{{ formData.responsibleNames || '-' }}</strong>
          </div>
        </div>
      </div>
    </div>
  </ContentWrap>
  <ContentWrap
    v-loading="formLoading"
    class="device-detail-wrap"
    :body-style="{ padding: '0 18px 18px' }">
    <el-tabs v-model="activeName" class="device-tabs" @tab-click="handleTabClick">
      <el-tab-pane :label="t('deviceInfo.basicInformation')" name="info">
        <div class="device-record">
          <section class="record-section">
            <div class="record-section__header">
              <span class="section-icon section-icon--blue">
                <Icon icon="ep:office-building" />
              </span>
              <div>
                <h3>制造档案</h3>
                <p>设备生产、供应及质保信息</p>
              </div>
            </div>
            <div class="record-grid">
              <div class="record-item">
                <span>{{ t('deviceInfo.mfg') }}</span>
                <strong>{{ formData.zzName || '-' }}</strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.pd') }}</span>
                <strong>
                  {{ formData.manDate ? formatDate(formData.manDate, 'YYYY-MM-DD') : '-' }}
                </strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.supplier') }}</span>
                <strong>{{ formData.supplierName || '-' }}</strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.warranty') }}</span>
                <strong>
                  {{ formData.expires ? formatDate(formData.expires, 'YYYY-MM-DD') : '-' }}
                </strong>
              </div>
              <div class="record-item record-item--wide">
                <span>{{ t('deviceInfo.ni') }}</span>
                <strong>{{ formData.nameplate || '-' }}</strong>
              </div>
            </div>
          </section>

          <section class="record-section">
            <div class="record-section__header">
              <span class="section-icon section-icon--orange">
                <Icon icon="ep:coin" />
              </span>
              <div>
                <h3>资产折旧</h3>
                <p>采购成本及折旧执行信息</p>
              </div>
            </div>
            <div class="record-grid">
              <div class="record-item">
                <span>{{ t('deviceInfo.pp') }}</span>
                <strong>{{ formData.plPrice || '-' }}</strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.pdate') }}</span>
                <strong>
                  {{ formData.plDate ? formatDate(formData.plDate, 'YYYY-MM-DD') : '-' }}
                </strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.dp') }}</span>
                <strong>{{ formData.plYear || '-' }}</strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.ds') }}</span>
                <strong>
                  {{ formData.plStartDate ? formatDate(formData.plStartDate, 'YYYY-MM-DD') : '-' }}
                </strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.yd') }}</span>
                <strong>{{ formData.plMonthed || '-' }}</strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.yy') }}</span>
                <strong>{{ formData.plAmounted || '-' }}</strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.sy') }}</span>
                <strong>{{ formData.remainAmount || '-' }}</strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.my') }}</span>
                <strong>{{ formData.monthAmount || '-' }}</strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.mmy') }}</span>
                <strong>{{ formData.totalMonth || '-' }}</strong>
              </div>
              <div class="record-item">
                <span>{{ t('deviceInfo.currency') }}</span>
                <strong>{{ formData.currency || '-' }}</strong>
              </div>
            </div>
          </section>

          <section v-if="list.length" class="record-section">
            <div class="record-section__header">
              <span class="section-icon section-icon--green">
                <Icon icon="ep:grid" />
              </span>
              <div>
                <h3>扩展属性</h3>
                <p>设备分类模板补充信息</p>
              </div>
            </div>
            <div class="record-grid">
              <div v-for="field in list" :key="field.sort" class="record-item">
                <span>{{ field.name }}</span>
                <strong>{{ field.value || '-' }}</strong>
              </div>
            </div>
          </section>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="t('deviceInfo.fileLibrary')" name="file">
        <!--        <DeviceUpload ref="fileRef" v-if="loadedTabs.includes('1')" />-->
        <DeviceFile
          ref="fileRef"
          :deviceId="id"
          :deviceName="formData.deviceName"
          v-if="loadedTabs.includes('1')" />
      </el-tab-pane>
      <el-tab-pane :label="t('deviceInfo.deviceBOM')" name="bom">
        <BomList
          ref="bomRef"
          v-model:activeName="activeName"
          :deviceId="id"
          :deviceCategoryName="formData.assetClassName"
          v-if="loadedTabs.includes('2')" />
      </el-tab-pane>
      <el-tab-pane :label="t('deviceInfo.operationRecords')" name="record">
        <RecordList
          ref="recordRef"
          v-model:activeName="activeName"
          :deviceId="id"
          v-if="loadedTabs.includes('3')" />
      </el-tab-pane>
      <el-tab-pane :label="t('deviceInfo.faultRecords')" name="failure">
        <FailureList
          ref="failureRef"
          v-model:activeName="activeName"
          :deviceId="id"
          v-if="loadedTabs.includes('4')" />
      </el-tab-pane>
      <el-tab-pane :label="t('deviceInfo.repairRecords')" name="maintain">
        <MaintainList
          ref="maintainRef"
          v-model:activeName="activeName"
          :deviceId="id"
          v-if="loadedTabs.includes('5')" />
      </el-tab-pane>
      <el-tab-pane :label="t('deviceInfo.maintenanceRecords')" name="maintenance">
        <MaintenanceList
          ref="maintenanceRef"
          v-model:activeName="activeName"
          :deviceId="id"
          v-if="loadedTabs.includes('6')" />
      </el-tab-pane>
      <el-tab-pane :label="t('deviceInfo.inspectionRecords')" name="inspect">
        <InspectList
          ref="inspectRef"
          v-model:activeName="activeName"
          :deviceId="id"
          v-if="loadedTabs.includes('7')" />
      </el-tab-pane>
      <el-tab-pane :label="t('deviceInfo.transferRecords')" name="allot">
        <AllotLogList
          ref="allotRef"
          v-model:activeName="activeName"
          :deviceId="id"
          v-if="loadedTabs.includes('8')" />
      </el-tab-pane>
      <el-tab-pane :label="t('deviceInfo.statusChangeRecords')" name="status">
        <DeviceStatusLogList
          ref="statusRef"
          v-model:activeName="activeName"
          :deviceId="id"
          v-if="loadedTabs.includes('9')" />
      </el-tab-pane>
      <el-tab-pane :label="t('deviceInfo.RPAdjustmentRecords')" name="person">
        <PersonList
          ref="personRef"
          v-model:activeName="activeName"
          :deviceId="id"
          v-if="loadedTabs.includes('10')" />
      </el-tab-pane>

      <!-- 关联设备 -->
      <el-tab-pane :label="t('deviceInfo.associationDevice')" name="association">
        <AssociationDevices
          ref="personRef"
          v-model:activeName="activeName"
          :deviceId="id"
          v-if="loadedTabs.includes('11')" />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { IotDeviceApi, IotDeviceVO } from '@/api/pms/device'
import { DICT_TYPE, getDictLabel } from '@/utils/dict'
import { formatDate } from '../../../utils/formatTime'
import DeviceUpload from '@/views/pms/device/DeviceUpload.vue'
import BomInfo from '@/views/pms/device/bom/BomInfo.vue'
import DeviceFile from '@/views/pms/device/DeviceFile.vue'
import BomList from '@/views/pms/device/bom/BomList.vue'
import FailureList from '@/views/pms/device/FailureList.vue'
import MaintainList from '@/views/pms/device/MaintainList.vue'
import InspectList from '@/views/pms/device/InspectList.vue'
import MaintenanceList from '@/views/pms/device/maintenance/MaintenanceList.vue'
import AllotLogList from '@/views/pms/device/allotlog/AllotLogList.vue'
import DeviceStatusLogList from '@/views/pms/device/statuslog/DeviceStatusLogList.vue'
import PersonList from '@/views/pms/device/personlog/PersonList.vue'
import RecordList from '@/views/pms/device/record/RecordList.vue'
import AssociationDevices from '@/views/pms/device/completeSet/AssociationDevices.vue'
import { createImageViewer } from '@/components/ImageViewer'
import { ref, onMounted } from 'vue'
import { getAccessToken } from '@/utils/auth'

const defaultPicUrl = ref(
  import.meta.env.VITE_BASE_URL + '/admin-api/infra/file/29/get/IntegratedSolution.png'
) // 默认设备图片

defineOptions({ name: 'DeviceDetailInfo' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { params } = useRoute() // 查询参数
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('info') // Tag 激活的窗口
const list = ref([])
const id = params.id
const fileRef = ref() // 搜索的表单
// SPU 表单数据
const formData = ref({
  id: undefined,
  code: undefined,
  name: undefined,
  classification: undefined,
  type: undefined,
  nature: undefined,
  creditCode: undefined,
  tin: undefined,
  corporation: undefined,
  incorporationDate: undefined,
  address: undefined,
  bizScope: undefined,
  registeredCapital: undefined,
  annualTurnove: undefined,
  size: undefined,
  status: undefined,
  remark: undefined,
  deptName: undefined,
  monthAmount: undefined,
  totalMonth: undefined,
  currency: undefined
})
const pics = ref([])
const imgSrc = ref('')
const loadedTabs = ref(['info']) // 记录已加载的标签

/** 获得详情 */
const getDetail = async () => {
  if (id) {
    formLoading.value = true
    try {
      const res = (await IotDeviceApi.getIotDevice(id)) as IotDeviceVO
      formData.value = res
      pics.value.push(res.picUrl)
      if (res) {
        if (res.templateJson) {
          list.value = JSON.parse(res.templateJson)
        }
      }
      if (formData.value.picUrl) {
        defaultPicUrl.value = formData.value.picUrl
      }
    } finally {
      formLoading.value = false
    }
  }
}

const imagePreview = (imgUrl: string) => {
  const token = getAccessToken()
  createImageViewer({
    urlList: [imgUrl],
    headers: {
      Authorization: `Bearer ${token}`
    }
  })
}

const handleTabClick = (tab) => {
  if (!loadedTabs.value.includes(tab.index)) {
    // 这里可以添加每个标签对应的加载逻辑，如果有的话
    loadedTabs.value.push(tab.index)
  }
}

/** 初始化 */
onMounted(async () => {
  await getDetail()
})
</script>
<style scoped lang="scss">
.device-overview-wrap,
.device-detail-wrap {
  overflow: hidden;
  border: 0;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgb(31 45 61 / 6%);
}

.device-overview {
  display: flex;
  min-height: 248px;
  padding: 24px;
  background: radial-gradient(circle at 0 0, rgb(64 158 255 / 13%), transparent 32%),
    linear-gradient(135deg, #f5f9ff 0%, var(--el-bg-color) 46%, var(--el-bg-color) 100%);
}

.device-image-panel {
  display: flex;
  width: 286px;
  min-width: 286px;
  align-items: center;
  justify-content: center;
}

.device-image-frame {
  position: relative;
  width: 252px;
  height: 194px;
  padding: 8px;
  overflow: hidden;
  cursor: zoom-in;
  background: var(--el-bg-color);
  border: 1px solid rgb(64 158 255 / 14%);
  border-radius: 14px;
  box-shadow: 0 12px 30px rgb(39 83 135 / 15%);

  &:hover {
    .device-image {
      transform: scale(1.035);
    }

    .image-preview-mask {
      opacity: 1;
    }
  }
}

.device-image {
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: 9px;
  transition: transform 0.3s ease;
}

.image-preview-mask {
  position: absolute;
  right: 16px;
  bottom: 16px;
  display: flex;
  gap: 6px;
  padding: 6px 11px;
  font-size: 12px;
  color: #fff;
  pointer-events: none;
  background: rgb(20 29 43 / 72%);
  border: 1px solid rgb(255 255 255 / 22%);
  border-radius: 14px;
  opacity: 0.88;
  backdrop-filter: blur(6px);
  align-items: center;
  transition: opacity 0.2s ease;
}

.device-summary {
  flex: 1;
  min-width: 0;
  padding: 4px 10px 0 30px;
}

.device-heading {
  display: flex;
  min-height: 70px;
  padding-bottom: 18px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  align-items: flex-start;
  justify-content: space-between;
}

.device-title-row {
  display: flex;
  gap: 12px;
  min-width: 0;
  align-items: center;

  :deep(.el-tag) {
    flex: none;
    padding: 0 12px;
    font-weight: 600;
  }
}

.device-title {
  max-width: 760px;
  margin: 0;
  overflow: hidden;
  font-size: 24px;
  font-weight: 700;
  line-height: 34px;
  color: var(--el-text-color-primary);
  text-overflow: ellipsis;
  white-space: nowrap;
}

.device-code {
  display: flex;
  gap: 6px;
  margin-top: 8px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
  align-items: center;
}

.asset-badge {
  display: flex;
  gap: 7px;
  padding: 8px 12px;
  margin-top: 2px;
  font-size: 13px;
  color: #80631b;
  background: #fff8e7;
  border: 1px solid #f7e6b4;
  border-radius: 8px;
  align-items: center;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(150px, 1fr));
  gap: 0 26px;
  padding-top: 13px;
}

.summary-item {
  display: flex;
  min-width: 0;
  min-height: 58px;
  padding: 10px 0;
  border-bottom: 1px dashed var(--el-border-color-lighter);
  flex-direction: column;
  justify-content: center;

  strong {
    margin-top: 5px;
    overflow: hidden;
    font-size: 14px;
    font-weight: 600;
    line-height: 20px;
    color: var(--el-text-color-primary);
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.summary-item__label {
  font-size: 12px;
  line-height: 18px;
  color: var(--el-text-color-secondary);
}

.device-tabs {
  :deep(.el-tabs__header) {
    padding: 0 20px;
    margin: 0 -18px 18px;
    background: var(--el-bg-color);
  }

  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
    background-color: var(--el-border-color-lighter);
  }

  :deep(.el-tabs__item) {
    height: 54px;
    padding: 0 17px;
    font-weight: 500;
    color: var(--el-text-color-regular);
  }

  :deep(.el-tabs__item.is-active) {
    font-weight: 600;
    color: var(--el-color-primary);
  }

  :deep(.el-tabs__active-bar) {
    height: 3px;
    border-radius: 3px 3px 0 0;
  }
}

.device-record {
  display: grid;
  gap: 18px;
}

.record-section {
  overflow: hidden;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 10px;
}

.record-section__header {
  display: flex;
  gap: 12px;
  min-height: 68px;
  padding: 14px 20px;
  background: linear-gradient(90deg, #f7faff 0%, var(--el-bg-color) 70%);
  border-bottom: 1px solid var(--el-border-color-lighter);
  align-items: center;

  h3 {
    margin: 0;
    font-size: 15px;
    font-weight: 700;
    line-height: 22px;
    color: var(--el-text-color-primary);
  }

  p {
    margin: 2px 0 0;
    font-size: 12px;
    line-height: 18px;
    color: var(--el-text-color-secondary);
  }
}

.section-icon {
  display: flex;
  width: 38px;
  height: 38px;
  font-size: 18px;
  border-radius: 9px;
  align-items: center;
  justify-content: center;
}

.section-icon--blue {
  color: #3478f6;
  background: #eaf2ff;
}

.section-icon--orange {
  color: #e78324;
  background: #fff2e3;
}

.section-icon--green {
  color: #20a36a;
  background: #e7f8f0;
}

.record-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
}

.record-item {
  display: flex;
  min-width: 0;
  min-height: 76px;
  padding: 15px 20px;
  border-right: 1px solid var(--el-border-color-lighter);
  border-bottom: 1px solid var(--el-border-color-lighter);
  flex-direction: column;
  justify-content: center;

  &:nth-child(4n) {
    border-right: 0;
  }

  span {
    font-size: 12px;
    line-height: 18px;
    color: var(--el-text-color-secondary);
  }

  strong {
    margin-top: 6px;
    font-size: 14px;
    font-weight: 500;
    line-height: 22px;
    color: var(--el-text-color-primary);
    word-break: break-word;
  }
}

.record-item--wide {
  grid-column: span 2;
}

@media (width <= 1399px) {
  .device-image-panel {
    width: 250px;
    min-width: 250px;
  }

  .device-image-frame {
    width: 224px;
    height: 180px;
  }

  .device-summary {
    padding-left: 22px;
  }

  .record-grid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }

  .record-item {
    &:nth-child(4n) {
      border-right: 1px solid var(--el-border-color-lighter);
    }

    &:nth-child(3n) {
      border-right: 0;
    }
  }
}

@media (width <= 991px) {
  .device-overview {
    flex-direction: column;
  }

  .device-image-panel {
    width: 100%;
    min-width: 0;
  }

  .device-summary {
    padding: 24px 0 0;
  }

  .summary-grid {
    grid-template-columns: repeat(2, minmax(140px, 1fr));
  }

  .record-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  .record-item {
    &:nth-child(3n) {
      border-right: 1px solid var(--el-border-color-lighter);
    }

    &:nth-child(2n) {
      border-right: 0;
    }
  }
}

@media (width <= 575px) {
  .device-overview {
    padding: 18px;
  }

  .device-heading {
    gap: 12px;
    flex-direction: column;
  }

  .device-title {
    font-size: 20px;
  }

  .summary-grid,
  .record-grid {
    grid-template-columns: 1fr;
  }

  .summary-item {
    min-height: 54px;
  }

  .record-item,
  .record-item--wide {
    grid-column: span 1;
    border-right: 0;

    &:nth-child(2n),
    &:nth-child(3n),
    &:nth-child(4n) {
      border-right: 0;
    }
  }

  .record-section__header {
    padding: 13px 16px;
  }

  .record-item {
    min-height: 68px;
    padding: 12px 16px;
  }
}
</style>
