// pages/Workorderdetails/index.js
const api = require('../../api/index.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    first: 1,
    second: 1,
    third: 1,
    visible: false,
    workorder: [],
    optionsid: '',
    workorderId: '',
    partnerAvite: [],
    bindreviewtype: '',
    latitude: null,
    longitude: null,
    locationName: '获取中...',
    checkinStatus: 'waiting', // waiting, success, fail
    checkinRecords: [],
    distance: null, // 距离目标点的距离
    canCheckin: false,
    showPermissionGuide: null,
    workorderContent: '',
    switchtype: false,
    codeswitchtype:false,
    partnerPosition: wx.getStorageSync('partnerPosition'),
    scanCode:{},
    result:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    console.log(options);
    this.setData({
      optionsid: options.id,
      workorderId: options.workorderId
    })
    this.onworkorder()

  },
  // 获取当前位置
  getCurrentLocation() {
    const that = this;
    // 先检查位置权限
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          // 如果没有授权，请求授权
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
              that._getLocation();
            },
            fail: () => {
              wx.showModal({
                title: '位置权限提示',
                content: '需要位置权限才能使用此功能，是否去设置开启？',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting();
                  }
                }
              });
            }
          });
        } else {
          // 已经授权，直接获取位置
          that._getLocation();
        }
      }
    });
  },
  // 提取获取位置的具体逻辑
  _getLocation() {
    const that = this;
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        console.log('位置获取成功:', res);
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        // that.reverseGeocode(res.latitude, res.longitude);
        that.checkDistance();
      },
      fail: (err) => {
        console.error('获取位置失败:', err);
        wx.showToast({
          title: '获取位置失败，请重试',
          icon: 'none'
        });
      }
    })
  },
  checkDistance() {
    // this.data.workorder.devicesLatitudelongitude.split(",")

    let position = this.data.workorder.devicesLatitudelongitude;
    console.log(position);
    const targetLng = position[0]; // 目标经度
    const targetLat = position[1]; // 目标纬度
    const allowedDistance = 100; // 允许打卡距离（米）
    // longitude: 116.66504838681816      2号楼位置
    // latitude: 40.088160079721874    2号楼位置
    // longitude: 116.66504838932426   工位位置
    // latitude: 40.08816007901852   工位位置

    const distance = this.calculateDistance(
      this.data.latitude,
      this.data.longitude,
      targetLat,
      targetLng
    );

    this.setData({
      distance: distance.toFixed(2),
      canCheckin: distance <= allowedDistance
    });
    console.log(this.data.distance);
    console.log(this.data.canCheckin);
  },
  // 计算两点间距离（Haversine公式）
  calculateDistance(lat1, lng1, lat2, lng2) {
    const R = 6371000; // 地球半径（米）
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLng = (lng2 - lng1) * Math.PI / 180;
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
      Math.sin(dLng / 2) * Math.sin(dLng / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return R * c;
  },
  onposition() {
    this.checkLocationPermission();

  },
  onworkorder() {
    let _this = this
    let data = {
      workorderId: this.data.workorderId,
      id: this.data.optionsid
    }
    api.request(`/workoder/selectsysworkoderid`, 'POST', data)
      .then((res) => {
        console.log(res);
        if (res.code == 200) {
          if (res.data.workorderImg) {
            res.data.workorderImg = res.data.workorderImg.split(",")
          }
          // console.log(res.data.workoderstationimg==undefined);
          if (res.data.workoderstationimg) {
            res.data.workoderstationimg = res.data.workoderstationimg.split(",")
          }
          if (res.data.workoderendimg) {
            res.data.workoderendimg = res.data.workoderendimg.split(",")
          }
          if (res.data.workoderPartnerId) {
            res.data.workoderPartnerId=res.data.workoderPartnerId.split(",")
            
          }
          console.log(res.data.workoderPartnerId);
          if (res.data.devicesLatitudelongitude) {
            res.data.devicesLatitudelongitude.split(",")
          } else {
            res.data.devicesLatitudelongitude = ['116.66504838681816', '40.088160079721874']
          }
          this.setData({
            workorder: res.data
          })
          if (res.data.workorderType == 1) {
            console.log('定位开始');
            // _this.goToSetting();
            // this.checkLocationPermission();
            this.getCurrentLocation();

          }

        }

        // .split(" ")
      })
      .catch((err) => {
        console.error('请求失败：', err);
        // 在这里处理请求失败的情况
      });
  },
  onFirstChange(e) {
    this.setData({ first: e.detail.current });
  },
  onSecondChange(e) {
    this.setData({ second: e.detail.current });
  },
  onThirdChange(e) {
    this.setData({ third: e.detail.current });
  },
  onstep() {
    this.setData({
      visible: true,
      switchtype:true
        })
    console.log(this.data.workorder);
    if (this.data.workorder.workorderType==2) {
      for (let index = 0; index < this.data.workorder.sysRegions.length; index++) {
        if (this.data.workorder.sysRegions[index].type==0) {
          this.setData({
            codeswitchtype:false
          })
      return
        }else{
          this.setData({
            codeswitchtype:true
          }) 
        }
        
      }
    }
  
    // wx.navigateTo({
    //   url: '/pages/workorderstep/index',
    // })
  },
  oncode(){
    wx.showToast({
      title: '请先完成设备扫码',
      icon: 'none',
    });
  },
  // 删除图片
  bindCancel(e) {
    console.log(e.currentTarget.dataset.index);
    let index = e.currentTarget.dataset.index
    // 使用 filter 方法创建新数组（推荐）
    const newPartnerAvite = this.data.partnerAvite.filter((item, i) => i !== index);

    this.setData({
      partnerAvite: newPartnerAvite
    });
  },
  onVisibleChange() {
    this.setData({
      visible: false
    })
  },
  ontextarea(e) {
    this.setData({
      workorderContent: e.detail.value
    })
  },
  submit() {

    if (!this.data.switchtype) {
      return
    }
    this.setData({
      switchtype: false
    })
    let data = {
      id: this.data.workorder.id,
      workoderImg: this.data.partnerAvite.length > 0 ? this.data.partnerAvite.toString() : '',
      workoderDetails: this.data.workorderContent,
      devicesRange: this.data.canCheckin ? '到达设备范围' : '不在设备范围'
    }
    api.request(`/workoder/addwork`, 'POST', data)
      .then((res) => {
        console.log(res);
        if (res.code == 200) {

          wx.showToast({
            title: '提交成功',
            icon: 'success',
          });
          this.setData({
            visible: false,
            partnerAvite: [],
            switchtype: true,
            workorderContent: ''
          })
          if (this.data.workorder.workorderType == 2) {
            wx.reLaunch({
              url: '/pages/index/index',
            })
          }
          this.onworkorder()
        }

      })
      .catch((err) => {
        console.error('请求失败：', err);
        this.setData({
          switchtype: true
        })
        // 在这里处理请求失败的情况
      });
  },
  // 审核
  bindreview(e) {
    this.setData({
      bindreviewtype: e.currentTarget.dataset.type
    })
    if (e.currentTarget.dataset.type == '不通过') {
      this.setData({
        visible: true,
      })
      return
    }
    let data = {
      id: this.data.workorder.id,
      examineType: e.currentTarget.dataset.type,
      workoderReason: this.data.workorderContent
    }
    api.request(`/workoder/examine`, 'POST', data)
      .then((res) => {
        console.log(res);
        if (res.code == 200) {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
          });
          this.setData({
            visible: false
          })
          wx.reLaunch({
            url: '/pages/index/index',
          })
          // this.onworkorder()
        }

      })
      .catch((err) => {
        console.error('请求失败：', err);
        // 在这里处理请求失败的情况
      });
  },
  // 预览图片
  previewImage(e) {
    console.log(e);
    const src = e.currentTarget.dataset.src;
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: [src]   // 需要预览的图片http链接列表
    });
  },
  // 上传头像
  bindtoImage() {
    let _this = this
    // 先检查隐私授权状态
    wx.getPrivacySetting({
      success: (res) => {
        if (res.needAuthorization) {
          // 弹出隐私协议弹窗
          wx.requirePrivacyAuthorize({
            success: () => {
              console.log('用户已同意隐私协议');
              _this.choosetoImage(); // 继续执行上传
            },
            fail: () => {
              console.log('用户拒绝了隐私协议');
              wx.showToast({
                title: '需同意隐私协议才能使用',
                icon: 'none'
              });
            }
          });
        } else {
          _this.choosetoImage(); // 已授权，直接上传
        }
      }
    });
  },
  // 上传头像图片
  choosetoImage() {
    let _this = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res);
        const tempFiles = res.tempFiles;
        _this.setData({
          imageList: tempFiles.map(file => file.tempFilePath),
        });
        _this.uploadtoImages(tempFiles);
      },
      fail(err) {
        console.error("选择失败:", err);
      }
    })
  },
  // 上传到服务器
  uploadtoImages(files) {
    let _this = this
    const token = wx.getStorageSync('token');
    files.forEach((file) => {
      wx.uploadFile({
        url: 'https://esos-iot.com:8443/config/upload/webPost',
        filePath: file.tempFilePath,
        name: 'file',
        formData: {
          file: file.tempFilePath
        },
        header: {
          'Authorization': 'Bearer ' + token // Also add to header if needed
        },
        success: (res) => {
          console.log(res);
          const obj = JSON.parse(res.data);
          this.data.partnerAvite.push(obj.data.partnerAvite)
          this.setData({
            partnerAvite: this.data.partnerAvite
          })
        },
        fail: (err) => {
          console.error('上传失败', err);
        },
      });
    });
  },
  scancode(e) {
    let _this =this
    console.log(e.currentTarget.dataset.deviceid);
    wx.scanCode({
      onlyFromCamera:true,
      success: (res) => {
        console.log(res);
       let rawData = e.currentTarget.dataset.deviceid.devicesQrcode.split(",")
        console.log(rawData);
        for (let index = 0; index < rawData.length; index++) {
            if (rawData[index] ==res.rawData) {
              wx.showToast({
                title: '扫码完成',
                icon: 'none'
              });
              _this.onupdatesysdeviceworkorder(e.currentTarget.dataset.deviceid)
            
              return
            }
        }
        wx.showToast({
          title: '没有匹配到正确的设备码',
          icon: 'none'
        });
     
        console.log(this.data.scanCode);
      },
      fail: (err) => {
        console.log(err);
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        });
      }
    })
  },
  onupdatesysdeviceworkorder(e) {
    let _this = this
    let data = {
      workorderId: this.data.workorderId,
      deviceId: e.deviceId,
      type:1
    }
    api.request(`/device/updatesysdeviceworkorder`, 'POST', data)
      .then((res) => {
        if (res.code == 200) {
    this.onworkorder()
        }
      })
      .catch((err) => {
        console.error('请求失败：', err);
        // 在这里处理请求失败的情况
      });
  },
  onqrcode(e){
    console.log(e.target.dataset.name);
    // console.log(this.data.scanCode.result);
  // 优化后的复制代码，增加错误处理
wx.setClipboardData({
  data: e.target.dataset.name,
  success (res) {
    console.log('设置剪贴板成功', res)
    wx.showToast({
      title: '复制成功',
      icon: 'none'
    });
 
  },
  fail (err) {
    console.error('设置剪贴板失败:', err)
    wx.showToast({
      title: '复制失败，请重试',
      icon: 'none'
    });
  }
})
 
 
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})