// pages/cloud_currency_center/cloud_currency_center.js
const axios = require('../../api/index')
let http = require('../../utils/request')

const bs4 = require('./data')
const app = getApp()
Page({

  /**pathway_list
   * 页面的初始数据
   */
  data: {
    imgurl: '',
    cloud_recharge_list: [

    ],
    recharge_grid_idx: 0,
    cloud_tag_list: [{
      name: '云币充值',
      imageUrl: '/images/me/cloud_1.png',
      selectImageUrl: '/images/me/cloud_1_select.png',
    }, {
      name: '优惠卡充值',
      imageUrl: '/images/me/cloud_2.png',
      selectImageUrl: '/images/me/cloud_2_select.png',
    }, {
      name: '云币账单',
      imageUrl: '/images/me/cloud_3.png',
      selectImageUrl: '/images/me/cloud_3_select.png'
    }, {
      name: '邀请好友',
      imageUrl: '/images/me/cloud_4.png',
      selectImageUrl: '/images/me/cloud_4_select.png'
    }],
    bill_type_list: ['全部', '收入', '支出'],
    bill_type_idx: 0,
    cloud_tag_idx: 0,
    currency_list: null,
    currentPage: 1,
    pageSize: 20,
    detail: {
      availableCurrency: 3,
      officialCurrency: 3,
      temporarylCurrency: 0,
      userId: 256644812259397
    },
    // 优惠卡确认购买
    is_show_modal: false,
    cardintro_list: [],
    iscardintro:0,
    // 从不够钱过来的
    // is_come:0,//1是详情页,2是
  },
  /**buy_vip_card
 * 生命周期函数--监听页面加载
 */
  onLoad: function (options) {
    if(options.is_come){
      this.setData({
        is_come:options.is_come
      })
    }
    if(options.index){
      this.setData({
        cloud_tag_idx:options.index
      })
    }
    this.getCardintro()
    this.get_cloud_recharge_list()
  },
  // 优惠卡
  getCardintro() {
    // 获取优惠卡
    axios.getCardintro().then((res) => {
      this.setData({
        cardintro_list: res.data
      })
    }
    )
  },
  confirm_fn() {//确认购买
    // console.log(this.data.cardintro_list[this.data.iscardintro].id)
    var id=this.data.cardintro_list[this.data.iscardintro].id
    var data ={id,type:2}
    axios.wxpay(data).then(res => {
      console.log(res)
      let { timeStamp, nonceStr, signType, paySign } = res.data;
      wx.requestPayment({
        timeStamp, nonceStr, signType, paySign, package: res.data.package,
        success: res => {
            axios.getUser().then(res => {
              console.log(res)
            app.globalData.userInfo = res.data
            wx.setStorageSync('userInfo', res.data)
            wx.showToast({
              title: '充值成功',
              icon:'none'
            })
            if(this.data.is_come==1){
              setTimeout(()=>{
                wx.navigateBack()
              },1000)
            }else{
              this.onShow()
            }
            this.onShow()
          })
        },
        fail: err => {
        },
        complete: e => {
        }
      })
    })
    this.setData({
      is_show_modal: false
    })
  },
  hide_modal() {//取消购买
    this.setData({
      is_show_modal: false
    })
  },
  // 点击购买优惠卡
  buy_vip_card(e) {
    this.setData({
      iscardintro:e.currentTarget.dataset.idx
    })
    this.setData({
      is_show_modal: true
    })
  },
  get_cloud_recharge_list() {
    // console.log(1)
    axios.getRecharge().then(res => {
      console.log(res)
      this.setData({
        cloud_recharge_list: res.data
      })
    })
    // var cloud_recharge_list = { "id": 1001, "name": "云车招聘充值活动,充得越多送的越多!", "introOutputs": [{ "id": 1001, "productName": "30云币", "productValue": 30, "sendValue": 8, "allValue": 38, "price": 29.0, "description": "38云币(可拨打38个电话)" }, { "id": 1002, "productName": "60云币", "productValue": 60, "sendValue": 18, "allValue": 78, "price": 59.0, "description": "78云币(可拨打78个电话)" }, { "id": 1003, "productName": "100云币", "productValue": 100, "sendValue": 38, "allValue": 138, "price": 99.0, "description": "138云币(可拨打138个电话)" }, { "id": 1004, "productName": "200云币", "productValue": 200, "sendValue": 68, "allValue": 268, "price": 199.0, "description": "268云币(可拨打268个电话)" }, { "id": 1005, "productName": "400云币", "productValue": 400, "sendValue": 108, "allValue": 508, "price": 399.0, "description": "508云币(可拨打508个电话)" }, { "id": 1006, "productName": "600云币", "productValue": 600, "sendValue": 158, "allValue": 758, "price": 599.0, "description": "758云币(可拨打758个电话)" }] }
    // this.setData({
    //   cloud_recharge_list: cloud_recharge_list
    // })
  },
  wxpay() {
    let { cloud_recharge_list, recharge_grid_idx } = this.data;
    let id = cloud_recharge_list.introOutputs[recharge_grid_idx].id;
    var data ={id,type:1}
    axios.wxpay(data).then(res => {
      console.log(res)
      let { timeStamp, nonceStr, signType, paySign } = res.data;
      wx.requestPayment({
        timeStamp, nonceStr, signType, paySign, package: res.data.package,
        success: res => {
          console.log(res)
          var num=Number(cloud_recharge_list.introOutputs[recharge_grid_idx].allValue)+Number(cloud_recharge_list.introOutputs[recharge_grid_idx].sendValue)
          wx.showToast({
            title: '充值'+num+'云币成功',
            icon:'none'
          })
          if(this.data.is_come==1){
            setTimeout(()=>{
              wx.navigateBack()
            },1000)
          }else{
            this.onShow()
          }
        },
        fail: err => {
        },
        complete: e => {
        }
      })
    })
  },
  recharge_grid(e) {
    this.setData({
      recharge_grid_idx: e.currentTarget.dataset.idx
    })
  },
  close() {
    wx.navigateBack()
  },
  bill_type_fn(e) {
    let bill_type_idx = e.currentTarget.dataset.idx;
    this.setData({
      bill_type_idx,
      currency_list: null,
      currentPage: 1,
    }, () => {
      this.get_currency_list()
    })
  },
  cloud_tag_fn(e) {
    let cloud_tag_idx = e.currentTarget.dataset.idx;
    this.setData({
      cloud_tag_idx,
      currency_list: null
    }, () => {
      if (cloud_tag_idx != 2) return
      this.get_currency_list()
    })
  },
  // 获取云币获取列表项
  get_type_list() {
    axios.getTypeList().then(res => {
      this.setData({
        pathway_list: res.data
      })
    })
  },
  // 获取云币
  get_currency_list() {
    let { bill_type_idx, currentPage, pageSize } = this.data,
      data = {
        currencyType: bill_type_idx,
        currentPage,
        pageSize
      };
    axios.getCurrencyList(data).then(res => {
      // console.log(res)
      let { currency_list } = this.data;
      if (currentPage == 1) {
        currency_list = [];
      }
      currency_list.push(...res.data.list)
      this.setData({
        currency_list,
        list_total: res.data.total,
        refresh: false,
        load: false,
        triggered: false
      })
    })
  },
  //   获取我的云币
  get_currency() {
    axios.getMyCurrency().then(res => {
      this.setData({
        detail: res.data
      })
    })
  },
  go_detail(e) {
    let data = e.currentTarget.dataset.item, { currencyType, currencySoureObjectId } = data, type = '';
    if (currencyType == 13 || currencyType == 16 || currencyType == 17) {
      type = 'recruitment'
    } else if (currencyType == 12 || currencyType == 15 || currencyType == 18) {
      type = 'apply'
    };
    wx.navigateTo({
      url: `/pages/detail/detail?type=${type}&id=${currencySoureObjectId}`,
    })
  },
  // 上拉加载
  onScrolltolower() {
    this.setData({
      currentPage: this.data.currentPage + 1,
      load: true,
    }, () => {
      this.get_currency_list()
    })
  },
  // 下拉刷新
  onRefresh() {
    this.setData({
      currentPage: 1,
      triggered: true,
      list: [],
      list_total: 0,
      refresh: true
    }, () => {
      this.get_currency_list()
    })
  },
  create_image1() {
    // var bs4=bs4.data
    // console.log(JSON.parse(bs4.data).buffer)
    var base64 = '/eyJlcnJjb2RlIjo0MjAwMSwiZXJybXNnIjoiYWNjZXNzX3Rva2VuIGV4cGlyZWQgcmlkOiA2MjE4NzJhMS0wZTM2ODczNi0zN2IwZmNiOSJ9'
    base64 = 'data:image/jpeg;base64,' + base64
    console.log(base64)
    this.setData({
      imgurl: base64
    })
  },
  // 生成图片
  create_image() {
    // 生成海报
    wx.showLoading({
      title: '正在生成图片',
    })
    http.xhr({
      url: 'api/v1/auth/weixin/unlimited'
    }).then(res => {
    var  base64 = JSON.parse(res.data).buffer;
    base64 = 'data:image/jpeg;base64,' + base64
    // var base64 = 'eyJlcnJjb2RlIjo0MjAwMSwiZXJybXNnIjoiYWNjZXNzX3Rva2VuIGV4cGlyZWQgcmlkOiA2MjE4NzJhMS0wZTM2ODczNi0zN2IwZmNiOSJ9'
    // base64 = 'data:image/jpeg;base64,' + base64
    this.triggerEvent('hide_share_mask_fn', false)
    // 处理二维码
    var imgPath = wx.env.USER_DATA_PATH + '/fx' + new Date().getTime() + '.png';
    var imageData = base64.replace(/^data:image\/\w+;base64,/, "");
    console.log(imageData)
    var fs = wx.getFileSystemManager();
    fs.writeFileSync(imgPath, imageData, "base64");
    let userInfo = wx.getStorageSync('userInfo');
    let left = 47, top = 0;
    console.log(userInfo)
    let paintPallette = {
      width: `${375}px`,
      height: `${553}px`,
      background: '#fff',
      borderRadius: '8px',
      views: [{
        type: 'image',
        url: '/images/publish/canvas_background2.png',
        css: {
          top: '0',
          left: '0',
          width: `${375}px`,
          height: `${553}px`,
          color: '#fff',
          borderRadius: '8px'
        }
      }, { //头像
        type: 'image',
        url: `${userInfo.avatarUrl}`,
        css: {
          top: `50px`,
          left: `${left}px`,
          width: '42px',
          height: '42px',
          borderRadius: '21px',
          borderColor: '#E6E6E6',
          borderWidth: '1px'
        }
      },
      { //姓名
        type: 'text',
        text: `${userInfo.userName}`,
        css: {
          top: `60px`,
          left: '97px',
          maxLines: 1,
          fontSize: '16px',
          color: '#888888',
        },
      }, {
        type: 'text',
        text: "直买直卖,没有中间商赚差价,卖车买车就来云车二手 ~~",
        css: {
          top: `110px`,
          left: `60px`,
          width: `240px`,
          maxLines: 4,
          fontSize: '16px',
          color: '#888888',
          lineHeight: '24px'
        },
      }, {
        type: 'text',
        text: `长按识别二维码,查看更多车辆信息`,
        css: {
          top: `${414}px`,
          left: '42px',
          width: `300px`,
          textAlign: "center",
          lineHeight: '28px',
          color: '#1f6cff',
          fontSize: '16px',
          maxLines: 1,
        },
      }, {
        type: 'text',
        text: `欢迎转发分享~`,
        css: {
          top: `${455}px`,
          left: '42px',
          width: `300px`,
          textAlign: "center",
          lineHeight: '28px',
          color: '#1f6cff',
          fontSize: '16px',
        },
      }, {
        type: 'image',
        url: `${imgPath}`,
        css: {
          top: `${242}px`,
          left: `${118}px`,
          width: '144px',
          height: '144px',
        }
      }]
    };
    this.setData({
      paintPallette
    })
    }).catch(err => {
      console.log(err)
    })

  },
  image_mask_fn() {
    this.setData({
      imagePath: '',
      paintPallette: ''
    })
  },
  onImgOK(e) {
    let imagePath = e.detail.path;
    this.setData({
      imagePath: imagePath
    })
  },
  image_load() {
    this.setData({
      is_show_share_mask: false
    })
    wx.hideLoading()
  },
  save_image() {
    let url = this.data.imagePath;
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              // 同意授权
              this.save_img_fn(url);
            },
            fail: (res) => {
              wx.showModal({
                content: '暂无权限保存本地,点击确认前往设置页面开启权限',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting({
                      withSubscriptions: true,
                    })
                  }
                }
              })
            }
          })
        } else {
          // 已经授权了
          this.save_img_fn(url);
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '您还未授权,请授权',
          icon: 'none'
        })
      }
    })
  },
  save_img_fn(url) {
    wx.getImageInfo({
      src: url,
      success: (res) => {
        let path = res.path;
        wx.saveImageToPhotosAlbum({
          filePath: path,
          success: (res) => {
            wx.showToast({
              title: '保存成功',
              icon: 'none'
            })
          },
          fail: (res) => {
            wx.showToast({
              title: '保存失败',
              icon: 'none'
            })
          }
        })
      },
      fail: (res) => { }
    })
  },


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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.get_currency()
    // this.get_type_list()
    this.get_currency_list()
  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    let share_data = app.global_share()
    let userInfo = wx.getStorageSync('userInfo')
    if (e.from == "button") {
      console.log(1)
      share_data.path = `/pages/index/index?shareType=newusers&userId=${userInfo.id}`
    }
    return share_data
  }
})