<template>
  <view class="equipment-detail">
    <!-- 顶部导航区 -->
	<Topnav :topLevel="topLevel" title="设备详情" defaultBackColor="#333333"
		defaultNavTextColor="#333333" showBack />
	<!-- <view :style="{height: CustomBar + 'px'}" /> -->
    <!-- 主要内容区域 -->
    <view class="detail-container">
      <!-- 设备图片展示区 -->
      <view class="equipment-images">
        <u-swiper
          v-if="equipmentImages.length > 0"
          mode="dot"
          :list="equipmentImages"
          :name="'image'"
          @change="(e) => (currentImageIndex = e.current)"
          :autoplay="true"
          height="750"
          :interval="3000"
          border-radius="12"
        >
          <view slot="indicator" class="indicator">
            <view
              class="indicator__dot"
              v-for="(item, index) in equipmentImages"
              :key="index"
              :class="[index === currentImageIndex && 'indicator__dot--active']"
            >
            </view>
          </view>
        </u-swiper>
      </view>

      <!-- 设备基本信息区 -->
      <view class="equipment-info">
        <view class="info-card">
          <text class="device-id">{{
            equipmentDetail.name || "未知设备"
          }}</text>
          <text class="device-model">{{
            equipmentDetail.model || "未知型号"
          }}</text>
        </view>
      </view>

      <!-- 维保记录区 -->
      <view class="maintenance-records">
        <view class="section-title">
          <text style="z-index: 1">维保记录</text>
          <view class="title-underline"></view>
        </view>

        <view class="record-list">
          <view
            class="record-item"
            v-for="(record, index) in maintenanceRecords || []"
            :key="index"
          >
            <view class="record-image">
              <image :src="ordFileUrl+defaultIcon" mode="aspectFill" class="thumbnail" />
            </view>
            <view class="record-info">
              <view class="info-top">
                <text class="record-type">{{ record.type }}</text>
                <text class="record-operator">{{ record.operator }}</text>
              </view>
              <view class="info-bottom">
                <text class="record-time">{{ record.time }}</text>
                <text class="record-desc">{{ record.description }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作区  -->
    <view class="bottom-action">
      <view class="add-action" @click="showAddRecordModal"> 新增记录 </view>
    </view>

    <!-- 新增记录弹窗 -->
    <u-popup
      v-model="showRecordPopup"
      mode="bottom"
      border-radius="40"
      @close="closeAddAction"
    >
      <view class="action-popup">
        <view class="action-top">
          <view class="action-close" />
          <view class="action-title">新增记录</view>
          <u-icon
            class="action-close"
            :name="ordFileUrl + closeIcon"
            size="32"
            @click="showRecordPopup = false"
          />
        </view>
        <view>
          <view class="action-lam" style="margin-top: 50rpx">
            <view class="lam-title">维保类型</view>
            <u-input
              class="lam-input"
              placeholder-style="font-size:32rpx;color:#B3B3B3;"
              custom-style="font-size:32rpx;"
              placeholder="请选择维保类型"
              type="select"
              v-model="recordForm.type"
              @click="handleClickType()"
              :clearable="false"
            />
          </view>
          <view label="备注" :border-bottom="false" required>
            <view class="lam-title">备注</view>
            <view class="textarea-container">
              <u-input
                v-model="recordForm.description"
                type="textarea"
                placeholder="请在此输入备注内容~"
                height="200"
                :maxlength="100"
              />
              <view class="word-count">
                {{ recordForm.description ? recordForm.description.length : 0 }}
                <view class="word-count-max">/100</view>
              </view>
            </view>
          </view>
        </view>
        <view class="save-action" @click="saveRecord"> 保存 </view>
      </view>
    </u-popup>

    <u-picker
      v-model="showTypePicker"
      mode="selector"
      :range="maintenanceTypes"
      range-key="label"
      confirm-color="#f7c04d"
      @confirm="handleTypeSelect"
      title="维保类型"
    />
  </view>
</template>

<script>
import Topnav from "components/topnav/index.vue";
import configService from "@/common/config.service.js";

export default {
  // #ifdef MP
  options: {
    styleIsolation: "shared",
  },
  // #endif
  components: { Topnav },
  data() {
    return {
      // #ifdef MP
      // 微信小程序自定义导航栏参数
      CustomBar: this.CustomBar || 0,
      // #endif
      deviceId: '',
      currentImageIndex: 0,
      // 页面是否滚动到顶
      topLevel: 0,
      // 滚动顶部
      scrollTop: 0,
      // 设备详情
      equipmentDetail: {},
      maintenanceRecords: [],
	  fileUrl: configService.fileUrl + 'aerocraft/equipment/', //静态资源基础路径
      // 订单页图标基础路径
      ordFileUrl: configService.fileUrl + "aerocraft/order/",
	  // 飞行任务默认图片
	  defaultIcon: 'default.png',
      // 设备图片列表
      equipmentImages: [{
        image: this.fileUrl + "drone.png",
        title: "默认图片"
      }],
      // 下拉三角
      triangle: "triangle.png",
      // 弹窗关闭图标
      closeIcon: "close.png",
      // 新增记录表单
      showRecordPopup: false,
      showTypePicker: false,
      maintenanceType: "",
      maintenanceTypes: [
        { label: "例行检查", value: 0 },
        { label: "电池损坏", value: 1 }, 
      ],
      recordForm: {
        type: "",
        description: "",
      },
    };
  },
  onLoad(e) {
    this.deviceId = e.id;
  },
  mounted() {
    // 获取路由参数中的设备ID
    this.loadDeviceDetail();
    this.loadMaintenanceRecords();
  },
  methods: {
    // 加载设备详情
    async loadDeviceDetail() {
      try {
        const detail = await this.$api.getDevicesDetail(this.deviceId);
        console.log("设备详情:", detail);
        if (detail) {
          this.equipmentDetail = detail;
          // 设置设备图片
          if (detail.deviceImages && detail.deviceImages.length > 0) {
            this.equipmentImages = detail.deviceImages.map((img) => ({
              image: img.fileFullPath,
              title: img.sourceFileName,
            }));
          } else {
            this.equipmentImages = [{
              image: this.fileUrl+"drone.png",
              title: "默认图片"
            }];
          }
        }
      } catch (err) {
        console.error("获取设备详情失败:", err);
        uni.showToast({
          title: "获取设备详情失败",
          icon: "none",
        });
      }
    },

    // 加载维保记录
    async loadMaintenanceRecords() {
      try {
        const res = await this.$api.getMaintenanceRecords({
          aircraftId: this.deviceId,
        });
        if (res && res.records && res.records.length > 0) {
          this.maintenanceRecords = res.records.map((record) => ({
            type: this.getMaintenanceTypeName(record.maintenanceType),
            operator: record.createBy || "未知",
            time: record.createTime || "未知时间",
            description: record.remark || "无",
            image: this.equipmentImages[0]?this.equipmentImages[0].image : (this.fileUrl+"drone.png"),
          }));
        } else {
          this.maintenanceRecords = [];
        }
      } catch (err) {
        console.error("获取维保记录失败:", err);
        uni.showToast({
          title: "获取维保记录失败",
          icon: "none",
        });
      }
    },

    // 获取维保类型名称
    getMaintenanceTypeName(type) {
      const typeMap = {
        0: "例行检查",
        1: "电池损坏",
      };
      return typeMap[type] || "未知类型";
    },

    onPageScroll(e) {
      const level = e.scrollTop / 60;
      if (level <= 1) this.topLevel = level;
      else this.topLevel = 1;
      this.scrollTop = e.scrollTop;
    },
    // 显示新增记录弹窗
    showAddRecordModal() {
      this.showRecordPopup = true;
      // 重置表单
      this.recordForm = {
        type: "",
        description: "",
      };
      this.maintenanceType = "";
    },
    // 关闭弹窗
    closeAddAction() {
      // this.clearForm();
      this.showRecordPopup = false;
    },
    // 打开新增任务弹窗
    addAction() {
      this.showRecordPopup = true;
    },
    // 设备选择
    handleClickType() {
      this.showTypePicker = true;
    },
    // 保存维保记录
    async saveRecord() {
      if (!this.recordForm.type || !this.recordForm.description) {
        uni.showToast({
          title: "请填写完整信息",
          icon: "none",
        });
        return;
      }

      // 获取类型值
      const selectedType = this.maintenanceTypes.find(
        (t) => t.label === this.recordForm.type
      );
      if (!selectedType) {
        uni.showToast({
          title: "请选择正确的维保类型",
          icon: "none",
        });
        return;
      }

      try {
        // 使用设备详情中的employeesId
        const employeesId = this.equipmentDetail.employeesId;
        if (!employeesId) {
          uni.showToast({
            title: "获取员工ID失败",
            icon: "none",
          });
          return;
        }

        await this.$api.addMaintenanceRecord({
          aircraftId: this.deviceId,
          employeesId: employeesId,
          maintenanceType: selectedType.value,
          remark: this.recordForm.description,
          createTime: new Date().toISOString(),
        }); 

        uni.showToast({
          title: "添加成功",
          icon: "success",
        });

        // 重新加载维保记录
        await this.loadMaintenanceRecords();

        // 关闭弹窗并重置表单
        this.showRecordPopup = false;
        this.recordForm = {
          type: "",
          description: "",
        };
        this.maintenanceType = "";
      } catch (err) {
        console.error("添加维保记录失败:", err);
        uni.showToast({
          title: "添加失败",
          icon: "none",
        });
      }
    },

    // 选择维保类型
    handleTypeSelect(e) {
      if (e && typeof e[0] === "number") {
        const selected = this.maintenanceTypes[e[0]];
        if (selected) {
          this.recordForm.type = selected.label;
          this.maintenanceType = selected.label;
        }
        console.log("选中的维保类型:", this.recordForm.type);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.equipment-detail {
  display: flex;
  flex-direction: column;
  // min-height: 100vh;
  background-color: #f5f5f5;

  .detail-container {
    flex: 1;
    min-height: 100vh;
  }

  // 设备图片展示区
  .equipment-images {
    width: 100%;
    overflow: hidden;
	// padding-top:144rpx;
	background-color: #ebebf0;
    // margin-bottom: 20rpx;
  }
  ::v-deep .u-indicator-item-dot {
    width: 20rpx;
    height: 20rpx;
    border-radius: 50%;
    opacity: 0.5;
    background-color: #999999 !important; /* 默认颜色 */
  }
  ::v-deep .u-indicator-item-dot-active {
    opacity: 1;
    background-color: #fee547 !important; /* 选中颜色 */
  }
  ::v-deep .u-swiper-indicator{
	  bottom: 100rpx !important;
  }
  .indicator {
    display: flex;
    flex-direction: row;
    justify-content: center;
    position: absolute;
    bottom: 20rpx;
    left: 0;
    right: 0;
    padding: 20rpx;

    &__dot {
      height: 12rpx;
      width: 12rpx;
      border-radius: 100rpx;
      background-color: rgba(255, 255, 255, 0.5);
      margin: 0 6rpx;
      transition: all 0.3s;

      &--active {
        background-color: #fee547;
        width: 24rpx;
      }
    }
  }

  // 设备基本信息区
  .equipment-info {
	  position: relative;
	  margin-top: -80rpx;
    padding: 0 24rpx 26rpx 24rpx;
    // margin: 20rpx 0 30rpx;

    .info-card {
      background-color: #ffffff;
      padding: 30rpx;
      border-radius: 16rpx;
      display: flex;
      flex-direction: column;
      // gap: 16rpx;
      // box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

      .device-id {
        font-family: Source Han Sans SC;
        font-weight: bold;
        font-size: 36rpx;
        color: #333333;
      }

      .device-model {
        font-family: Source Han Sans SC;
        font-weight: 400;
        font-size: 32rpx;
        color: #666666;
      }
    }
  }

  // 维保记录区
  .maintenance-records {
    background-color: #ffffff;
    border-radius: 16rpx;
    padding: 30rpx 20rpx calc(126rpx + env(safe-area-inset-bottom));
    margin: 24rpx;
    margin-top: 0;
	
    .section-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 30rpx;
      position: relative;
      display: flex;
      align-items: center;

      .title-underline {
        position: absolute;
        bottom: 0rpx;
        left: 38rpx;
        width: 68rpx;
        height: 10rpx;
        background-color: #fee547;
        border-radius: 3rpx;
      }
    }

    .record-list {
      display: flex;
      flex-direction: column;
      gap: 26rpx;

      .record-item:first-child {
        box-shadow: 0rpx -6rpx 10rpx 0rpx rgba(226, 226, 226, 0.3),
          0rpx 6rpx 8rpx 0rpx rgba(218, 218, 218, 0.3);
      }

      .record-item {
        display: flex;
        gap: 20rpx;
        padding: 30rpx 20rpx 37rpx 20rpx;
        border-radius: 8rpx;
        box-shadow: 0rpx 6rpx 10rpx 0rpx rgba(200, 199, 193, 0.3);
        .record-image {
          width: 123rpx;
          height: 123rpx;
          border-radius: 12rpx;
          border: 3rpx solid #fee547;
          .thumbnail {
            width: 100%;
            height: 100%;
          }
        }

        .record-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          gap: 8rpx;

          .info-top {
            display: flex;
            flex-direction: column;
            gap: 8rpx;

            .record-type {
              font-family: Source Han Sans SC;
              font-weight: bold;
              font-size: 32rpx;
              color: #333333;
            }

            .record-operator {
              font-family: Source Han Sans SC;
              font-weight: 400;
              font-size: 28rpx;
              color: #666666;
            }
          }

          .info-bottom {
            display: flex;
            flex-direction: column;
            gap: 8rpx;
            font-family: Source Han Sans SC;
            font-weight: 400;
            font-size: 28rpx;
            color: #666666;
          }
        }
      }
    }
  }

  // 底部操作区
  .bottom-action {
    z-index: 2;
    position: fixed;
    bottom: -2rpx;
    width: 100%;
    background-color: #ffffff;
    padding: 15rpx 24rpx calc(4rpx + env(safe-area-inset-bottom));
	margin-bottom: 10rpx;
    .add-action {
      background: #fee547;
      border-radius: 10rpx;
      font-family: Source Han Sans SC;
      font-weight: bold;
      font-size: 30rpx;
      color: #333333;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 22rpx 0;
      &:active {
        margin: 4rpx 0;
        font-size: 26rpx;
        opacity: 0.8;
      }
    }
  }

  .action-popup {
    padding: 30rpx 24rpx;
    .action-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .action-title {
        font-family: Source Han Sans SC;
        font-weight: bold;
        font-size: 36rpx;
        color: #333333;
      }
      .action-close {
        margin-top: -10rpx;
      }
    }
    .action-lam {
      border-bottom: 2rpx solid #d9d9d9;
      margin-bottom: 34rpx;
      display: flex;
      align-items: center;
      padding-bottom: 16rpx;
      .lam-title {
        font-family: Source Han Sans SC;
        font-weight: 400;
        font-size: 32rpx;
        color: #1a1a1a;
        margin-right: 50rpx;
      }
      .lam-input {
        flex: 1;
        &::v-deep .u-icon__icon {
          color: #333333 !important;
        }
      }
      .lam-input-right {
        font-family: Source Han Sans SC;
        font-weight: bold;
        font-size: 32rpx;
        color: #333333;
      }
    }
    .save-action {
      display: flex;
      justify-content: center;
      align-items: center;
      background: #fee547;
      border-radius: 10rpx;
      font-family: Source Han Sans SC;
      font-weight: bold;
      font-size: 30rpx;
      color: #333333;
      padding: 22rpx 0;
      margin-bottom: 44rpx;
      &:active {
        opacity: 0.8;
      }
    }
  }
  .textarea-container {
    position: relative;
    height: 420rpx;
    .u-input {
      height: 100%;
      font-size: 32rpx;
      color: #333333;
      padding: 20rpx 30rpx;
      border-radius: 12rpx;
      background-color: #f5f5f5;
    }
    .word-count {
      position: absolute;
      right: 20rpx;
      bottom: 103rpx;
      font-family: Arial;
      font-weight: 400;
      font-size: 32rpx;
      color: #b3b3b3;

      .word-count-max {
        color: #333333;
        display: inline-block;
      }
    }
  }

  // 新增记录弹窗
  .record-form {
    padding: 40rpx 30rpx;
    background-color: #ffffff;

    .form-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 40rpx;

      .form-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333333;
      }
    }

    :deep(.u-form-item) {
      margin-bottom: 30rpx;

      .u-form-item__body {
        padding: 26rpx 0;
      }

      &__label {
        font-size: 30rpx;
        color: #333333;
      }

      &__input {
        font-size: 30rpx;
      }
    }
  }
}
</style>
