<template>
  <view class="check-info">
    <view class="register" v-if="isProvince">
      <text>欢迎您登陆核验系统</text>
      <text @click="handleRegister">注册账号</text>
    </view>
    <view class="clock-container">
      <!-- 打卡圆形按钮 -->
      <view class="clock-circle" @click="handleClockIn">
        <text>{{ clockInInfo.dkdd ? "已打卡" : "打卡" }}</text>
      </view>

      <!-- 打卡信息 -->
      <view class="info-section">
        <view class="info-item">
          <text class="label">打卡时间：</text>
          <text class="value">{{ clockInInfo.dksj || "未打卡" }}</text>
        </view>
        <view class="info-item">
          <text class="label">打卡地点：</text>
          <text class="value">{{ clockInInfo.dkdd || "未打卡" }}</text>
        </view>
      </view>

      <!-- 拍照按钮 -->
      <button class="photo-btn" @click="takePhoto">拍照</button>
    </view>
    <!-- 图片预览区域 -->
    <view class="preview-section">
      <view class="preview-list" v-if="previewList.length > 0">
        <view
          v-for="(item, index) in previewList"
          :key="index"
          class="preview-item"
        >
          <image
            v-if="item.url"
            :src="item.url"
            mode="aspectFill"
            class="preview-image"
            @click="previewImage(index)"
          />
          <text v-else class="preview-text">预览</text>
          <text class="delete-icon" @click="deleteImage(index)">×</text>
        </view></view
      >

      <text v-else>暂无图片信息</text>
    </view>
  </view>
</template>

<script>
import { getClockInInfoApi, saveClockInInfo, getImageInfo } from "@/api/task";
export default {
  name: "CheckInfo",
  props: {
    taskInfo: {
      type: Object, // 根据实际数据类型调整
      default: () => ({}), // 默认值
    },
  },
  data() {
    return {
      previewList: [],
      clockInInfo: {
        dksj: "",
        dkdd: "",
        // latitude: "",
        // longitude: "",
      },
    };
  },

  // uni-app中的vue的生命周期执行顺序：
  // onLoad
  // created
  // onShow
  // beforeMount
  // onReady
  // mounted
  // beforeUpdate
  // updated
  // 返回上一页时，会执行onUnLoad，并未有执行destroyed，并未执行onHide
  // 进入下一页时，会执行onHide
  // 获取本地打卡记录
  // created() {
  //   this.getLocalClockInInfo();
  // },
  mounted() {
    // 判断是否是省级角色
    const userInfo = uni.getStorageSync("userInfo");
    if (userInfo.roles.includes("provincial_verification_personnel")) {
      this.isProvince = true;
    }

    this.getClockInInfo();
  },
  methods: {
    // 传递taskInfo并跳转
    handleRegister() {
      uni.navigateTo({
        url:
          "/pages/register/register?taskInfo=" + JSON.stringify(this.taskInfo),
      });
    },
    // handleRegister() {
    //   uni.navigateTo({
    //     url: "/pages/register/register",
    //   });
    // },

    getClockInInfo() {
      // const userInfo = uni.getStorageSync("userInfo");

      // 加载
      // uni.showLoading({
      //   title: "加载中...",
      // });

      getClockInInfoApi({
        kqId: this.taskInfo.kqId,
        // userId: userInfo.user.id,
      })
        .then((res) => {
          // console.log("初始化获取打卡信息：", res);
          // if (res.data.userId) {

          if (res.code === 0 && res.data !== null) {
            this.clockInInfo = res.data;
            // 添加这行，向父组件发送打卡信息
            this.$emit("update-clock-info", this.clockInInfo);
            if (
              this.clockInInfo.dkdd &&
              this.clockInInfo.pzxx &&
              this.clockInInfo.pzxx.length
            ) {
              getImageInfo({
                ids: res.data.pzxx,
              }).then((res) => {
                this.previewList = res.data.map((item) => {
                  return {
                    url: item.url,
                    id: item.id,
                  };
                });
              });
            }
            // getImageInfo({
            //   fileIds: this.clockInInfo.pzxx,
            // }).then((res) => {
            //   console.log(res, "图片信息");
            // });
          } else {
            this.clockInInfo = {
              dksj: "",
              dkdd: "",
            };
            // 当没有打卡信息时也要通知父组件
            this.$emit("update-clock-info", this.clockInInfo);
          }

          // }
        })
        .finally(() => {
          // uni.hideLoading();
        });
    },
    // 获取本地的打卡信息
    getLocalClockInInfo() {
      const today = this.getToday();
      const storageKey = `clockIn_${today}`;

      try {
        const clockInData = uni.getStorageSync(storageKey);
        if (clockInData) {
          this.clockInInfo = JSON.parse(clockInData);
        }
      } catch (e) {
        console.error("获取本地打卡记录失败：", e);
      }
    },
    // 获取今日日期
    getToday() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    async handleClockIn() {
      // const ClockData = await getClockInInfo({
      //   kqId: this.taskInfo.kqId,
      // });

      // 获取位置信息
      uni.getLocation({
        type: "gcj02",
        success: (res) => {
          this.clockInInfo.latitude = res.latitude;
          this.clockInInfo.longitude = res.longitude;

          // 获取详细地址
          this.getAddress(res.latitude, res.longitude);
        },
        fail: (err) => {
          uni.showToast({
            title: "获取位置信息失败，请检查定位权限",
            icon: "none",
          });
          console.error("获取位置失败：", err);
        },
      });
    },

    // 根据经纬度获取详细地址
    getAddress(latitude, longitude) {
      uni.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=SOEBZ-J2BHS-7YSOI-64K33-6RO65-G2FEJ`, // 需要替换为您的腾讯地图 key
        success: (res) => {
          if (res.data.status === 0) {
            this.clockInInfo.dkdd = res.data.result.address;
            // 记录打卡时间
            this.recordClockIn();
          } else {
            uni.showToast({
              title: "获取地址信息失败",
              icon: "none",
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: "获取地址信息失败",
            icon: "none",
          });
        },
      });
    },

    recordClockIn() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");

      this.clockInInfo.dksj = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      this.$emit("update-clock-info", this.clockInInfo);

      // 保存打卡记录到本地存储
      // const today = this.getToday();
      // const storageKey = `clockIn_${today}`;

      // try {
      //   uni.setStorageSync(storageKey, JSON.stringify(this.clockInInfo));
      // } catch (e) {
      //   console.error("保存本地打卡记录失败：", e);
      // }

      // 这里可以调用接口保存打卡记录
      this.saveClockInRecord();
    },

    // 保存打卡记录到服务器
    saveClockInRecord() {
      // 加载
      let clockInData;
      uni.showLoading({
        title: "打卡中...",
      });
      // clockInData = {
      //   // id: this.clockInInfo.id,
      //   kqId: this.taskInfo.kqId,
      //   dkdd: this.clockInInfo.dkdd,
      //   dksj: this.clockInInfo.dksj,
      //   // latitude: this.clockInInfo.latitude,
      //   // longitude: this.clockInInfo.longitude,
      // };
      // 示例：调用保存打卡记录的接口
    

      // 曾经打过卡
      if (this.clockInInfo.id) {
        clockInData = {
          id: this.clockInInfo.id,
          kqId: this.taskInfo.kqId,
          dkdd: this.clockInInfo.dkdd,
          dksj: this.clockInInfo.dksj,
          // latitude: this.clockInInfo.latitude,
          // longitude: this.clockInInfo.longitude,
        };
      } else {
        clockInData = {
          // userId: uni.getStorageSync("userInfo").user.id,
          // id: this.clockInInfo.id,
          kqId: this.taskInfo.kqId,
          dkdd: this.clockInInfo.dkdd,
          dksj: this.clockInInfo.dksj,
          // latitude: this.clockInInfo.latitude,
          // longitude: this.clockInInfo.longitude,
        };
      }

      saveClockInInfo(clockInData)
        .then((res) => {
          if (res.code === 0) {
            uni.showToast({
              title: "打卡成功",
              icon: "success",
            });

            this.getClockInInfo();
          } else {
            uni.showToast({
              title: "打卡失败",
              icon: "none",
            });
          }
        })
        .finally(() => {
          // uni.hideLoading();
        });
    },

    takePhoto() {
      if (!this.clockInInfo.dkdd) {
        uni.showToast({
          title: "请先打卡",
          icon: "none",
        });
        return;
      }

      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["camera", "album"],
        success: (res) => {
          // 获取图片 转化为二进制
          // uni.getFileSystemManager().readFile({
          //   filePath: res.tempFilePaths[0],
          //   encoding: "base64",
          //   // encoding: "binary",
          //   success: (base64Res) => {
          //     this.previewList.push({
          //       url: res.tempFilePaths[0],
          //       base64: base64Res.data,
          //     });

          //     this.uploadImage(base64Res.data);
          //   },
          //   fail: (err) => {
          //     console.error("图片转base64失败：", err);
          //     uni.showToast({
          //       title: "图片处理失败",
          //       icon: "none",
          //     });
          //   },
          // });
          this.uploadImage(res.tempFilePaths[0]);
        },
        fail: (err) => {
          console.error("选择图片失败：", err);
          uni.showToast({
            title: "选择图片失败",
            icon: "none",
          });
        },
      });
    },

    uploadImage(base64Data) {
      uni.uploadFile({
        url: "http://121.36.17.6:8002/admin-api/infra/file/uploadForFile",
        method: "POST",
        header: {
          authorization: "Bearer " + uni.getStorageSync("token"),
        },
        filePath: base64Data,
        name: "file",
        success: (resp) => {
          let res = JSON.parse(resp.data);

          if (res.code === 0) {
            uni.showToast({
              title: "图片上传成功",
              icon: "success",
            });

            this.previewList.push({
              url: res.data.url,
              id: res.data.id,
            });

            // getClockInInfo;

            let pzxx = this.previewList.map((item) => {
              return item.id;
            });

            if (this.clockInInfo.dkdd) {
              saveClockInInfo({
                id: this.clockInInfo.id,
                kqId: this.clockInInfo.kqId,
                pzxx,
              });
            } else {
              // 弹出
              uni.showToast({
                title: "请先打卡",
                icon: "none",
              });
            }
          } else {
            uni.showToast({
              title: "图片上传失败",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: "图片上传失败",
            icon: "none",
          });
        },
      });
    },

    deleteImage(index) {
      this.previewList.splice(index, 1);

      saveClockInInfo({
        id: this.clockInInfo.id,
        kqId: this.clockInInfo.kqId,
        pzxx: this.previewList.map((item) => {
          return item.id;
        }),
      }).then((res) => {
        if (res.code === 0) {
          uni.showToast({
            title: "删除图片成功",
          });
        } else {
          uni.showToast({
            title: "删除图片失败",
          });
        }
      });
    },

    // 添加图片预览方法
    previewImage(index) {
      const urls = this.previewList
        .map((item) => item.url)
        .filter((url) => url); // 获取所有图片url
      uni.previewImage({
        current: index, // 当前显示图片的索引
        urls: urls, // 需要预览的图片url列表
        indicator: "number",
        loop: true,
        success: () => {
          console.log("图片预览成功");
        },
        fail: (err) => {
          console.error("图片预览失败：", err);
          uni.showToast({
            title: "图片预览失败",
            icon: "none",
          });
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.check-info {
  height: 100%;
  padding: 20rpx;
  padding-bottom: 120rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: auto;
  .register {
    width: 100%;
    height: 70rpx;
    font-size: 28rpx;
    color: #333;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    border-radius: 10rpx;
    margin-bottom: 10rpx;
    padding: 0 20rpx;
    box-sizing: border-box;
  }
}

.clock-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #fff;
  border-radius: 10rpx;
}

.clock-circle {
  width: 300rpx;
  height: 300rpx;
  border-radius: 50%;
  background-color: #2979ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40rpx 0;
  cursor: pointer;
  box-shadow: 5px 0px 15px rgba(0, 0, 0, 0.4); /* 添加阴影 */

  text {
    color: #fff;
    font-size: 48rpx;
  }

  // &:active {
  //   opacity: 0.8;
  // }
}

.info-section {
  width: 100%;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  .info-item {
    margin-bottom: 20rpx;
    font-size: 28rpx;
    color: #333;

    .label {
      color: #666;
    }
  }
}

.photo-btn {
  width: 240rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #2979ff;
  color: #fff;
  border-radius: 10rpx;
  font-size: 28rpx;
  margin: 30rpx 0;
}

.preview-section {
  height: 540rpx;
  margin-top: 30rpx;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;

  .preview-list {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    overflow: auto;
  }
  .preview-item {
    margin: 20rpx;
    width: 310rpx;
    height: 270rpx;
    border: 2rpx solid #eee;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    .preview-image {
      width: 100%;
      height: 100%;
      cursor: pointer; // 添加手型光标提示可点击
    }

    .preview-text {
      color: #999;
      font-size: 28rpx;
    }

    .delete-icon {
      position: absolute;
      top: -20rpx;
      right: -20rpx;
      width: 40rpx;
      height: 40rpx;
      line-height: 34rpx;
      text-align: center;
      background-color: rgba(0, 0, 0, 0.3);
      color: #fff;
      border-radius: 50%;
      font-size: 32rpx;
    }
  }
}
</style>
