// pages/userCenter.js
const app = getApp()
const wxService = require('../../utils/wxService')
const utils = require('../../utils/util')
const envInfo = require('../../config/index').envInfo
var wxbarcode = require('../../codeUtils/index.js');
var count = 0;
const COLOR_OBJ = {
  Color010: '#63B359',
  Color020: '#2C9F67',
  Color030: '#509FC9',
  Color040: '#5885CF',
  Color050: '#9062C0',
  Color060: '#D09A45',
  Color070: '#E4B138',
  Color080: '#EE903C',
  Color081: '#F08500',
  Color082: '#A9D92D',
  Color090: '#DD6549',
  Color100: '#CC463D',
  Color101: '#CF3E36',
  Color102: '#5E6671',
}

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    endTime: '', // 2017-09-01
    date: '',
    focus: false,
    memberCardNo: '',
    memberInfo: {},
    memberId: '',
    array: ['男', '女', '保密'],
    objectArray: [
      {
        id: 0,
        name: '男'
      },
      {
        id: 1,
        name: '女'
      },
      {
        id: 2,
        name: '保密'
      }
    ],
    index: 0,
    cardStyle : {
      bgColor : '',
      bgUrl : ''
    },
    cardNoOffline : '',
    qrCardNo : '',
    membershipCardnoType: '1', ////1 舞象会员卡号 2 关联实卡号
    codeType: '',//CODE_TYPE_QRCODE 二维码  //CODE_TYPE_BARCODE 条形码  ///CODE_TYPE_TEXT 仅展示卡号
  },
  bindPickerChange(e) {
    this.setData({
      index: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.hideShareMenu();
    const { memberCardNo, memberId , member} = wx.getStorageSync('_baseUserInfo')
    // if(memberCardNo){

    // }
    if (member){
      this.data.cardNoOffline = member.cardNoOffline;
    }
  },
  //获取会员卡面设置
  getMemberCardSetting(){
    wxService.post(`/member/cardSetting/getByBrandId`).then(res => {
      let obj = res.data.data ? res.data.data.cardStyle : {};
      if (obj.backgroundPicUrl){
        this.data.cardStyle.bgUrl = obj.backgroundPicUrl;
        this.data.cardStyle.bgColor = '';
      }
      else if(obj.color){
        this.data.cardStyle.bgUrl = '';
        this.data.cardStyle.bgColor = COLOR_OBJ[obj.color];
      }
      else{
        this.data.cardStyle.bgUrl = 'https://bigaka-xie.oss-cn-shanghai.aliyuncs.com/711_08.png';
        this.data.cardStyle.bgColor = '';
      }

      let tempObj = res.data.data ? res.data.data : {};

      this.data.membershipCardnoType = tempObj.membershipCardnoType ? tempObj.membershipCardnoType : 1;
      this.data.codeType = tempObj.codeType ? tempObj.codeType : 'CODE_TYPE_BARCODE';
      // this.data.codeType = 'CODE_TYPE_TEXT';
      // this.data.codeType =  'CODE_TYPE_QRCODE';
      // this.data.codeType = 'CODE_TYPE_BARCODE';
      if (this.data.membershipCardnoType == 1){
        //舞象会员卡号
        this.data.qrCardNo = this.data.memberCardNo;
      }
      else{
        //三方实体卡
        this.data.qrCardNo = this.data.cardNoOffline;
      }

      // this.data.qrCardNo = this.data.memberCardNo;

      this.setData({
        qrCardNo: this.data.qrCardNo,
        membershipCardnoType: this.data.membershipCardnoType,
        codeType: this.data.codeType,
        cardStyle: this.data.cardStyle
      },() => {
        if (this.data.codeType == 'CODE_TYPE_QRCODE'){
          this.generateQrcode();
        }
        else if (this.data.codeType == 'CODE_TYPE_BARCODE'){
          this.generateBarCode();
        }
      });
    })
  },
  //生成条形码
  generateBarCode(){
    wxbarcode.barcode('barcode', this.data.qrCardNo, 500, 120);
    setTimeout(() => {
      wxbarcode.barcode('barcode', this.data.qrCardNo, 500, 120);
    }, 200);
  },
  //生成二维码
  generateQrcode(){
    wxbarcode.qrcode('qrcode', this.data.qrCardNo, 300, 300);
    setTimeout(() => {
      wxbarcode.qrcode('qrcode', this.data.qrCardNo, 300, 300);
    }, 200);
  },
  //微信支付
  onTapWxPay() {
    //调用接口回调拼接数据 TODO
    this.getPayCodeParam();
  },

  //获取小程序支付码配置参数
  getPayCodeParam() {
    wxService.get(`/platform/brand/openOfflinePayView`).then(res => {
      if (!res) return false;
      const { result, data } = res && res.data || res && res.result
      if (result == 0) {
        wx.openOfflinePayView({
          appId: data.appId,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: data.signType,
          timeStamp: data.timeStamp,
          paySign: data.paySign,
          success: function (res) {
            console.log('success', res)
          },
          fail: function (res) {
            console.log('error', res)
          },
          complete: function (res) {
            console.log('complete', res)
          }
        })
        // this.setInternal();
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 取会员卡号
    const { memberCardNo, memberId } = wx.getStorageSync('_baseUserInfo')
    if (memberCardNo && memberId) {
      // 获取当前日期
      const currentDate = utils.formatDate(new Date())
      this.setData({
        endTime: currentDate
      }, () => {
        this.setData({
          memberCardNo,
          memberId
        }, () => {
          // 获取会员信息
          this.getMemberFind()
        })
      })
    }
  },
  bindDateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },
  formSubmit(e) {
    // 0 男 1 女
    const { sex, email } = e.detail.value
    if (sex == 0) {
      e.detail.value.sex = '男'
    } else if (sex == 1) {
      e.detail.value.sex = '女'
    } else {
      e.detail.value.sex = '保密'
    }
    // 校验邮箱
    if (email) {
      let emailFlag = utils.validateEmail(email)
      if (!emailFlag) {
        wx.showToast({
          title: `请输入正确的邮箱地址!`,
          icon: 'none'
        })
        return false
      }
    }
    const params = e.detail.value
    // 保存接口
    this.handelMemberUplate(params)
  },
  // 会员详情
  getMemberFind() {
    wx.showLoading({
      title: '加载中'
    })
    const params = {
      cardNoOnline: this.data.memberCardNo
    }
    wxService.post(`/member/find`, params).then(res => {
      if (!res) return false
      const { result, data } = res && res.data || res && res.result
      if (result == 0) {
        wx.hideLoading()
        data.member.birthday = data.member.birthday && data.member.birthday.substring(0, 10) || ''
        // 性别
        const { sex } = data.member
        if (sex == '男') {
          data.member.sex = 0
        } else if (sex == '女') {
          data.member.sex = 1
        } else {
          data.member.sex = 2
        }
        this.setData({
          cardNoOffline: data.member.cardNoOffline,
          memberInfo: data.member,
          index: data.member.sex,
          date: data.member.birthday
        },() => {
          this.getMemberCardSetting();
        })
        // this.setInternal();
      }
    })
  },
  //定时刷新 10s
  setInternal() {
    var timeOut = setInterval(() => {
      if (count < 10) {
        count++;
        wxbarcode.barcode('barcode', this.data.memberCardNo, 500, 120);
      }
      else {
        clearInterval(timeOut);
      }
    }, 500);
  },

  canvasIdErrorCallback(e) {
    console.log('code-me', e.detail.errMsg)
  },
  // 更新
  handelMemberUplate(params) {
    wx.showLoading({
      title: '加载中'
    })
    params.id = this.data.memberId
    wxService.post(`/member/update`, params).then(res => {
      const { result, data } = res.data
      if (result == 0) {
        wx.hideLoading()
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    })
  },
  bindTextAreaBlur: function (e) {
    console.log(e.detail.value)
  },

  //日期选择
  bindDateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },
  handleGoWxCard() {
    // wechatCardId wechatCode
    // const { wechatCardId, wechatCode } = wx.getStorageSync('_baseUserInfo')
    // wx.openCard({
    //   cardList: [{
    //     cardId: wechatCardId,
    //     code: wechatCode
    //   }],
    //   success(res) {
    //     console.log('查看微信卡包中的卡券', res)
    //   }
    // })

  }
})