<template>
  <view class="content">
    <view class="top">
      <u-cell-group>
        <u-cell-item
          :arrow="false"
          title="保洁人员"
          :value="dataInfo.userName"
          :title-style="{
            color: '#303133',
            fontSize: '32rpx',
          }"
          :value-style="{
            color: '#303133',
            fontSize: '32rpx',
          }"
        ></u-cell-item>
        <u-cell-item
          :arrow="false"
          title="上报时间"
          :value="reportingTime"
          :title-style="{
            color: '#303133',
            fontSize: '32rpx',
          }"
          :value-style="{
            color: '#303133',
            fontSize: '32rpx',
          }"
        ></u-cell-item>
      </u-cell-group>
    </view>

    <!-- <view class="title">保洁区域</view> -->

    <view class="bottom">
      <u-form
        :model="form"
        :rules="rules"
        ref="uForm"
        label-width="400rpx"
        :label-style="{ fontSize: '32rpx' }"
      >
        <!-- 区域选择（多选） -->
        <u-form-item :label="dataInfo.name" prop="areas">
          <!-- <u-input v-model="form.cleaner" placeholder="请输入故障" /> -->
          <view style="width: 100%; font-size: 32rpx; text-align: right"
            >NFC卡损坏</view
          >
        </u-form-item>

        <!-- 备注（文本域） -->
        <u-form-item label="备注" prop="note" label-position="top">
          <u-input
            v-model="form.note"
            placeholder="请对故障进行描述"
            autoHeight
            maxlength="200"
            count
            type="textarea"
          ></u-input>
        </u-form-item>

        <!-- 图片上传 -->
        <u-form-item label="图片" prop="images" label-position="top">
          <!-- <u-upload
            v-model="form.images"
            :max-count="3"
            :previewFullImage="true"
            :multiple="true"
            @afterRead="handleImageUpload"
            @delete="handleImageDelete"
          ></u-upload> -->
          <view v-if="!form.url" class="upload-box" @click="takePhoto">
            <image
              src="/static/images/icon-camera.png"
              mode="aspectFit"
              style="width: 49rpx; height: 43rpx"
            />
          </view>

          <view v-else class="upload-image">
            <image
              :src="form.url"
              mode="aspectFit"
              style="width: 100%; height: 100%"
            />
            <view class="delete-icon" @click="handleDelete">×</view>
          </view>
        </u-form-item>
      </u-form>
    </view>

    <!-- 提交按钮 -->
    <u-button
      shape="circle"
      type="primary"
      style="margin-top: 40rpx"
      @click="submitForm"
      >保存</u-button
    >
  </view>
</template>

<script>
import { ReportingNFCDanger, GetPlanInfoAre, UploadFiles } from "@/api/apiList";

import { dateFormat } from "@/utils/utils";

export default {
  data() {
    return {
      reportingTime: "", // 当时时间 2025-4-14 10:00
      form: {
        note: "", // 备注
        url: "", // 图片
        // url: "http://sl.vrgon.com:8005/uploads/20250418/13800451500/3e6bd20b50d34555b5737db851acd71e.png", // 图片
      },
      areaOptions: [
        { label: "东大门操场", value: "east_gate" },
        { label: "西区教学楼", value: "west_building" },
        { label: "中心花园", value: "central_garden" },
      ],
      rules: {
        cleaner: [
          {
            required: true,
            message: "请填写保洁人员",
            trigger: ["blur", "change"],
          },
        ],
        reportingTime: [
          {
            required: true,
            message: "请选择上报时间",
            trigger: ["change"],
          },
        ],
        areas: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个清洁区域",
            trigger: ["change"],
          },
        ],
        url: [
          {
            type: "array",
            min: 1,
            required: true,
            message: "请至少上传一张现场照片",
            trigger: ["change"],
          },
        ],
      },

      params: {},

      dataInfo: {},
    };
  },

  onLoad(options) {
    console.log("options", JSON.parse(decodeURIComponent(options.params)));
    this.params = JSON.parse(decodeURIComponent(options.params));
    window.uploadFn = this.uploadResFn;
  },

  created() {
    this.reportingTime = dateFormat(new Date(), "YYYY-MM-DD HH:mm");
    this.getAreaInfo();
  },

  methods: {
    // 图片上传处理  废弃
    handleImageUpload(event) {
      const files = event.file;
      // 这里添加实际的上传逻辑
      this.form.images.push(...files.map((file) => ({ url: file.url })));
    },

    // 图片删除处理  废弃
    handleImageDelete(index) {
      this.form.images.splice(index, 1);
    },

    // 拍照获取图片
    takePhoto() {
      let u = navigator.userAgent;
      let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android
      // let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios
      try {
        if (isAndroid && AndroidJs) {
          console.log("%c%s", "color:red", "安卓--调用方法");
          const reqRow = {
            name: "upload",
            data: "",
          };
          AndroidJs.func(JSON.stringify(reqRow)); // 给安卓传参
        } else {
          console.log("%c%s", "color:red", "苹果--调用方法");
          const reqRow = {
            name: "back-iphone",
            data: "",
          };
          window.webkit.messageHandlers.func.postMessage(
            JSON.stringify(reqRow)
          ); // 给ios 传参
        }
      } catch (e) {
        console.log(e, "e-----判断安卓苹果类型出错");
      }
      return;
      uni.chooseImage({
        count: 1, // 每次拍摄1张
        sourceType: ["camera"], // 仅限拍照
        sizeType: ["compressed"], // 压缩图片
        success: async (res) => {
          console.log("拍照成功", res);
          this.form.url = res.tempFilePaths[0];

          // this.uploadFiles(res.tempFilePaths[0]);
        },
        fail: (err) => {
          uni.showToast({ title: "拍照失败，请重试", icon: "none" });
        },
      });
    },
    // android回调
    uploadResFn(data) {
      if (!data) {
        return uni.showToast({ title: "未传入参数 uploadFn", icon: "none" });
      }
      // uni.showModal({
      //   title: "查看uploadFn",
      //   content: JSON.stringify(data) || "未传入参数 initFn",
      //   showCancel: true,
      //   success: function (res) {},
      // });

      this.form.url = data[0].path;
    },

    // 删除图片
    handleDelete() {
      this.form.url = "";
    },

    // 获取区域信息
    async getAreaInfo() {
      const res = await GetPlanInfoAre({
        id: this.params.id,
      });

      if (res.succeed) {
        this.dataInfo = res.data;
      }
    },

    // 表单提交
    async submitForm() {
      if (!this.form.url) {
        uni.showToast({ title: "请上传图片", icon: "none" });
        return;
      }

      // const res = await UploadFiles([this.form.url]);
      // if (!res.succeed) return;

      const params = {
        note: this.form.note,
        planInfoId: this.dataInfo.planInfoId,
        reportingTime: this.reportingTime.replace(" ", "T"),
        userId: this.dataInfo.userId,
        id: this.dataInfo.id,
        // url: res.data[0].path,
        url: this.form.url,
      };

      const res1 = await ReportingNFCDanger(params);

      if (res1.succeed) {
        const queryParams = encodeURIComponent(JSON.stringify(this.params));
        uni.showModal({
          title: "提示",
          content: "任务已完成，快去上传图片吧",
          confirmText: "去上传图片",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              uni.navigateTo({
                url: "/pages/index/uploadPhoto?params=" + queryParams,
              });
            }
          },
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
page {
  background-color: #f3f5fa !important;
}
.content {
  height: auto;
  // min-height: 100vh;
  padding: 24rpx 32rpx;
  background-color: #f3f5fa;

  .top {
    background: #ffffff;
    border-radius: 22rpx;
    padding: 0rpx 10rpx;
    margin-bottom: 30rpx;
  }

  .bottom {
    background: #ffffff;
    border-radius: 22rpx;
    padding: 0rpx 40rpx;
    margin-bottom: 30rpx;
    padding-bottom: 30rpx;

    .upload-box {
      border: 1px dashed #526fa3;
      width: 130rpx;
      height: 130rpx;
      background-color: #edf2ff;
      border-radius: 16rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .upload-image {
      width: 130rpx;
      height: 130rpx;
      border-radius: 16rpx;

      position: relative;
      .delete-icon {
        position: absolute;
        right: -10rpx;
        top: -10rpx;
        width: 36rpx;
        height: 36rpx;
        background: rgba(110, 110, 110, 0.6);
        border-radius: 50%;
        color: white;
        text-align: center;
        line-height: 36rpx;
        font-size: 28rpx;
      }
    }
  }

  .title {
    font-size: 38rpx;
    color: #1a1a1b;
    margin: 42rpx 0 32rpx 0;
    font-weight: bold;
  }

  // 调整复选框布局
  .u-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 30rpx;
  }
}
</style>
