<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';

import { Page } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';

import { ElImageViewer } from 'element-plus';

import { assetLogList, getAssetDetail } from '#/api/system/asset/asset';
import { DictTag } from '#/components/dict/index';
import { getDictOptions } from '#/utils/dict';

const route = useRoute();
const assetId = route.params.id as string;
const assetDetail = ref<any>(null);
const loading = ref(true);
const activeTab = ref('1'); // 1操作日志 2维修记录

// 表格数据
const operationLogs = ref<any[]>([]);
const maintenanceLogs = ref<any[]>([]);
const tableLoading = ref(false);

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

const dictRef: any = ref([]);

// 图片预览相关
const previewVisible = ref(false);
const previewImages = ref<string[]>([]);

// 预览图片
const previewImage = (imageUrl: string) => {
  previewImages.value = [imageUrl];
  previewVisible.value = true;
};

// 关闭图片预览
const closePreview = () => {
  previewVisible.value = false;
};

onMounted(async () => {
  dictRef.value = await getDictOptions(DictEnum.ASSET_STATUS);
  await loadAssetDetail();
  await loadLogs(1);
});

async function loadAssetDetail() {
  try {
    loading.value = true;
    const res = await getAssetDetail(assetId);
    assetDetail.value = res?.data || res;
  } catch (error) {
    console.error('获取资产详情失败:', error);
  } finally {
    loading.value = false;
  }
}

async function loadLogs(type: number) {
  try {
    tableLoading.value = true;
    const res = await assetLogList({
      assetId,
      type,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
    });

    if (type === 1) {
      operationLogs.value = res.rows || [];
    } else {
      maintenanceLogs.value = res.rows || [];
    }
    pagination.total = res.total || 0;
  } catch (error) {
    console.error('获取日志失败:', error);
  } finally {
    tableLoading.value = false;
  }
}

function handleTabChange(tab: any) {
  activeTab.value = tab.props.name;
  loadLogs(Number.parseInt(tab.props.name));
}

function handlePageChange(val: number) {
  pagination.currentPage = val;
  loadLogs(Number.parseInt(activeTab.value));
}

function handleSizeChange(val: number) {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  loadLogs(Number.parseInt(activeTab.value));
}
</script>

<template>
  <Page :auto-content-height="true" :loading="loading">
    <!-- 资产信息 -->
    <div v-if="assetDetail" class="bg-white p-6 shadow">
      <el-descriptions :column="4" title="资产详情">
        <el-descriptions-item label="资产类型">
          {{ assetDetail.typeName }}
        </el-descriptions-item>
        <el-descriptions-item label="资产名称">
          {{ assetDetail.assetName }}
        </el-descriptions-item>
        <el-descriptions-item label="资产编码">
          {{ assetDetail.assetCode }}
        </el-descriptions-item>
        <el-descriptions-item label="所在油站">
          {{ assetDetail.stationName }}
        </el-descriptions-item>

        <el-descriptions-item label="生产厂商">
          {{ assetDetail.manufacturer }}
        </el-descriptions-item>
        <el-descriptions-item label="生产厂商联系人">
          {{ assetDetail.manufacturerContact }}
        </el-descriptions-item>
        <el-descriptions-item label="资产生产日期">
          {{ assetDetail.productionDate }}
        </el-descriptions-item>
        <el-descriptions-item label="资产投用日期">
          {{ assetDetail.useDate }}
        </el-descriptions-item>

        <el-descriptions-item label="资产使用年限">
          {{ assetDetail.serviceLife }} 年
        </el-descriptions-item>
        <el-descriptions-item label="资产预警提醒">
          {{ assetDetail.alert }}
          {{ assetDetail.alertType === 'month' ? '月' : '日' }}
        </el-descriptions-item>
        <el-descriptions-item label="资产预警日期">
          {{ assetDetail.alertDate }}
        </el-descriptions-item>
        <el-descriptions-item label="资产状态">
          <DictTag :value="assetDetail.status" :dicts="dictRef" />
        </el-descriptions-item>

        <el-descriptions-item label="资产附件" :span="4">
          <div v-if="assetDetail.attachments">
            <!-- 图片预览 -->
            <div class="mb-4">
              <div class="asset-images">
                <img
                  v-for="(attachment, index) in assetDetail.attachmentsUrl"
                  :key="index"
                  :src="attachment"
                  alt="资产图片"
                  class="asset-image"
                  @click="previewImage(attachment)"
                />
              </div>
            </div>
          </div>
          <div v-else class="text-gray-500">暂无附件</div>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 操作日志和维修记录 -->
    <div v-if="assetDetail" class="bg-white p-6 shadow">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="操作日志" name="1">
          <el-table
            :data="operationLogs"
            style="width: 100%"
            :loading="tableLoading"
            border
            class="gray-header-table"
          >
            <el-table-column
              type="index"
              label="序号"
              width="80"
              align="center"
            />
            <el-table-column prop="operator" label="操作人" align="center" />
            <el-table-column
              prop="operationTime"
              label="操作时间"
              align="center"
            />
            <el-table-column
              prop="description"
              label="资产描述"
              align="center"
            />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="维修记录" name="2">
          <el-table
            :data="maintenanceLogs"
            style="width: 100%"
            :loading="tableLoading"
            border
            class="gray-header-table"
          >
            <el-table-column
              type="index"
              label="序号"
              width="80"
              align="center"
            />
            <el-table-column prop="orderNo" label="工单编号" align="center" />
            <el-table-column prop="operator" label="维修人" align="center" />
            <el-table-column
              prop="operationTime"
              label="维修时间"
              align="center"
            />
            <el-table-column
              prop="description"
              label="维修记录"
              align="center"
            />
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div class="mt-4 flex items-center justify-between">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <div v-else-if="!loading" class="py-10 text-center">
      <el-empty description="未找到资产信息" />
    </div>

    <!-- 图片预览组件 -->
    <ElImageViewer
      v-if="previewVisible"
      :url-list="previewImages"
      @close="closePreview"
    />
  </Page>
</template>

<style scoped lang="scss">
:deep(.el-tag) {
  margin-left: 8px;
}
:deep(.el-descriptions__cell) {
  padding: 12px;
}
:deep(.el-descriptions__label) {
  font-weight: 500;
}
:deep(.gray-header-table .el-table__header-wrapper th) {
  background-color: #f5f7fa !important;
  color: #303133;
}

.asset-images {
  display: flex;
  gap: 12px;
  margin-top: 4px;

  .asset-image {
    width: 60px;
    height: 60px;
    cursor: pointer;
    object-fit: cover;
    border-radius: 4px;
    transition: transform 0.2s;
  }
}
</style>
