<template>
  <div class="app-container">
    <!-- 基本信息 -->
    <basic-info :form="form" />

    <!-- 维护记录 -->
    <maintenance-record
      :data="maintenanceData"
      :page="maintenancePage"
      @size-change="handleMaintenanceSizeChange"
      @current-change="handleMaintenanceCurrentChange"
    />

    <!-- 保险记录 -->
    <insurance-record
      :data="insuranceData"
      :page="insurancePage"
      :aircraft-id="String($route.query.id)"
      @size-change="handleInsuranceSizeChange"
      @current-change="handleInsuranceCurrentChange"
      @view="handleInsuranceView"
      @edit="handleInsuranceEdit"
      @delete="handleInsuranceDelete"
      @refresh="loadInsuranceRecords"
    />

    <!-- API模块入口 -->
    <api-links @click="handleApiClick" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getDeviceDetail, getMaintenanceRecords, getInsuranceRecords } from '@/api/aircraft'
import { get } from "@/api/system/dictDetail";
import BasicInfo from './components/BasicInfo'
import MaintenanceRecord from './components/MaintenanceRecord'
import InsuranceRecord from './components/InsuranceRecord'
import ApiLinks from './components/ApiLinks'
export default {
  name: 'aircraftDetail',
  components: {
    BasicInfo,
    MaintenanceRecord,
    InsuranceRecord,
    ApiLinks
  },
  data() {
    return {
      form: {
        name: '',
        model: '',
        useType: '',
        areaName: '',
        scenicName: '',
        username: '',
        remark: '',
        deviceImages: [
          'https://axure-file.lanhuapp.com/md5__f344f816278c2a3f5164e4571c580ad9.png'
        ]
      },
      typeOptions: [], // 飞行类型选项
      maintenanceData: [],
      insuranceData: [],
      maintenancePage: {
        current: 1,
        size: 10,
        total: 0
      },
      insurancePage: {
        current: 1,
        size: 10,
        total: 0
      }
    }
  },
  computed: {
    ...mapGetters([
      's3UploadApi',
      'baseApi'
    ])
  },
  created() {
    this.getFlightTypes()
    const id = this.$route.query.id
    const rowData = this.$route.query.data ? JSON.parse(this.$route.query.data) : null
    if (rowData) {
      setTimeout(() => {
        this.getDetail(id, rowData)
      }, 0)
    }else {
      setTimeout(() => {
        this.getDetail(id)
      }, 0)
    }
    this.loadMaintenanceRecords()
    this.loadInsuranceRecords()
  },
  methods: {
    // 获取飞行类型
    async getFlightTypes() {
      try {
        const res = await get('user_qualification');
        if (res && res.content) {
          this.typeOptions = res.content;
        }
      } catch (error) {
        console.error("获取飞行类型失败:", error);
        this.$message.error("获取飞行类型失败");
        this.typeOptions = [];
      }
    },

    getDetail(id, rowData = null) {
      getDeviceDetail(id).then(response => {
        this.form = response
        if (rowData) {
          this.form.areaName = rowData.areaName
          this.form.scenicName = rowData.scenicName
          this.form.username = rowData.username
        }
        const type = this.typeOptions.find(t => t.dictSort === this.form.useType);
        this.form.useType = type ? type.label : '未知';
        // 确保设备图片数据格式统一
        this.form.deviceImages = this.form.deviceImages.map((image, index) => {
          if (typeof image === 'string') {
            return {
              id: String(index),
              fileFullPath: image
            }
          }
          return {
            ...image,
            id: String(image.id || index)
          }
        });
      }).catch(error => {
        console.error('获取设备详情失败:', error)
        this.$message.error('获取设备详情失败')
      })
    },
    async loadInsuranceRecords() {
      try {
        const params = {
          aircraftId: this.$route.query.id,
          current: this.insurancePage.current,
          size: this.insurancePage.size
        }
        const response = await getInsuranceRecords(params)
        this.insuranceData = response.records
        this.insurancePage.total = Number(response.total)
      } catch (error) {
        console.error('Failed to load insurance records:', error)
        this.$message.error('获取保险记录失败')
      }
    },
    async loadMaintenanceRecords() {
      try {
        const params = {
          aircraftId: this.$route.query.id,
          current: this.maintenancePage.current,
          size: this.maintenancePage.size
        }
        const response = await getMaintenanceRecords(params)
        this.maintenanceData = response.records
        this.maintenancePage.total = Number(response.total)
      } catch (error) {
        console.error('Failed to load maintenance records:', error)
        this.$message.error('获取维护记录失败')
      }
    },
    handleMaintenanceSizeChange(val) {
      this.maintenancePage.size = val
      this.loadMaintenanceRecords()
    },
    handleMaintenanceCurrentChange(val) {
      this.maintenancePage.current = val
      this.loadMaintenanceRecords()
    },
    handleInsuranceSizeChange(val) {
      this.insurancePage.size = val
      this.loadInsuranceRecords()
    },
    handleInsuranceCurrentChange(val) {
      this.insurancePage.current = val
      this.loadInsuranceRecords()
    },
    handleInsuranceView(row) {
      console.log('查看保险详情:', row)
    },
    handleInsuranceEdit(row) {
      this.handleAdd()
      this.dialogTitle = '编辑保险'
      this.form = {
        name: row.name,
        insuranceType: row.insuranceType,
        deadlineTime: row.deadlineTime ? row.deadlineTime.split('T')[0] : '',
        files: row.insuranceAttachment ? row.insuranceAttachment.map(attachment => ({
          name: attachment.sourceFileName,
          url: attachment.fileFullPath
        })) : []
      }
    },
    handleInsuranceDelete(row) {
      console.log('删除保险记录:', row)
    },
    handleInsuranceSubmit(form) {
      console.log('保存保险记录:', {
        ...form,
        aircraftId: this.$route.query.id
      })
      this.$message.success('保存成功')
      this.loadInsuranceRecords()
    },
    handleApiClick(type) {
      console.log('跳转到API模块:', type)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0;
  margin-bottom: 33px;
}
</style>
