const Service = require('../../utils/service.js');
const Util = require('../../utils/util.js');
const Tim = require('../../utils/tim.js');
const App = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showview: false,
    scrollTop: 0,
    itemList: [],
    noRecord: {
      winH: null,
    },
    loginModal: {
      title: '请授权您的信息',
      msg: '医生需要获取您的信息进行，方便以后为您进行服务，拒绝将影响您正常使用，请选择允许授权后填写。',
      btn: '授 权'
    },
    type: 0,
    toA: '', //对方unionID  扫码获取
    // tab模板数据
    startX: 0, //开始坐标
    startY: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.data.type = options.type; //type=1扫描二维码加好友,=2我的医生进入
    that.data.toA = Util.isEmpty(options.id) ? "" : options.id;
    console.log("options",options)
    that.getHeight() // 获取屏幕高度
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    //获得modal组件
    that.modal = that.selectComponent("#modal");
    that.login = that.selectComponent("#login");
    that.answer = that.selectComponent("#answer");
    that.setData({
      showview: false
    })
    wx.login({
      success: function (msg) {
        Service.getOpenId(msg.code).then((res) => {
          wx.setStorageSync('user', res)
          return Service.getUserData(res.openid)
        }).then((res) => {
          if (Util.isEmpty(res.unionid)) {
            that.setData({
              showview: true,
            })
            that.login.showLogin();
          } else {
            wx.setStorageSync('data', res)
            that.setData({
              userInfo: res,
            })
            if (!App.globalData.isLogin) {
              Service.getUserSig(res.unionid).then((res1) => {
                return Tim.login(res1.data.userid, res1.data.sign)
              }).then(function (imResponse) {
                console.log('%c登录成功', "color:#04BE02", imResponse);
                if (imResponse.data.repeatLogin === true) {
                  // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
                  console.log('"%c本次登录操作为重复登录', "color:#ff0000", imResponse.data.errorInfo);
                }
                if (that.data.type == 1) {
                  that.addFriend(res);
                } else if (that.data.type == 2) {
                  that.getFriend(res.unionid)
                }
              }).catch(function (imError) {
                console.log('"%c登录失败', "color:#ff0000", imError); // 登录失败
                console.warn('login error:', imError); // 登录失败的相关信息
              });
            } else {
              if (that.data.type == 1) {
                that.addFriend(res);
              } else if (that.data.type == 2) {
                that.getFriend(res.unionid)
              }
            }
          }
        })
      }
    })
  },
  //获取好友
  getFriend: function (unionid) {
    let that = this
    Service.getFriendList(unionid).then((res) => {
      if (res.code == 1) {
        that.setData({
          itemList: res.data
        })
      }
      that.setData({
        showview: true,
      })
    }).catch((err)=>{
      that.setData({
        showview: true,
      })
    })
  },
  //添加好友
  addFriend(Data) {
    let that = this
    let data = {
      add_unionid: that.data.toA,
      unionid: Data.unionid,
      options_type: 1
    }
    Service.addFriend(data).then((res) => {
      console.log('addFriend', res)
      var showModal = {
        title: ' ',
        msg: res.msg,
        type: res.code
      }
      that.setData({
        showModal: showModal,
      })
      //1没服务 2有多个服务 3只有一个服务
      if (res.code == 3) {
        that.data.chat_home = res.data.chat_home
      }
      this.modal.showModal();
      this.modal.showCancel(false);
      that.getFriend(Data.unionid) // 获取好友
    })
  },
  //点击医生
  next: Util.debouce(function (e) {
    let item = e.currentTarget.dataset.item;
    let t_unionid=item.consultant_unionid;
    let data = {
      add_unionid:  item.consultant_unionid,
      unionid: wx.getStorageSync('data').unionid,
      options_type: 3
    }
    Service.addFriend(data).then((res) => {
     // code：1没服务 2有多个服务 3只有一个服务
      if (res.code == 1) {
        wx.navigateTo({
          url: '/packageA/selectUser/selectUser?type=3&t_unionid=' + t_unionid,
        })
      } else if (res.code == 2) {
        wx.navigateTo({
          url: '/packageB/myService/myService?t_unionid=' + t_unionid,
        })
      } else if(res.code == 3){
        wx.navigateTo({
          url: '/packageA/chat/chat?t_unionid=' + t_unionid + '&groupID=' + res.data.chat_home,
        })
      }else {
        wx.showToast({
          title:res.msg+'错误码：'+res.code,
          icon:"none"
        })
      }
    })
  }, 1000, true),
  //获取当前高度
  getHeight: function () {
    let that = this;
    wx.getSystemInfo({
      success: (res) => {
        that.setData({
          ['noRecord.winH']: res.windowHeight,
        })
      }
    });
  },
  //确认事件
  _confirmEvent: Util.debouce(function () {
    console.log('你点击了确定');
    this.modal.hideModal();
    this.doctorDetail(this.data.toA)
  }, 1000, true),
  //登录回调
  _refreshEvent() {
    console.log("刷新");
    this.onShow();
  },
  doctorDetail(t_unionid) {
    var that = this;
    var type = that.data.showModal.type;
    var data = {};
    data.unionid = t_unionid;
    Service.getChatDoctor(data).then((res) => {
      console.log("doctorDetail", res)
      if (res.code == 1) {
        if (type == 1) {
          wx.reLaunch({
            url: '/packageA/selectUser/selectUser?type=3&t_unionid=' + that.data.toA,
          })
        } else if (type == 2) {
          wx.reLaunch({
            url: '/packageB/myService/myService?t_unionid=' + that.data.toA,
          })
        } else {
          wx.reLaunch({
            url: '/packageA/chat/chat?t_unionid=' + that.data.toA + '&groupID=' + that.data.chat_home,
          })
        }
      } else {
        wx.switchTab({
          url: '/pages/index/index',
        })
      }
    })
  },
  touchE: function (e) {
    // console.log(e);
    var that = this
    if (e.changedTouches.length == 1) {
      //手指移动结束后触摸点位置的X坐标
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = that.data.startX - endX;
      var delBtnWidth = that.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "rpx" : "left:0rpx";

      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = that.data.itemList;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      that.setData({
        itemList: list
      });
    }
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.itemList.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      itemList: this.data.itemList
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引 
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.itemList.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      itemList: that.data.itemList
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除
  delBtn:Util.debouce(function(e) {
    let that = this
    let data = {}
    data.punionid = wx.getStorageSync('data').unionid
    data.cunionid = e.currentTarget.dataset.id
    Service.delFriend(data).then((res) => {
      if (res.code == 1) {
        wx.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 1500,
          success: function () {
            that.getFriend(wx.getStorageSync('data').unionid);
          }
        })
      }
    })
  },1000,true),
      /**
   * 图片加载失败函数
   * @param {any} e 
   */
  binderrorimg(e) {
    let errorindex = e.currentTarget.dataset.errorindex;
    let up = "itemList[" + errorindex + "].image";
    this.setData({
      [up]: '/images/doctor_img.png'
    })
  },
})