// pages/home/xyc/wdyw/wdyw.js
const app = getApp();//新建页面时 默认引入
const req = app.xzjlReq();//初始化一个的request() 实例
import Wxml2Canvas from 'wxml2canvas'; 
Page({

    /**
     * 页面的初始数据
     */
    data: {
        showDelDialog:false,
        detail:{},
        visible:false,
        shareVisible:false, //分享弹层
        wishes:[],
        showCanvas: true
    },
    // 分享微信
    shareWx(){
        console.log('分享微信')
    },

    getImg(){
        console.log('获取图片');
        this.drawMyCanvas()
        this.setData({shareVisible: false, showCanvas:true})
    },

    drawMyCanvas() {
        wx.showLoading({
            title: '图片生成中'
        })
        const that = this
        const query = wx.createSelectorQuery().in(this);
        query.select('#my-canvas').fields({ // 选择需要生成canvas的范围
            size: true,
            scrollOffset: true
        }, data => {
            let width = data.width;
            let height = data.height;
            that.setData({
                width,
                height
            })
            setTimeout(() => {
                that.startDraw()
            }, 1500);
       }).exec()
},
startDraw() {
        let that = this
        
        // 创建wxml2canvas对象
        let drawMyImage = new Wxml2Canvas({
          element: 'myCanvas', // canvas的id,
          obj: that, // 传入当前组件的this
          width: that.data.width ,
          height: that.data.height,
          background: '#fff', // 生成图片的背景色
          progress(percent) { // 进度
            // console.log(percent);
          },
          finish(url) { // 生成的图片
            wx.hideLoading()
            console.log(url);
            that.savePoster(url)
          },
          error(res) { // 失败原因
            console.log(res);
            wx.hideLoading()
          }
        }, this);
        let data = {
            // 获取wxml数据
            list: [{
                type: 'wxml',
                class: '.my_canvas .my_draw_canvas',  // my_canvas要绘制的wxml元素根类名， my_draw_canvas单个元素的类名（所有要绘制的单个元素都要添加该类名）
                limit: '.my_canvas', // 要绘制的wxml元素根类名
                x: 0,
                y: 0
            }]
        }
        // 绘制canvas
        drawMyImage.draw(data, this);
    },
    savePoster(url) {
        const that = this
        wx.saveImageToPhotosAlbum({
            filePath: url,
            success: () => {
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    duration: 1500
                });
                this.setData({showCanvas : false})
            },
            fail(err) {
              if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                wx.showModal({
                  title: '提示',
                  content: '需要您授权保存相册',
                  showCancel: false,
                  success: modalSuccess => {
                    wx.openSetting({
                      success(settingdata) {
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                            wx.saveImageToPhotosAlbum({
                                filePath: url,
                                success: function () {
                                  wx.showToast({
                                    title: '保存成功',
                                    icon: 'success',
                                    duration: 2000
                                  })
                                },
                            })
                        } else {
                            wx.showToast({
                                title: '授权失败，请稍后重新获取',
                                icon: 'none',
                                duration: 1500
                            });
                        }
                      }
                    })
                  }
                })
              }
            }
          })
      },



    showShare(){
        this.setData({
            shareVisible:!this.data.shareVisible
        })
    },
    go2DelDialog(){
        this.setData({showDelDialog:true})
    },
    closeDelDialog(){
        this.setData({showDelDialog:false})
    },
    confirmDelDialog(e){
        /**确定删除愿望 */
        this.setData({showDelDialog:false})
        req.deleteRequest('/api/user/curt/wish/'+this.data.detail.id,{}).then((res)=>{
            console.log(res)
            if(res.data.code==200){
                wx.showToast({
                    title:'愿望删除成功',
                    icon: 'none',
                    duration: 1000,
                })
                this.getMyWish()
                this.setData({
                    visible: false
                })
            }
           }).catch((err)=>{
            console.log(err);
        })
    },
    doFinishWish(e){/**愿望已达成 */
        console.log(e.target.dataset.del)
        console.log('愿望达成')
        console.log(this.data.detail.id)
        /**确定删除愿望 */
        this.setData({showDelDialog:false})
        req.patchRequest('/api/user/curt/wish/'+this.data.detail.id+"/completed",{}).then((res)=>{
            console.log(res)
            if(res.data.code==200){
                wx.showToast({
                    title:'愿望达成成功',
                    icon: 'none',
                    duration: 1000
                })
                this.getMyWish()
                this.setData({visible: false})
            }else{
                wx.showToast({
                    title:res.data.msg,
                    icon: 'none',
                    duration: 1000
                })
            }
           }).catch((err)=>{
            console.log(err);
        })
    },
    go2WishDetail(e){/**查看愿望详情 */
        this.setData({visible:true,detail:e.currentTarget.dataset.wish})
        this.setData({detail:e.currentTarget.dataset.wish})
    },
    onVisibleChange(e) {
        this.setData({
          visible: e.detail.visible,
        });
      },
    changeVisible(){
        this.setData({
            visible:false, 
            showCanvas:false,
            shareVisible: false
        })
    },
    closeVisible(){
        this.setData({visible : false})
    },
    go2Reback(){
        // wx.navigateBack({ changed: true });
        wx.switchTab({
            url: '/pages/home/xyc/index'
        })
    },
    getMyWish(){
        req.getRequest('/api/user/curt/wish',{limit: '-1'}).then((res)=>{
            if(res.data.code==200){
                this.setData({wishes:res.data.data.records})
            }
            }).catch((err)=>{
            console.log(err);
        })
    },
    // 修改愿望 回显数据
    editYw(){
        console.log('1111');
        const id = this.data.detail.id
        wx.reLaunch({
            url: '/pages/home/xyc/index?id=' + id
        })
    },

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

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

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

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

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

    },

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

    },

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

    },

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

    },

    onShareTimeline(){
    }
})