// pages/home/xyc/index.js
import FormData from './../../../utils/formdata/index'
import Toast from 'tdesign-miniprogram/toast/index';
const app = getApp();//新建页面时 默认引入
const req = app.xzjlReq();//初始化一个的request() 实例
Page({

    /**
     * 页面的初始数据
     */
    data: {
        xyLink:'',
        xyContent:'',
        imgUrl:'',
        fileList: [],//图片list
        form:{
            content:"",
            deadline:'',
            link:'',
            img:''
        },
        minDate:new Date().getTime() + 24 * 60 * 60 * 1000,
        cvisible: false,
        note: '',
        xyForm:{},
        visible:false,//弹窗
        single:true,
        xzInfo:{},
        userInfo:{},
        xyNfc:true,
        xyInfo:{},
        showXyz:false, //显示许愿中弹层
        showDetail:false, //许愿成功回显弹层
        shareVisible:false //显示分享页面
    },
    handleAdd(e){/**添加图片 */
         const { fileList } = this.data;
       const { files } = e.detail;

       // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
       this.setData({
         fileList: [...fileList, ...files], // 此时设置了 fileList 之后才会展示选择的图片
       });
       files.forEach(file => this.uploadFile(file))
    },
    handleRemove(e){/**删除图片 */
        const { index } = e.detail;
        const { fileList } = this.data;
  
        fileList.splice(index, 1);
        this.setData({
          fileList,
        });
    },
    uploadFile(file) {/**执行 */
    console.log(file,'这里');
        wx.uploadFile({
            url: 'https://xzjl-api.windymuse.cn/api/resource',
            filePath: file.url,
            name: 'file',
            header: {
                'Authorization': wx.getStorageSync('token'),        
              'Content-Type': 'multipart/form-data'
            },
            formData: {
              type: 'poster'
            },
            success: async res => {
              let data = JSON.parse(res.data);
              console.log(data, '111111');
              if (data.code == 200) {
                  this.setData({imgUrl:data.data.abUrl})
                  console.log('打印1111')
                  console.log(this.data.imgUrl)
                res.data = JSON.parse(res.data);
                console.log(res.data);
                if (res.data.code == 1) {
                  console.log(res.data.data.url);
                  this.img = this.baseUrl + res.data.data.url;
                  // 图片路径
                  this.userinfo.avatar = res.data.data.url;
                  // let n = await this.$api.upload({ file: res.data.fullurl });
                  // console.log(n, '上传后');
                }
              }
            },
            fail(res) {
              showToast('图片上传失败');
            }
          });
    },
    go2MyYw(){
        wx.navigateTo({
            url: '/pages/home/xyc/wdyw/wdyw'
            })
    },
    go2TaYw(){
        wx.navigateTo({
            url: '/pages/home/xyc/tdyw/tdyw'
            })

    },
    doXzTime(){
        this.setData({ cvisible: true });
        console.log('执行选择时间')
    },
    handleConfirm(e) {
        console.log(e,'111');
        const { value } = e.detail;
        const format = (val) => {
          const date = new Date(val);
          const year = date.getFullYear();
          const month = (date.getMonth() + 1).toString().padStart(2, '0');
          const day = date.getDate().toString().padStart(2, '0');
          return `${year}-${month}-${day}`;
        };
  
        this.setData({
          note: format(value)
        });
      },
      onClose({ detail }) {
        console.log(detail.trigger);
      },
    showMultiText() {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '投枚银币许个愿吧\n守护精灵将会祝福你的愿望！',
          dataduration:10
        });
      },
      doXyPop(){/**弹出许愿弹窗 */
        console.log('执行力。。。。。')
        this.setData({visible:true})

      },
      onVisibleChange(e) {
        this.setData({
          visible: e.detail.visible,
        });
      },
      doCancelXy(){/**取消许愿 */
        this.setData({
            visible: false,
          });

      },
      doFinishXy(e){/**许愿 */
        if(!this.data.xyContent){
            wx.showToast({
                title:'许愿内容不能为空！',
                icon: 'none',
                duration: 5000
            })
        }else if(!this.data.note){
            wx.showToast({
                title:'期望事件不能为空！',
                icon: 'none',
                duration: 5000
            })
        }else if(!this.data.imgUrl){
            wx.showToast({
                title:'许愿图片不能为空！',
                icon: 'none',
                duration: 5000
            })
        }else{
              console.log('图片地址', this.data.imgUrl);
              console.log('图片地址', this.data.xyLink);
              req.postRequest('/api/user/curt/wish',{content:this.data.xyContent,deadline:this.data.note,img:this.data.imgUrl,link:this.data.xyLink}).then((res)=>{
                console.log('许愿成功11111！')
                console.log(res)
                if(res.data.code==200){
                    this.setData({
                        visible: false,
                      });
                    this.setData({userInfo:res.data.data})
                    if(res.data.data&&res.data.data.loverId&&res.data.data.loverId!=null){
                        this.setData({single:false})
                    }
                    this.setData({xyContent:'',xyLink:'',note:'',imgUrl:'',fileList:[],showXyz:true})
                    setTimeout(()=>{
                      this.setData({
                        showXyz:false,
                        showDetail:true,
                        item:res.data.data
                      })
                    },2000)
                }else{
                    console.log('额外情况')
                    wx.showToast({
                        title:res.data.msg,
                        icon: 'none',
                        duration: 5000
                    })
                }
                

               }).catch((err)=>{
                wx.showToast({
                    title:'出错了：'+err.data.msg,
                    icon: 'none',
                    duration: 5000
                })
            })
              console.log('许愿成功111！')
        }
        

      },
    initXy(){
        req.getRequest('/api/user/curt',{}).then((res)=>{
            console.log(res)
            if(res.data.code==200){
                this.setData({userInfo:res.data.data})
                if(res.data.data&&res.data.data.loverId&&res.data.data.loverId!=null){
                    this.setData({single:false})
                }
            }
            console.log(this.userInfo);
           }).catch((err)=>{
            console.log(err);
        })
        this.setData({xyInfo:wx.getStorageSync('nfc')})
    },
    // 关闭回显
    closeDetail(){
      this.setData({
        showDetail: false
      })
    },
    // 分享
    openShare(){
      this.setData({
        shareVisible:!this.data.shareVisible
      })
    },
    shareQQ(){
      console.log('分享到qq')
    },
    downLoad(){
      console.log('下载图片');
      wx.downloadFile({
        url: 'https://res.wx.qq.com/wxdoc/dist/assets/img/demo.ef5c5bef.jpg',
        success: (res) => {
          wx.showShareImageMenu({
            path: res.tempFilePath
          })
        }
      })
    },
    // 获取我的许愿
    getMyWish(){
      req.getRequest('/api/user/curt/wish',{}).then((res)=>{
          if(res.data.code==200){
              this.setData({wishes:res.data.data.records})
          }
         }).catch((err)=>{
          console.log(err);
      })
    },

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

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

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

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

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

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

    },

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

    },

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

    // 分享到朋友圈
    onShareTimeline(){}
})