<template>
  <a-modal
    :visible="visible"
    :bodyStyle="{'padding':'12px'}"
    title="一机一档"
    width="1500px"
    @cancel="handleCancel"
    :footer="null"
  >
    <a-row :gutter="16">
      <!-- 左侧树结构 -->
      <a-col :span="4">
        <a-card title="设备结构" :bordered="false">
          <a-tree
            :tree-data="treeData"
            :default-expand-all="true"
            @select="onTreeSelect"
          />
        </a-card>
      </a-col>

      <!-- 右侧详情区域 -->
      <a-col :span="20">
        <!-- 产品基本信息 -->
        <a-card title="产品基本信息" :bordered="false" class="section-card-1" :bodyStyle="{'padding':'12px'}">
          <a-button
            type="primary"
            icon="qrcode"
            style="float:right"
            @click="qrVisible = true"
          >
            二维码
          </a-button>
          <a-descriptions :column="4" size="small">
            <a-descriptions-item label="设备名称">{{ basicInfo.deviceName }}</a-descriptions-item>
            <a-descriptions-item label="设备编码">{{ basicInfo.deviceCode }}</a-descriptions-item>
            <a-descriptions-item label="产品型号">{{ basicInfo.typeId }}</a-descriptions-item>
            <a-descriptions-item label="生产厂商">{{ basicInfo.supplierId_dictText }}</a-descriptions-item>
            <a-descriptions-item label="启用时间">{{ basicInfo.enableTime }}</a-descriptions-item>
            <a-descriptions-item label="安装位置">{{ basicInfo.location_dictText }}</a-descriptions-item>
            <a-descriptions-item label="使用单位">成都27号线</a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 位置物料信息 -->
        <a-card title="位置物料信息" :bordered="false" class="section-card-1" :bodyStyle="{'padding':'12px'}">
          <a-descriptions :column="3" size="small">
            <a-descriptions-item label="物料编码">{{ materialInfo.code }}</a-descriptions-item>
            <a-descriptions-item label="位置编码">{{ materialInfo.locationCode }}</a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 数据图表 -->
        <a-card title="数据图表" :bordered="false" class="section-card-1" :bodyStyle="{'padding':'12px 12px 0 12px'}">
          <a-tabs size="small" v-model="activeTab" @change="onTabChange">
            <a-tab-pane key="fault" tab="故障信息">
              <FaultInfo v-if="activeTab === 'fault'" ref="faultRef"/>
            </a-tab-pane>
            <a-tab-pane key="assembly" tab="装配履历">
              <AssemblyInfo v-if="activeTab === 'assembly'" ref="assemblyRef"/>
            </a-tab-pane>
            <a-tab-pane key="process" tab="工艺文件">
              <ProcessDocs v-if="activeTab === 'process'" ref="processRef"/>
            </a-tab-pane>
            <a-tab-pane key="plan" tab="检修计划">
              <MaintenancePlan v-if="activeTab === 'plan'" ref="planRef"/>
            </a-tab-pane>
            <a-tab-pane key="replacement" tab="换件信息">
              <ReplacementInfo v-if="activeTab === 'replacement'" ref="replacementRef"/>
            </a-tab-pane>
            <a-tab-pane key="predict" tab="设备预测">
              <DevicePrediction v-if="activeTab === 'predict'" ref="predictRef"/>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>

    <DeviceQrModal
      :visible="qrVisible"
      @close="qrVisible = false"
      :info="basicInfo"
    />
  </a-modal>
</template>

<script>
import FaultInfo from './tabs/FaultInfo.vue'
import AssemblyInfo from './tabs/AssemblyInfo.vue'
import ProcessDocs from './tabs/ProcessDocs.vue'
import MaintenancePlan from './tabs/MaintenancePlan.vue'
import ReplacementInfo from './tabs/ReplacementInfo.vue'
import DevicePrediction from './tabs/DevicePrediction.vue'
import DeviceQrModal from '@/views/device/component/DeviceQrModal/DeviceQrModal.vue'
import { getAction } from '@api/manage'

export default {
  name: 'DeviceArchives',
  components: {
    FaultInfo,
    AssemblyInfo,
    ProcessDocs,
    MaintenancePlan,
    ReplacementInfo,
    DevicePrediction,
    DeviceQrModal
  },
  props: {
    deviceId: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
  },
  data() {
    return {
      activeTab: 'fault',
      basicInfo: {},
      materialInfo: {},
      treeData: [],
      urlList: {
        listAllPart: '/device/part/list',
        queryById: "/device/buDevice/queryById",
      },
      selectedNode: null,
      qrVisible: false
    }
  },
  watch: {
    visible(newVal, oldVal) {
      if(newVal) this.show()
    }
  },
  methods: {
    show() {
      this.loadTree()
      this.loadBasicInfo()
      this.loadMaterialInfo()
      // 等待 DOM 渲染完成再调用子组件方法
      this.$nextTick(() => {
        this.$refs.faultRef.fetchData(this.deviceId)
      })
    },
    handleCancel() {
      this.$emit('close');
    },
    onTabChange(key) {
      console.log('Switched to tab:', key)
      // 使用 ref 调用对应子组件的方法
      this.$nextTick(() => {
        switch (key) {
          case 'fault':
            this.$refs.faultRef.fetchData(this.deviceId)
            break
          case 'assembly':
            this.$refs.assemblyRef.fetchData()
            break
          case 'process':
            this.$refs.processRef.fetchData(this.basicInfo.deviceTypeId)
            break
          case 'plan':
            this.$refs.planRef.fetchData(this.deviceId)
            break
          case 'replacement':
            this.$refs.replacementRef.fetchData(this.deviceId)
            break
          case 'predict':
            this.$refs.predictRef.fetchData()
            break
        }
      })
    },
    onTreeSelect(selectedKeys, info) {
      const node = info.node
      this.selectedNode = node
      // TODO: 根据所选节点重新加载信息
      this.loadBasicInfo(node)
      this.loadMaterialInfo(node)
    },
    loadTree() {
      getAction(this.urlList.listAllPart, {
        device: this.deviceId,
        pageNo: 1,
        pageSize: 10000,
      }).then((res) => {
        if (res.success) {
          const newChildren = res.result.records.map((item) => {
            return {
              key: item.id,
              title: item.name + '(' + item.serialCode + ')',
              children: item.children.map((item1) => {
                return {
                  key: item1.id,
                  title: item1.name + '(' + item1.serialCode + ')',
                  level: 2,
                  isLeaf: this.maxLevel === 2,
                }
              }),
              level: 2,
              isLeaf: this.maxLevel === 2,
            }
          })
          if (newChildren.length > 0) {
            // 创建现有子节点的Map
            this.treeData = newChildren;
          }
        }
      })
    },
    loadBasicInfo() {
      // 加载基本信息
      getAction(this.urlList.queryById, {id:this.deviceId}).then((res) => {
          if(res.success) {
            this.basicInfo = res.result;
          }
      });
    },
    loadMaterialInfo() {
      // TODO: 加载物料信息
    }
  }
}
</script>

<style scoped>
.section-card {
  padding: 12px;
}
.section-card-1 {
  padding: 12px 12px 0 12px;
}
</style>
