<template>
	<view class="">
		<view id="call">
		    <view class="call-box" @tap="jumpDetail">
		        <image mode="widthFix" :src="info.data.free.img" alt></image>
		        <view class="name" v-if="info.data.free.label!=undefined">
		            {{info.data.free.label}}
		        </view>
		    </view>
		    <view class="time-box" :class="info.data.free.activity_status == 'OnGoing' ? 'active' : ''" v-if="info.free.activity_status == 'NoBegin'">
		        <seckill :end="info.data.free.ends_at" :starts="info.data.free.starts_at" typename="集call" :server="info.data.free.server_time" mold="list" @starts="isStarts" @end="isEnd"></seckill>
		    </view>
		    <view class="call-user">
		        <image v-if="info.data.task_user_avatar" :src="info.data.task_user_avatar"></image>
		        <image v-else src="http://ovef29y3v.bkt.clouddn.com/%E5%A4%B4%E5%83%8F_%E7%94%BB%E6%9D%BF%201.png"></image>
		        <view class="call-status">
		            <view v-if="!info.meta.is_call && info.data.gap_task != 0">还差 <span>{{info.data.gap_task}}</span> 个Call就可以免费领取礼品了，求助攻~</view>
		            <view v-if="info.data.gap_task == 0 && !info.meta.is_call">我已集满</view>
		            <view v-if="info.meta.is_call && Brand_name != 'UTO'">感谢你为我打Call~</view>
		            <view v-if="info.meta.is_call && Brand_name == 'UTO'">听说给我点赞的朋友都变好看了~</view>
		            <!--<view class="receive" wx:if="{{info.data.gap_task == 0}}">立即领取 》</view>-->
		        </view>
		    </view>
		    <view class="share-box" :style="'color: ' + config.mainColor" v-if="info.data.free.activity_status == 'OnGoing'">
		        <button class="friends claa-btn" :style="'background: ' + config.mainColor" v-if="!info.meta.is_call && info.data.gap_task != 0 && !token" open-type="getUserInfo" @getuserinfo="bindUserInfo">帮TA打call</button>
		        <view class="friends" :style="'background: ' + config.mainColor + '; border-color: ' + config.mainColor" v-if="!info.meta.is_call && info.data.gap_task != 0 && token" @tap="beforCall">帮TA打call</view>
		        <button class="friend share-btn" :style="'color: ' + config.mainColor" v-if="info.meta.is_call && info.data.gap_task != 0" open-type="share">帮TA分享</button>
		        <view class="friends" :style="'background: ' + config.mainColor + '; border-color: ' + config.mainColor" v-if="info.meta.is_call || info.data.gap_task == 0" @tap="jumpCall">我也要领取</view>
		    </view>
		    <view class="no-active" v-if="info.data.free.activity_status == 'NoBegin'">
		        活动未开始
		    </view>
		    <view class="call-num">
		        <view class="text mx-1px-bottom">
		            已有 {{info.data.count_task}} 人为他打Call
		        </view>
		        <view class="item-box">
		            <view class="call-num-item" :style="'height: ' + itemHeight + 'px;'" v-for="(item, index) in callList" :key="index">
		                <view class="info">
		                    <image v-if="item.id && !item.meta.avatar" src="http://ovef29y3v.bkt.clouddn.com/%E5%A4%B4%E5%83%8F_%E7%94%BB%E6%9D%BF%201.png"></image>
		                    <image v-else :src="item.meta.avatar"></image>
		                </view>
		            </view>
		        </view>
		        <view class="text-info mx-1px-top" @tap="infoF">
		            集Call说明
		        </view>
		    </view>
		    <view class="home" @tap="jump">
		        <i class="iconfont icon-home"></i>
		        首页
		    </view>
		    <view class="ibrand-author" v-if="author" @tap="jumpAuthor">
		        <i class="iconfont icon-dibu"></i>
		    </view>
		</view>
		
		<view class="call-goods" v-if="info.data.recommend_goods && info.data.recommend_goods.length">
		    <view class="title mx-1px-bottom">
		        相关推荐
		    </view>
		    <view class="content">
		        <view class="like_list">
		            <view class="like_box" v-for="(item, index) in info.data.recommend_goods" :key="index" :data-id="item.id" @tap="jumpStore">
		                <view>
		                    <view class="like_image">
		                        <image class="responsive" :src="item.img" alt></image>
		                    </view>
		                    <view class="like_name">
		                        {{item.name}}
		                    </view>
		                    <view class="like_money">
		                        ￥{{item.sell_price}}
		                    </view>
		                </view>
		            </view>
		        </view>
		    </view>
		</view>
		
		<view id="coupon-box" v-if="!coupon.has_get && coupon.discount">
		    <view class="mask">
		
		    </view>
		    <view class="coupon-body">
		        <view class="title">
		            优惠券
		        </view>
		        <view class="tips">
		            <view>
		                Hi，亲爱的会员
		            </view>
		            <view>
		                这是我送给你的优惠券，快去领取吧！
		            </view>
		        </view>
		        <view class="coupon" v-for="(item, index) in coupon.discount" :key="index">
		            <view class="left">
		                <view class="icon">
		                    <i class="iconfont icon-xingzhuang"></i>
		                </view>
		                <view class="text-box">
		                    <view class="title nowarp">
		                        {{item.title}}
		                    </view>
		                    <view class="info">
		                        仅支持商城使用
		                    </view>
		                </view>
		            </view>
		            <view class="right">
		                <text class="money" v-if="item.action_type.type == 'cash'">￥</text>
		                <sapn>{{ item.action_type.value }}</sapn>
		
		                <text class="money" v-if="item.action_type.type == 'discount'">折</text>
		            </view>
		        </view>
		
		        <view class="close iconfont icon-yiquxiao" @tap="closeCoupon">
		
		        </view>
		        <view class="btn" v-if="token" @tap="getCoupon">
		            立即领取
		        </view>
		        <button class="btn" v-else open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
		            立即领取
		        </button>
		    </view>
		</view>
	</view>
</template>
<script>
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';
import seckill from "@/components/seckill/seckill";

export default {
  data() {
    return {
      itemHeight: '',
      callList: '',
      info: '',
      init: false,
      task_id: '',
      token: "",
      userInfo: '',
      shop_id: '',
      unionInFo: '',
      openInFo: '',
      author: config.PACKAGES.author,
      list: [{
        id: 1,
        value: 1
      }, {
        id: 2,
        value: 2
      }],
      Brand_name: '',
      config: '',
      coupon: '',
      code: ''
    };
  },

	components:{
		seckill
	},

  onShareAppMessage(res) {
    return {
      title: '快来帮我免费领取|' + this.info.data.free.label,
      imageUrl: this.info.data.free.img,
      path: '/pages/store/shareCall/shareCall?task_id=' + this.info.data.id
    };
  },

  onShow() {
    var token = this.$cookieStorage.get('user_token');
   
	this.token=token;
	 // 用来区分是哪个项目

    /*if(config.BRAND.name == 'nu') {
        this.userAuthorize();
    }*/

    this.queryTaskInfo(this.task_id);

    if (!this.token) {
      this.getOpenid();
    }
  },

  onLoad(e) {
    // 第三方平台配置颜色
    var gbConfig = this.$cookieStorage.get('globalConfig') || '';
    var init = this.$cookieStorage.get('init');
    this.setData({
      config: gbConfig,
      author: init ? init.other_technical_support : ''
    });

    if (!gbConfig) {
      let extConfig = {};

      if (extConfig) {
        this.setData({
          config: extConfig
        });
      }
    }

    wx.getSystemInfo({
      success: res => {
        // this.setData({
        //   itemHeight: (res.screenWidth - 14) / 12.5
        // });
		
		this.itemHeight=(res.screenWidth-14)/12.5;
      }
    });

    if (e.scene) {
      this.setData({
        task_id: decodeURIComponent(e.scene)
      });
    }

    if (e.task_id) {
      this.setData({
        task_id: e.task_id
      });
    }
  },

  components: {
    seckill
  },
  props: {},
  methods: {
    jumpAuthor() {
      wx.navigateTo({
        url: '/pages/index/author/author'
      });
    },

    infoF() {
      wx.showModal({
        title: '集Call说明',
        content: this.info.data.free.content,
        showCancel: false
      });
    },

    jump() {
      wx.switchTab({
        url: '/pages/index/index/index'
      });
    },

    jumpDetail() {
      wx.navigateTo({
        url: '/pages/store/detail/detail?id=' + this.info.data.free.freeable_id
      });
    },

    jumpEnd() {
      wx.redirectTo({
        url: '/pages/store/detail/detail?id=' + this.info.free.freeable_id
      });
    },

    jumpCall() {
      if (this.token) {
        wx.redirectTo({
          url: '/pages/store/call/call?id=' + this.info.data.free_id
        });
      } else {
        wx.showModal({
          content: '请先登录',
          success: res => {
            if (res.confirm || !res.cancel && !res.confirm) {
              pageLogin(getUrl());
            }
          }
        });
      }
    },

    jumpStore(e) {
      var id = e.currentTarget.dataset.id;
      wx.redirectTo({
        url: '/pages/store/detail/detail?id=' + id
      });
    },

    // 查询信息
    queryTaskInfo(id) {
      var token = this.$cookieStorage.get('user_token') || '';
      wx.showLoading({
        title: "加载中",
        mask: true
      });
      this.$http.get({
        api: 'api/free_event/task/getTaskForUser/' + id,
        data: {
          open_id: this.$cookieStorage.get('user_open_id') || ''
        },
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            if (res.meta.is_self) {
              wx.redirectTo({
                url: '/pages/store/call/call?id=' + res.data.free_id
              });
              return;
            }

            var list = Array(res.data.free.per_count - res.data.count_task).fill({
              meta: {
                avatar: ''
              }
            });
            var newList = res.data.items.concat(list);
            this.setData({
              info: res,
              callList: newList // init: true

            });
            /*
             NoBegin 未开始
             OnGoing  进行中
             End 结束
             */
            // 如果活动未开始，不显示转发按钮

            if (res.data.free.activity_status == 'NoBegin') {
              wx.hideShareMenu();
            }
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false,
              success: res => {
                if (res.confirm || !res.cancel && !res.confirm) {
                  wx.redirectTo({
                    url: '/pages/store/callList/callList'
                  });
                }
              }
            });
          }
        } else {
          wx.showModal({
            content: res.message || '请求失败',
            showCancel: false,
            success: res => {
              if (res.confirm || !res.cancel && !res.confirm) {
                wx.redirectTo({
                  url: '/pages/store/callList/callList'
                });
              }
            }
          });
        }

        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
        wx.showModal({
          content: '内部错误',
          showCancel: false,
          success: res => {
            if (res.confirm || !res.cancel && !res.confirm) {
              wx.redirectTo({
                url: '/pages/store/callList/callList'
              });
            }
          }
        });
      });
    },

    beforCall() {
      if (this.token) {
        this.call();
      }
    },

    // 关闭优惠券弹出
    closeCoupon() {
      this.setData({
        'coupon.has_get': true
      });
    },

    // 获取手机号
    getPhoneNumber(e) {
      if (e.detail.encryptedData) {
        wx.login({
          success: res => {
            if (res.code) {
              this.setData({
                code: res.code
              }, res => {
                this.phone(e);
              });
            } else {
              wx.showModal({
                content: " 获取code失败",
                showCancel: false
              });
            }
          }
        });
      }
    },

    // 利用手机号登录
    phone(e) {
      wx.showLoading({
        title: '正在登录',
        mask: true
      });
      this.$http.post({
        api: 'api/oauth/MiniProgramMobileLogin',
        data: {
          open_type: 'miniprogram',
          code: this.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          open_id: this.$cookieStorage.get('user_open_id') || ''
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.access_token) {
            var access_token = res.token_type + ' ' + res.access_token;
            var expires_in = res.expires_in || 315360000;
            this.$cookieStorage.set("user_token", access_token, expires_in); // 领取优惠券

            this.getCoupon();
          } else {
            wx.showModal({
              content: res.message || '请求失败，请重试',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: '请求失败，请重试',
            showCancel: false
          });
        }

        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
        wx.showModal({
          content: '请求失败，请重试',
          showCancel: false
        });
      });
    },

    // 获取优惠券信息
    getCouponInfo() {
      var token = this.$cookieStorage.get('user_token') || '';
      this.$http.get({
        api: 'api/free_event/getCouponList',
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            this.setData({
              coupon: res.data
            });
            console.log(res);
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: '请求失败',
            showCancel: false
          });
        }
      }).catch(err => {
        wx.showModal({
          content: '内部错误',
          showCancel: false
        });
      });
    },

    // 领取优惠券
    getCoupon() {
      wx.showLoading({
        title: '领取中',
        mask: true
      });
      var discount_ids = [];
      this.coupon.discount.forEach(item => {
        discount_ids.push(item.id);
      });
      var token = this.$cookieStorage.get('user_token') || '';
      this.$http.post({
        api: 'api/coupon/getCouponConvertBatch',
        data: {
          discount_ids: discount_ids
        },
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            wx.showModal({
              content: '领取成功',
              showCancel: false
            });
            this.closeCoupon();
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: '请求失败',
            showCancel: false
          });
        }

        wx.hideLoading();
      }).catch(err => {
        wx.hideLoading();
        wx.showModal({
          content: '内部错误',
          showCancel: false
        });
      });
    },

    // 绑定用户信息
    bindUserInfo(e) {
      if (e.detail.encryptedData) {
        this.call(this.open_id, e.detail.userInfo);
      }
    },

    // 打Call
    call(open_id, user_info) {
      var token = this.$cookieStorage.get('user_token');
      wx.showLoading({
        title: "正在打Call",
        mask: true
      });
      this.$http.post({
        api: 'api/free_event/task/call',
        data: {
          task_id: this.task_id,
          open_id: open_id || this.$cookieStorage.get('user_open_id') || '',
          userInfo: user_info
        },
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode = 200) {
          res = res.data;

          if (res.status) {
            this.queryTaskInfo(this.task_id);
            this.getCouponInfo();
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: res.message || '请求失败',
            showCancel: false
          });
        }

        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
        wx.showModal({
          content: '内部错误',
          showCancel: false
        });
      });
    },

    // 获取open_id
    getOpenid() {
      wx.showLoading({
        title: "正在登录",
        mask: true
      });
      wx.login({
        success: res => {
          if (res.code) {
            this.autoLogin(res.code);
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '获取code失败',
              image: '../../../static/error.png'
            });
          }
        }
      });
    },

    // 自动登录
    autoLogin(code) {
      this.$http.post({
        api: 'api/mini/program/login',
        data: {
          code: code
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.access_token) {
            var access_token = res.token_type + ' ' + res.access_token;
            var expires_in = res.expires_in || 315360000;
            this.$cookieStorage.set("user_token", access_token, expires_in); // this.call();
          } else if (res.data && res.data.open_id) {
            this.$cookieStorage.set('user_open_id', res.data.open_id); // this.getUserAuthorize(res.data.open_id)
            // this.call(res.data.open_id)
          } else {
            wx.showModal({
              content: res.message || '获取数据失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: res.message || '获取数据失败',
            showCancel: false
          });
        }

        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
        wx.showModal({
          content: '获取数据失败',
          showCancel: false
        });
      });
    },

    // 获取用户授权
    getUserAuthorize(open_id) {
      wx.getSetting({
        success: res => {
          if (!res.authSetting['scope.userInfo']) {
            wx.authorize({
              scope: 'scope.userInfo',
              success: res => {
                wx.getUserInfo({
                  lang: 'zh_CN',
                  success: res => {
                    this.$cookieStorage.set('Wechat_user_info', res);
                    this.call(open_id, res.userInfo);
                  }
                });
              },
              fail: ret => {
                wx.showModal({
                  content: '需要授权才能完成打Call',
                  showCancel: false,
                  success: res => {
                    if (res.confirm || !res.cancel && !res.confirm) {
                      wx.openSetting({
                        success: res => {
                          if (res.authSetting['scope.userInfo']) {
                            wx.getUserInfo({
                              lang: 'zh_CN',
                              success: ret => {
                                this.$cookieStorage.set('Wechat_user_info', ret);
                                this.call(open_id, ret.userInfo);
                              }
                            });
                          }
                        }
                      });
                    }
                  }
                });
              }
            });
          } else {
            wx.getUserInfo({
              lang: 'zh_CN',
              success: res => {
                this.$cookieStorage.set('Wechat_user_info', res);
                this.call(open_id, res.userInfo);
              }
            });
          }
        }
      });
    },

    // 开始
    isStarts(e) {
      if (this.info.free.activity_status == 'NoBegin') {
        this.queryTaskInfo(this.id);
      }
    },

    // 结束
    isEnd(e) {
      if (this.info.free.activity_status == 'OnGoing') {
        this.jumpEnd();
      }
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style rel="stylesheet/less" lang="less">
    @import "shareCall";
</style>