<template>
  <!-- 机房巡检操作 -->
  <view>
    <view v-for="(item, index) in itemData.detail" :key="index">
      <view class="form-item">
        <text class="form-label"
          ><text class="required">*</text>{{ item.label }}</text
        >
        <view class="switch-container">
          <view
            :class="['status-btn', { active: item.inspectionResult === 0 }]"
            @click="setInspectionResult(index, 0, item.lableArr[0])"
          >
            {{ item.lableArr[0] }}
          </view>
          <view
            :class="['status-btn', { active: item.inspectionResult === 1 }]"
            @click="setInspectionResult(index, 1, item.lableArr[1])"
          >
            {{ item.lableArr[1] }}
          </view>
        </view>
      </view>
      <template v-if="item.inspectionResult === 1">
        <view class="form-item">
          <text class="form-label"
            ><text class="required">*</text>情况摘要</text
          >
          <text
            :class="['conclusion', { 'no-text': !item.conclusion }]"
            @click="showPopup(item, index)"
          >
            {{ item.conclusion || "请输入情况摘要" }}</text
          >
        </view>
        <view class="form-item">
          <text class="form-label"
            ><text class="required">*</text>现场照片</text
          >
          <CommonUpload v-model="item.photos" :max-count="5">
          </CommonUpload> </view
      ></template> </view
    ><custom-popup
      ref="customPopup"
      :inspectionItem="inspectionItem"
      @confirm="handlePopupConfirm"
    ></custom-popup>
  </view>
</template>

<script>
import CommonUpload from "@/components/CommonUpload/index.vue";
import customPopup from "./customPopup.vue";
import _ from "lodash";
import mixin from "./mixin";

export default {
  components: {
    CommonUpload,
    customPopup,
  },
  mixins: [mixin],
  props: {
    // 父组件传递的巡检状态
    status: {
      type: Number,
      default: 0,
    },
    // 父组件传递的巡检事项名
    inspectionItem: {
      type: String,
      default: "",
    },
    // 父组件传递的数据
    defaultData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      currentIndex: 0, // 当前操作的索引
      photos: [],
      itemData: {
        isValid: false, // false是校验未通过 true是校验通过
        status: 0, //0是未巡检 1是已巡检 2巡检异常
        statusLabel: "未巡检",
        inspectionItem: "", //巡检事项
        detail: [
          {
            label: "屏幕画质",
            inspectionResult: "",
            inspectionResultLable: "正常",
            lableArr: ["正常", "异常"],
            conclusion: "",
            photos: [],
          },
          {
            label: "配电箱外观",
            inspectionResult: "",
            inspectionResultLable: "正常",
            lableArr: ["正常", "异常"],
            conclusion: "",
            photos: [],
          },
        ],
      },
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.now_user || {};
    },
  },
  watch: {
    defaultData(newVal) {
      // 在这里处理数据变化
      if (Object.keys(this.defaultData).length !== 0) {
        this.itemData = this.defaultData;
      }
    },
  },
  async mounted() {
    console.log("sdsadasd", this.itemData);
    // if (Object.keys(this.defaultData).length !== 0) {
    //   this.itemData = this.defaultData;
    // }
  },
  methods: {
    // 拍照
    takePhoto(index) {
      uni.chooseImage({
        count: 1,
        sourceType: ["camera"], // 可以从相机拍摄
        success: async (res) => {
          if (this.photos.length < 5) {
            const base64 = await this.convertFileToBase64(res.tempFilePaths[0]);
            this.itemData.detail[index].photos.push(base64);
          } else {
            uni.showToast({
              title: "最多只能上传5张照片",
              icon: "none",
            });
          }
        },
      });
    },
    // 转化为base64
    convertFileToBase64(filePath) {
      return new Promise((resolve, reject) => {
        plus.io.resolveLocalFileSystemURL(
          filePath,
          function (entry) {
            entry.file(
              function (file) {
                const reader = new plus.io.FileReader();
                reader.onloadend = function (evt) {
                  const base64 = evt.target.result; // 获取 Base64 数据
                  resolve(base64); // 返回 Base64 数据
                };
                reader.readAsDataURL(file); // 读取文件并转换为 Base64
              },
              function (error) {
                reject("获取文件对象失败：" + error.message);
              },
            );
          },
          function (error) {
            reject("解析文件路径失败：" + error.message);
          },
        );
      });
    },
    // 删除照片
    deletePhoto(index, itemIndex) {
      this.itemData.detail[index].photos.splice(itemIndex, 1);
    },
    // 处理弹窗确认
    handlePopupConfirm(summary) {
      this.itemData.detail[this.currentIndex].conclusion = summary; // 回显到文字显示区域
    },
    // 处理】数据
    getFromData() {
      const isValid = this.areAllObjectsValid(this.itemData.detail); //false不通过 true通过
      console.log("wlhj", isValid);
      const isAllOne = this.areAllInspectionResultsOne(this.itemData.detail);
      console.log("isAllOne", isAllOne);
      this.itemData.isValid = isValid;
      this.itemData.inspectionItem = this.inspectionItem;
      this.itemData.status = isAllOne.status; //1表示已经巡检过没有异常
      this.itemData.statusLabel = isAllOne.statusLabel;
      console.log("查看数据", this.itemData);
      return this.itemData;
    },
    // 数据校验方法 true说明有未填项
    areAllObjectsValid(details) {
      // 检查是否有任何项的 inspectionResult 为空字符串
      const hasEmptyResult = details.some(
        (item) => item.inspectionResult === "",
      );
      if (hasEmptyResult) {
        return false;
      }

      // 遍历每一项进行检查
      for (const item of details) {
        if (item.inspectionResult === 0) {
          // 如果 inspectionResult 为 0，跳过此项的其他检查
          continue;
        } else if (item.inspectionResult === 1) {
          // 如果 inspectionResult 为 1，检查 conclusion 和 photos
          if (!item.conclusion || item.photos.length === 0) {
            return false;
          }
        } else {
          // 其他情况（理论上不应该存在，根据当前规则）
          return false;
        }
      }
      // 所有检查都通过
      return true;
    },
    areAllInspectionResultsOne(details) {
      let hasEmpty = false;
      let allZero = true;
      let hasOne = false;

      for (const item of details) {
        if (item.inspectionResult === "") {
          hasEmpty = true;
          break;
        } else if (item.inspectionResult === 1) {
          hasOne = true;
          allZero = false;
        } else if (item.inspectionResult === 0) {
          // 继续检查
        } else {
          // 如果有其他值，可以在这里处理
          allZero = false;
        }
      }

      if (hasEmpty) {
        return { statusLabel: "未巡检", status: 0 };
      } else if (allZero) {
        return { statusLabel: "已巡检", status: 1 };
      } else if (hasOne) {
        return { statusLabel: "巡检异常", status: 2 };
      } else {
        // 默认情况，可以根据需求调整
        return { statusLabel: "未巡检", status: 0 };
      }
    },
    setNormal() {
      this.itemData.detail.forEach((item) => {
        item.inspectionResult = 0;
      });
    },
  },
};
</script>
<style scoped lang="less">
.form-item {
  display: flex;
  align-items: center;
  padding: 9.6px 0;
  line-height: 28.8px;
  border-bottom: 0.8px solid #f2f3f5;

  .form-label {
    font-size: 11.2px;
    margin-right: 25.6px;
    width: 88px;
    text-align: right;
    color: #7c7c7c;

    .required {
      color: red;
      margin-right: 3.2px;
    }
  }
  .conclusion {
    &.no-text {
      color: #c7c7c7;
    }
    .have {
      color: #000;
    }
  }
  .label {
    font-size: 11.2px;
  }

  .switch-container {
    display: flex;
    gap: 9.6px;

    .status-btn {
      flex: 1;
      padding: 5.6px 19.2px;
      font-size: 12.8px;
      color: #000000;
      background: #f2f2f2;
      text-align: center;
      font-weight: 400;
      line-height: 17.6px;
      border-radius: 14.4px;

      &.active {
        color: #ffffff;
        background: #3774f6;
        border: 0.32px solid rgba(224, 224, 224, 1);
      }
    }
  }

  .input-box {
    flex: 1;
    border-radius: 3.2px;
    font-size: 12.8px;
    line-height: 19.2px;
  }

  .photo-limit {
    font-size: 12.8px;
    color: #959595;
    line-height: 19.2px;
    font-weight: 400;
  }

  .photo-container {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 6.4px;

    .photo-item {
      position: relative;
      margin-right: 6.4px;
      margin-bottom: 6.4px;

      .photo {
        width: 57.6px;
        height: 57.6px;
        border-radius: 3.2px;
        margin-left: 9.6px;
      }

      .delete-photo {
        position: absolute;
        top: -6.4px;
        right: -6.4px;
        background-color: #ff4d4f;
        color: #fff;
        width: 12.8px;
        height: 12.8px;
        border-radius: 50%;
        text-align: center;
        line-height: 12.8px;
        font-size: 9.6px;
      }
    }
  }

  .photo-btn {
    background: #ffffff;
    border: 0.272px solid rgba(221, 221, 221, 1);
    border-radius: 1.64px;
    width: 57.6px;
    height: 57.6px;
    font-size: 57.6px;
    color: #cccccc;
    text-align: center;
    line-height: 51.2px;
  }
}
</style>
