// pages/personCenter/personCenter.js
const app = getApp()
import {
  getInfo,
  editAvatar,
  editName,
  loginout,
  getConfig,
  editConfig
} from "../../../api/personCenter"
import {
  getSign
} from "../../../api/common"
import {throttle} from "../../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user_info: null,
    showCrop:false,
    fileList: [],
    isLock:false,
    src: '',
    img_host:'https://oss.prod.applets.igandanyiyuan.com/applet/patient/static',
    width: 250, //宽度
    height: 250, //高度
    max_width: 300,
    max_height: 300,
    disable_rotate: true, //是否禁用旋转
    disable_ratio: false, //锁定比例
    limit_move: true, //是否限制移动
  },
  goBack(){
   wx.navigateBack({
     delta: 1,
   })
  },
 upload(file){
  let THIS = this;
  wx.showToast({
    icon: "loading",
    title: '头像上传中'
  })
  getSign({
    user_type: 1,
    scene: 1
  }).then((resdata) => {
    let {
      accessid,
      dir,
      policy,
      signature,
      host
    } = resdata;
    let imgUrl = file.url;
    let index = imgUrl.lastIndexOf("/");
    let filename = new Date().getTime()+this.data.user_info.patient_id+imgUrl.substring(index + 1, imgUrl.length);
    wx.uploadFile({
      url: host, // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: {
        OSSAccessKeyId: accessid,
        policy,
        key: dir + filename,
        signature
      },
      success(res) {
        if (res.statusCode === 204) {
          let url = host + '/' + dir + filename;
          // 上传完成需要更新 fileList
          // const { fileList} = THIS.data;
          // fileList.push({ ...file, url: url });
          editAvatar({
            avatar: url
          }).then(res => {
            wx.showToast({
              icon: "none",
              title: '头像保存成功'
            })

            THIS.setData({
              'user_info.avatar': url
            });
          })

        }
      },
      fail: err => {
        console.log(err);
      }
    });

  })
 },
  afterRead(event) {
    const {
      file
    } = event.detail;
    console.log(file)
  this.setData({
     showCrop:true,
     src:file.url
   })
    

  },
  editNameModal() {
    let THIS = this;
    wx.showModal({
      title: '请输入姓名',
      editable: true,
      confirmColor: "#3CC7C0",
      success(res) {
        if (res.confirm) {
          if (!/^[\u4E00-\u9FA5A-Za-z0-9_]{2,10}$/.test(res.content)) {
            wx.showToast({
              title: `姓名要求在2-10个字符`,
              icon: 'none',
            });
            return false;
          };
          THIS.editNameHandle(res.content);

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  handleThrottle:throttle(function(){
    this.handleLogout()
  }),
  goNotify:throttle(function(){
    app.method.navigateTo({
      url: '/patient/pages/notify/notify',
    })
  }),
  handleLogout() {
   if(!this.data.isLock){
    if(wx.$TUIKit){
      wx.$TUIKit.destroy()
    };
    this.setData({
      isLock:true
    })
    loginout().then(data => {
      this.setData({
        isLock:false
      })
      wx.showToast({
        title: `退出成功`,
        icon: 'none',
      });
      app.globalData.totalUnread=0;
      app.globalData.conversationList=[];
      wx.clearStorageSync();
      wx.setStorageSync('hasEntry', true);
      wx.reLaunch({
        url: '/patient/pages/login/login'
      })
   
    })
   }
    
  },
  
  editNameHandle(user_name) {
    editName({
      user_name
    }).then(data => {
      this.setData({
        'user_info.user_name': user_name
      })
      wx.showToast({
        title: `姓名修改成功`,
        icon: 'none',
      });
    })
  },
  getInfoDetail() {
    getInfo().then((data) => {
      this.setData({
        user_info: data
      })

    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getInfoDetail();
    this.initCrop(options);
  },
  closeCrop(){
    this.setData({
      showCrop:false
    })
  },
  submit() {
    this.setData({
      showCrop:false
    })
    this.cropper.getImg((obj) => {
        console.log(obj)
      this.upload(obj)
    });
},
cropperload(e) {
  console.log('cropper加载完成');
},
  initCrop(options){
  
    this.cropper = this.selectComponent("#image-cropper");

    

    if(options.imgSrc){
      this.setData({
        src: options.imgSrc
    });
    }
   
    // if(!options.imgSrc){
    //     this.cropper.upload(); //上传图片
    // }
  },
  loadimage(e) {

    this.cropper.imgReset();
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      img_host:app.hostConfig().imghost
    })
  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  
})