<template>
	<view class="">
		<view id="call">
		    <view class="call-box" @tap="jumpDetail">
		        <image mode="widthFix" :src="info.free.img?info.free.img:''" alt></image>
		        <view class="name" v-if="info.free.label!=undefined">
		            {{info.free.label}}
		        </view>
		    </view>
		    <view class="time-box" :class="info.free.activity_status == 'OnGoing' ? 'active' : ''" v-if="info.free.activity_status == 'NoBegin'">
		        <seckill :end="info.free.ends_at" :starts="info.free.starts_at" typename="集call" :server="info.free.server_time" mold="list" @starts="isStarts" @end="isEnd"></seckill>
		    </view>
		    <view class="call-user">
		        <image :src="info.task_user_avatar"></image>
		        <view class="call-status">
		            <view v-if="info.gap_task != 0">还差 <span>{{info.gap_task}}</span> 个Call就可以免费领取礼品了，求助攻~</view>
		            <view v-if="info.gap_task == 0 && !info.is_get">您已完成目标可免费领取礼品</view>
		            <view v-if="info.gap_task == 0 && info.is_get">您领取过该礼品</view>
		        </view>
		    </view>
		    <view class="no-active" v-if="info.free.activity_status == 'NoBegin'">
		        活动未开始
		    </view>
		    <view class="no-active get" :style="'background: ' + config.mainColor" v-if="info.gap_task == 0 && !info.is_get" @tap="showSelect">立即领取</view>
		
		    <view class="share-box" v-if="info.free.activity_status == 'OnGoing' && info.gap_task != 0">
		        <button class="friend" :style="'border-color: ' + config.mainColor + '; color: ' + config.mainColor" open-type="share">分享给好友</button>
		        <view class="friends" :style="'background: ' + config.mainColor" @tap="shareImg">生成海报</view>
		    </view>
		    <view class="call-num">
		        <view class="text mx-1px-bottom">
		            已有 {{info.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="info.task_user_avatar"></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="maks" :class="!show_select ? 'cur' : ''" @tap="closeSelect">
		
		</view>
		
		<view class="detail-popup" :hidden="show_select" :animation="show.animation">
		    <view class="select_goods_container">
		        <!--关闭按钮-->
		        <view class="select_goods_cloese" @tap="closeSelect"></view>
		        <view class="select_goods_header">
		
		            <view class="img_box">
		
		                <image v-if="select_product && select_product.img" :src="select_product.img" :alt="select_product.sku"></image>
		                <image v-else :src="commodity.img + ' '" alt></image>
		            </view>
		            <!--<view class="img_box" style="background-color: {{select_product.bac}};width: 78px;height: 78px;"  wx:if="{{!select_product.img && !!select_product.color}}"></view>-->
		            <view class="price_item">
		                <text>￥ {{price}}</text>
		
		                <text v-if="detailData.data.shop_show_store == 1">库存{{store_count}}</text>
		            </view>
		
		        </view>
		
		        <view class="select_spec">
		            <view class="spec_line" v-for="(spec, index) in specs" :key="index">
		                <view class="spec_title">{{spec.label}}</view>
		                <view class="spec_value">
		                    <view class :class=" !!item.disabled ? 'disabled' : '' " v-for="(item, index) in spec.values" :key="index" :data-key="index" :data-index="item.index" :data-disabled="item.disabled ? 1 : 0" :data-id="item.id" :data-active="item.active ? 1 : 0" @tap="selectSpec">
		                        <!--<view class="spec_icon spec_text" wx:if="{{item.spec_img}}">-->
		                        <!--<image src="{{item.spec_img}}" data-alt="{{item.alias || item.value}}"></image>-->
		                        <!--</view>-->
		                        <!--<text class="spec_icon" style="background-color:{{item.color}}" wx:if="{{!item.spec_img && item.color}}"></text>-->
		                        <view class="spec_text" v-if="(item.alias || item.value) && item.spec_img !== undefined">
		                            {{item.alias || item.value}}
		
		                            <view v-if="!!item.active" :style="'border-color: ' + config.mainColor" class="border-color">
		
		                            </view>
		                        </view>
		                        <view class="spec_text" v-if="!item.spec_img && !item.color">
		                            {{item.alias || item.value}}
		
		
		                            <view v-if="!!item.active" :style="'border-color: ' + config.mainColor" class="border-color">
		
		                            </view>
		                        </view>
		                    </view>
		                    <!--<view class="spec_list" wx:if="{{spec.id != 2}}">尺码表</view>-->
		                </view>
		            </view>
		
		            <view class="spec_line">
		                <view class="num_title">数量</view>
		                <view class="num_value">
		                    <!--<text bindtap="changeCount" data-index="0">-</text>-->
		                    <view class="none_border">
		                        <input @input="modifyCount" disabled="true" :value="select_count" type="number" confirm-type="done"></input>
		                    </view>
		                    <!--<text bindtap="changeCount" data-index="1">+</text>-->
		
		                </view>
		                <view class="purchase" v-if="detailData.data.user_limit">
		                    本商品每人限购{{detailData.data.user_limit}}件
		                </view>
		            </view>
		
		            <button class="button disabled" v-if="canBuy" type="primary" :loading="loading" @tap="confirm">确定</button>
		            <button class="button" v-else type="primary" :style="'background: ' + config.mainColor" :loading="loading" @tap="confirmF">确定</button>
		            <!--<view  class="button {{ canBuy ? 'disabled' : '' }}" bindtap="confirm">-->
		
		            <!--&lt;!&ndash;<submit-button v-ref:button bindsubmit="confirm" :status="disallow_cart ? 'disabled' : 'normal'">确定</submit-button>&ndash;&gt;-->
		            <!--</view>-->
		        </view>
		    </view>
		
		</view>
	</view>

</template>
<script>
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';
import Animation from '@/common/js/animation.js';
import seckill from "@/components/seckill/seckill";

export default {
  data() {
    return {
      itemHeight: '',
      callList: '',
      info: {
		  free:''
	  },
      userInfo: '',
      cart_status: {
        status: false,
        message: '商品已下架'
      },
      id: '',
      skuTable: {},
      price: 0,
      commodity: {},
      detailData: {data:''},
      specs: [],
      showToTop: false,
      show_select: true,
      //选尺寸
      select_product: {},
      //当前选中商品
      store_count: 0,
      store_num: 0,
      select_count: 1,
      canBuy: false,
      query: {},
      animationSelect: {},
      loading: false,
      show_cart: false,
      // 加入购物车弹窗
      message: '',
      purchaseInfo: {
        status: false,
        num: 0
      },
      // 限购
      active: false,
      type: 0,
      config: '',
      author: '',
	 animation:'',
	 show:''
    };
  },

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

  onShow() {
    var token = this.$cookieStorage.get('user_token');

    if (token) {
      this.queryTaskInfo(this.id);
    } else {
      pageLogin(getUrl());
    }
  },

  onLoad(e) {
    // 第三方平台配置颜色
    var gbConfig = this.$cookieStorage.get('globalConfig') || '';
    var init = this.$cookieStorage.get('init');
    this.setData({
      config: gbConfig,
      author: init ? init.other_technical_support : ''
    });
    wx.getSystemInfo({
      success: res => {
        // this.setData({
        //   itemHeight: (res.screenWidth - 14) / 12.5
        // });
		this.itemHeight=(res.screenWidth - 14)/12.5;
      }
    });
    this.setData({
      id: e.id
    });
  },

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

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

    shareImg() {
      wx.navigateTo({
        url: '/pages/store/shareImg/shareImg?task_id=' + this.info.id
      });
    },

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

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

    receive() {
      /*wx.showLoading({
      	title: "加载中",
      	mask: true
      });*/
      this.getGoodsDetail({
        api: `api/store/detail/${this.info.free.freeable_id}`,
        data: {
          include: 'photos,oneComment,guessYouLike,point'
        }
      }).then(() => {
        // this.setData({
        //   price: Number(this.commodity.sell_price).toFixed(2),
        //   store_count: this.commodity.store_nums
        // });
		
		 
		  this.price=Number(this.commodity.sell_price).toFixed(2);
		  this.store_count=this.commodity.store_nums;
		
		
        this.disallow_cart();
        this.queryCommodityStore(this.info.free.freeable_id);
      });
    },

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

    changeStatus() {
      var token = this.$cookieStorage.get('user_token');

      if (token) {
        this.changeFavorite(this.id, 'goods');
      } else {
        var url = getUrl();
        wx.showModal({
          title: '',
          content: '请先登录',
          success: res => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/user/register/register?url=' + url
              });
            }
          }
        });
      }
    },

    changeText() {
      var ret;
      var commodity = this.commodity;
      var seckill = this.detailData.meta.seckill;

      if (!commodity) {
        return;
      }

      if (commodity.is_del != 0 || commodity.is_largess != 0) {
        ret = {
          status: false,
          message: '商品已下架'
        };
      } else if (commodity.store_nums <= 0) {
        ret = {
          status: false,
          message: '商品缺货中'
        };
      } else {
        ret = {
          status: true,
          message: '加入购物车'
        };
      }

      if (seckill && seckill.init_status == 2) {
        ret = {
          seckill: false,
          message: '原价购买'
        };
      } else if (seckill && seckill.init_status == 1) {
        ret = {
          seckill: true,
          message: '立即抢购'
        };
      }

      this.setData({
        cart_status: ret
      });
    },

    showSelect(e) {
      this.setData({
        show_select: false
      });
      var animation = new Animation('show');
      animation.positionInit();
    },

    closeSelect() {
      var animation = new Animation('show');
      animation.up().then(() => {
        this.setData({
          show_select: true
        });
      });
    },

    changeCount(e) {
      var select_count = parseInt(this.select_count);
      var index = e.target.dataset.index;
      var val = select_count + (parseInt(index) ? 1 : -1);

      if (val > 0 && val <= parseInt(this.store_count)) {
        this.setData({
          select_count: val
        }); // 用户登录并且开启了限购

        if (this.purchaseInfo.status && this.is_login) {
          if (this.select_count > this.purchaseInfo.num) {
            this.setData({
              select_count: this.select_count - 1
            });
            wx.showToast({
              title: '超过限购数量',
              image: '../../../static/error.png'
            });
          }
        }
      } else if (val <= 0) {
        wx.showToast({
          title: '小于最小库存',
          image: '../../../static/error.png'
        });
      } else if (val > parseInt(this.store_count)) {
        wx.showToast({
          title: '超出最大库存',
          image: '../../../static/error.png'
        });
      }
    },

    modifyCount(e) {
      var val = parseInt(e.detail.value);

      if (!val) {
        val = 1;
      } else if (!/^[1-9]\d*$/.test(val)) {
        val = val.replace(/[^\d].*$/, '');
        val = parseInt(val) || 1;
      }

      if (this.purchaseInfo.status && this.is_login) {
        if (val < 0) {
          val = 1;
        } else if (val > this.purchaseInfo.num) {
          val = this.purchaseInfo.num || 1;
          wx.showToast({
            title: '超过限购数量',
            image: '../../../static/error.png'
          });
        }
      } else {
        if (val < 0) {
          val = 1;
        } else if (val > this.store_count) {
          wx.showToast({
            title: '超过最大库存',
            image: '../../../static/error.png'
          });
          val = parseInt(this.store_count);
        }
      }

      this.setData({
        select_count: val
      });
    },

    showCoupons() {
      this.setData({
        show_coupons: !this.show_coupons
      });
    },

    showDiscounts() {
      this.setData({
        show_discounts: !this.show_discounts
      });
    },

    getCoupon(e) {
      var is_login = this.$cookieStorage.get('user_token');
      var code = e.currentTarget.dataset.code;
      var index = e.currentTarget.dataset.index;

      if (is_login) {
        this.goodsConvertCoupon(code, index);
      } else {
        var url = getUrl();
        wx.showModal({
          tiele: '',
          content: '请先登录',
          success: res => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/user/register/register?url=' + url
              });
            }
          }
        });
      }
    },

    selectSpec(e) {
      var spec = {
        key: e.currentTarget.dataset.key,
        index: e.currentTarget.dataset.index,
        disabled: Number(e.currentTarget.dataset.disabled),
        active: Number(e.currentTarget.dataset.active),
        id: Number(e.currentTarget.dataset.id)
      };
      if (spec.disabled) return;
      var specs = this.specs;

      if (!spec.active) {
        for (let item of specs[spec.index].values) {
          if (item.active) {
            item.active = false;
            break;
          }
        }
      }

      specs[spec.index].values[spec.key].active = !specs[spec.index].values[spec.key].active;
      spec.active = !spec.active;
      specs[spec.index].select = spec.active ? spec.id : '';
      this.setData({
        specs: specs
      });
      var canBuy = this.disallow_cart();
      this.setData({
        canBuy: canBuy
      }); // this.queryCommodityStore(id, spec.index);

      this.specStore(this.result, spec.index);
    },

    specStore(result, key) {
      var query = this.query;
      var data = result.data;
      var specs = this.specs;

      if (key === undefined) {
        specs.forEach(spec => {
          for (let v of spec.values) {
            v.disabled = !data[v.id] || data[v.id].count == 0;
          }
        });
        this.setData({
          specs: specs,
          skuTable: result.table
        });
        specs = this.specs;
        var canBuy = this.disallow_cart();
        this.setData({
          canBuy: canBuy
        });
        specs.forEach(spec => {
          let name = 'spec[' + spec.id + ']';

          if (query[name]) {
            let id = query[name];

            for (let v of spec.values) {
              if (v.id == id && !v.disabled && data[v.id] && data[v.id].count) {
                v.active = true;
                spec.select = v.id;
                this.setData({
                  specs: specs
                });
                specs = this.specs;
                var canBuy = this.disallow_cart();
                this.setData({
                  canBuy: canBuy
                });
                this.specStore(result, v.index);
                return;
              }
            }
          }

          if (!spec.select) {
            for (let v of spec.values) {
              if (!v.disabled && data[v.id] && data[v.id].count) {
                v.active = true;
                spec.select = v.id;
                this.setData({
                  specs: specs
                });
                specs = this.specs;
                var canBuy = this.disallow_cart();
                this.setData({
                  canBuy: canBuy
                }); // this.$emit('specStore', result, v.index);

                this.specStore(result, v.index);
                return;
              }
            }

            return;
          }

          this.setData({
            specs: specs
          });
        });
        return;
      }

      var spec = specs[key];

      if (spec.select) {
        // this.setData({
        //   store_count: data[spec.select].count
        // });
		
		this.store_count=data[spec.select].count;

        for (let i = 0; i < specs.length; i++) {
          if (i === key) continue;
          specs[i].values.forEach(v => {
            v.disabled = !data[spec.select].specs[v.id].count;
          });

          if (specs[i].select) {
            // this.setData({
            //   store_count: data[spec.select].specs[specs[i].select].count
            // });
		
			 this.store_count=data[spec.select].specs[specs[i].select].count;
		
			
          }

          this.setData({
            specs: specs
          });
        }
      } else {
        this.setData({
          store_count: this.commodity.store
        });

        for (let i = 0; i < specs.length; i++) {
          if (i === key) continue;
          specs[i].values.forEach(v => {
            v.disabled = !data[v.id] || !data[v.id].count;
          });

          if (specs[i].select) {
   //          this.setData({
   //            store_count: data[specs[i].select].count
   //          });
			// 
			
			this.store_count=data[specs[i].select].count;
			
          }

          this.setData({
            specs: specs
          });
          console.log(specs);
        }
      }

      if (parseInt(this.select_count) > this.store_count) {
        this.setData({
          select_count: String(this.store_count)
        });
      } else if (parseInt(this.select_count) === 0) {
        this.setData({
          select_count: '1'
        });
      }

      this.setData({
        specs: specs
      });
      var canBuy = this.disallow_cart();
      this.setData({
        canBuy: canBuy
      });
    },

    confirmF() {
      if (this.loading) return;
      if (this.disallow_cart()) return;
      this.setData({
        loading: true
      });
      var select_product = this.select_product;
      var select_count = Number(this.select_count);
      var data = this.specs.length ? {
        id: select_product.id,
        name: this.commodity.name,
        qty: select_count,
        store_count: this.store_count,
        price: select_product.price,
        attributes: {
          img: select_product.img || this.detailData.data.photos[0].url,
          size: select_product.size,
          color: select_product.color,
          com_id: this.commodity.id
        }
      } : {
        id: this.commodity.id,
        name: this.commodity.name,
        qty: select_count,
        store_count: this.store_count,
        price: this.commodity.price,
        attributes: {
          img: this.commodity.img || this.detailData.data.photos[0].url,
          com_id: this.commodity.id
        }
      }; // if (this.channel) data.attributes.channel = 'employee';

      if (select_product.sku) data.attributes.sku = select_product.sku; //      秒杀开始添加信息

      if (this.detailData.meta.seckill && this.detailData.meta.seckill.init_status == 1) {
        var newData = {};
        newData.attributes = {};
        newData.id = data.id;
        newData.img = data.attributes.img || this.detailData.data.photos[0].url;
        newData.name = data.name;
        newData.price = data.price;
        newData.qty = data.qty;
        newData.total = data.qty * data.price;
        newData.seckill_goods_id = this.detailData.meta.seckill.item_id;
        newData.seckill_item_id = this.detailData.meta.seckill.id;
        newData.attributes['dynamic_sku'] = {};
        newData.attributes['dynamic_sku'].id = data.id;
        newData.attributes['dynamic_sku'].size = data.attributes.size;
        newData.attributes['dynamic_sku'].color = data.attributes.color;
      } // 判断是否登录
      // var is_login = !!Cache.get(cache_keys.token);
      // 判断是否参与秒杀并且秒杀开始


      if (this.detailData.meta.seckill && this.detailData.meta.seckill.init_status == 1) {
        if (!this.is_login) {
          var url = getUrl();
          wx.showModal({
            content: '请先登录',
            success: res => {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/user/register/register?url=' + url
                });
              }
            }
          });
        } else {
          this.checkoutSeckillOrder(newData);
        }
      } else {
        if (this.is_login) {
          this.appendToCart(data);
          this.addStoreNum();
        } else {
          data.local = true;
          data.total = Number(data.qty) * Number(data.price);
          data.color = data.attributes.color;
          data.size = data.attributes.size;
          data.img = data.attributes.img;
          var locals = this.$cookieStorage.get('cart') || [];
          locals.unshift(data);
          var skus = {};
          var save = [];
          locals.forEach(v => {
            let sku, index;

            if (v.attributes && v.attributes.sku) {
              sku = v.attributes.sku;
            } else {
              sku = v.id;
            }

            if (skus[sku] === undefined) {
              index = save.length;
              v.index = index;
              v.checked = true;
              save.push(v);
              skus[sku] = index;
            } else {
              let i = skus[sku];
              save[i].qty += v.qty;
              save[i].total += v.total;
              save[i].store_count = this.store_count;
            }
          });
          console.log(skus, save);
          this.$cookieStorage.set('cart', save);
          this.setData({
            store_num: 0
          });
          this.addStoreNum();
          this.addCart(true);
        }
      }
    },

    addStoreNum() {
      // 判断是否登录
      // var is_login = !!Cache.get(cache_keys.token);
      // var cache_store_num = Cache.get(cache_keys.cart);
      var cache_store_num = this.$cookieStorage.get('cart');

      if (this.is_login) {
        this.queryShoppingCount();
      } else {
        if (cache_store_num && cache_store_num.length) {
          var store_num = this.store_num;
          cache_store_num.forEach(v => {
            store_num += v.qty;
          });
          this.setData({
            store_num: store_num
          });
        }
      }
    },

    disallow_cart() {
      if (!this.specs.length) {
        return !this.store_count;
      }

      var ids = [],
          select_product = {},
          specs = this.specs;
      console.log(this.commodity.sell_price);
      this.setData({
        price: Number(this.commodity.sell_price).toFixed(2)
      });

      for (let spec of specs) {
        if (!spec.select) {
          this.setData({
            price: Number(this.commodity.sell_price).toFixed(2),
            select_product: null
          });
          return true;
        }

        ids.push(spec.select);

        for (let v of spec.values) {
          if (v.id === spec.select) {
            switch (spec.label_key) {
              case 'color':
                select_product.img = v.img;
                select_product.color = v.alias || v.value;
                select_product.bac = v.color;
                break;

              default:
                select_product.size = v.alias || v.value;
            }

            break;
          }
        }
      }

      if (this.skuTable) {
        ids = ids[0] > ids[1] ? [ids[1], ids[0]] : ids;
        ids = ids.join('-');
        select_product = Object.assign(select_product, this.skuTable[ids]);
      }

      console.log(ids);
      console.warn(this.skuTable);
      console.warn(this.skuTable[ids]);
      console.log(select_product.price);
      this.setData({
        price: Number(select_product.price).toFixed(2),
        select_product: select_product
      });
      return false;
    },

    attributesList(meta) {
      var topList = [];
      var bottomList = [];

      if (meta && meta.attributes) {
        var attributes = meta.attributes;

        for (var item of attributes) {
          if (item.is_chart === 1) {
            bottomList.push(item);
          } else {
            topList.push(item);
          }
        }
      }

      this.setData({
        'attributesList.top': topList,
        'attributesList.bottom': bottomList
      });
    },

    // 重要！！！！
    move() {},

    goCart() {
      wx.switchTab({
        url: '/pages/store/cart/cart'
      });
      this.changeCart();
    },

    changeCart() {
      this.setData({
        show_cart: !this.show_cart
      });
    },

    queryCommodityStore(id, key) {
      var that = this;
      this.$http.get({
        api: `api/store/detail/${id}/stock`
      }).then(res => {
        wx.hideLoading();
        res = res.data;
        if (!res.status || !res.data || !res.data.specs) return;

        if (res.data.specs && typeof key === 'undefined') {
          let specs = [];
          Object.keys(res.data.specs).forEach((key, index) => {
            let value = res.data.specs[key];
            value.select = '';
            value.values = value.list.map(v => {
              return Object.assign({
                index: index,
                active: false,
                disabled: false
              }, v);
            });
            delete value.list;
            specs.push(value);
          });
          that.setData({
            specs: specs
          });
          console.log(specs);
          var canBuy = this.disallow_cart();
          this.setData({
            canBuy: canBuy
          });
        }

        if (res.data.stores) {
          let data = {};
          Object.keys(res.data.stores).forEach(key => {
            let value = res.data.stores[key];
            value.ids.forEach(id => {
              data[id] = data[id] || {
                count: 0,
                specs: {}
              };
              data[id].count += Number(value.store);
              value.ids.forEach(i => {
                if (i === id) return;
                data[id].specs[i] = {
                  count: Number(value.store)
                };
              });
            });
          }); // console.log(data);

          var result = {
            data,
            table: res.data.stores
          };
          this.setData({
            result: result
          });
          that.specStore(result, key); // this.$emit('specStore', result, key);
        }
      }).catch(err => {});
    },

    appendToCart(data) {
      if (!Array.isArray(data)) {
        data = [data];
      }

      var oauth = this.is_login;
      var json = {};
      data.forEach((v, i) => json[i] = v);
      data = json;
      var that = this;
      this.$http.post({
        api: 'api/shopping/cart',
        header: {
          Authorization: oauth
        },
        data: data
      }).then(res => {
        res = res.data;

        if (res.status) {
          that.addCart(true);
        } else {
          that.addCart(false, res.message);
        }
      }).catch(rej => {
        that.addCart(false);
      });
    },

    addCart(success, message) {
      // this.$refs.button.finish();
      this.setData({
        loading: false
      });

      if (success) {
        this.closeSelect();
        this.changeCart(); // wx.showModal({
        //     content: '商品成功加入购物车！',
        //     cancelText: '进购物车',
        //     confirmText: '继续购物',
        //     success: function (res) {
        //         if (res.confirm) {
        //            console.log('用户点击取消')
        //         } else if (res.cancel) {
        //            wx.navigateTo({
        //                url: '/pages/store/cart/cart'
        //            })
        //         }
        //     },
        //     fail: function () {
        //         wx.showToast({
        //             title: '添加失败',
        //             image: '../../../static/error.png',
        //         })
        //     }
        // })
        // if (typeof window.__analytics == 'function') {
        //     console.log('11212132323')
        //     var cart = {
        //         action :'add to cart',
        //         product:{
        //             sku: this.$brand.name == 'JackWolfskin' ? this.select_product.id :this.select_product.sku,
        //             title: this.commodity.name,
        //             category: this.commodity.tags,
        //             quantity: this.store_count
        //         }
        //     }
        //
        //     window.__analytics({cart})
        // }
      } else {
        if (message) {
          wx.showToast({
            title: message
          });
        } else {
          wx.showToast({
            title: '添加到购物车失败，请重试'
          });
        }
      }
    },

    getGoodsDetail(obj) {
      var that = this;
      return new Promise((resolve, reject) => {
        this.$http.get(obj).then(res => {
          console.log(res);
          res = res.data;
          that.setData({
            detailData: res,
            commodity: res.data
          });

          if (res.meta.seckill) {
            var interval = setInterval(this.countStartsTime, 1000);
            that.setData({
              'startsTime.interval': interval
            });
          }

          if (res.meta.discounts) {
            res.meta.discounts.coupons.forEach(v => v.receive = false);
            that.setData({
              coupons: res.meta.discounts.coupons,
              discounts: res.meta.discounts.discounts
            });
          }

          resolve();
        }).catch(err => {
          console.log(err);
          reject();
        });
      });
    },

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

          if (res.status) {
            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.data,
              callList: newList
            });
            /*
             NoBegin 未开始
             OnGoing  进行中
            End 结束
            */
            // 如果活动未开始，不显示转发按钮

            if (res.data.free.activity_status == 'NoBegin') {
              wx.hideShareMenu();
            }

            if (res.data.gap_task == 0 && !res.data.is_get) {
              this.receive();
            } else {
              wx.hideLoading();
            }
          } else {
            wx.hideLoading();
            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.hideLoading();
          wx.showModal({
            content: res.message || '请求失败',
            showCancel: false,
            success: res => {
              if (res.confirm || !res.cancel && !res.confirm) {
                wx.redirectTo({
                  url: '/pages/store/callList/callList'
                });
              }
            }
          });
        }
      }).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'
              });
            }
          }
        });
      });
    },

    // 点击确定
    confirm() {
      if (this.loading) return;
      if (this.disallow_cart()) return;
      this.setData({
        loading: true
      });
      var select_product = this.select_product;
      var select_count = Number(this.select_count);
      var data = this.specs.length ? {
        id: select_product.id,
        name: this.commodity.name,
        qty: select_count,
        store_count: this.store_count,
        price: select_product.price,
        market_price: this.commodity.market_price,
        attributes: {
          img: select_product.img || this.detailData.data.photos[0].url,
          size: select_product.size,
          color: select_product.color,
          com_id: this.commodity.id
        }
      } : {
        id: this.commodity.id,
        name: this.commodity.name,
        qty: select_count,
        store_count: this.store_count,
        price: this.commodity.sell_price,
        market_price: this.commodity.market_price,
        attributes: {
          img: this.commodity.img || this.detailData.data.photos[0].url,
          com_id: this.commodity.id
        }
      };
      var newData = {};
      newData.attributes = {};
      newData.id = data.id;
      newData.img = data.attributes.img || this.detailData.data.photos[0].url;
      newData.name = data.name;
      newData.price = data.price;
      newData.qty = data.qty;
      newData.total = data.qty * data.price;
      newData.free_id = this.info.free_id;
      newData.task_id = this.info.id;

      if (this.specs.length) {
        newData.attributes['dynamic_sku'] = {};
        newData.attributes['dynamic_sku'].id = data.id;
        newData.attributes['dynamic_sku'].size = data.attributes.size;
        newData.attributes['dynamic_sku'].color = data.attributes.color;
      } // if (this.channel) data.attributes.channel = 'employee';


      if (select_product.sku) data.attributes.sku = select_product.sku; // 关闭弹出层

      this.closeSelect();
      this.checkoutFreeOrder(newData); //      秒杀开始添加信息

      /*if (this.detailData.meta.seckill && this.detailData.meta.seckill.init_status == 1) {
      	var newData = {};
      	newData.attributes={};
      	newData.id = data.id;
      	newData.img = data.attributes.img || this.detailData.data.photos[0].url;
      	newData.name = data.name;
      	newData.price = data.price;
      	newData.qty = data.qty;
      	newData.total = data.qty * data.price;
      	newData.seckill_goods_id = this.detailData.meta.seckill.item_id;
      	newData.seckill_item_id = this.detailData.meta.seckill.id;
      	newData.attributes['dynamic_sku'] = {};
      	newData.attributes['dynamic_sku'].id = data.id;
      	newData.attributes['dynamic_sku'].size = data.attributes.size;
      	newData.attributes['dynamic_sku'].color = data.attributes.color;
      }*/
      // 判断是否登录
      // var is_login = !!Cache.get(cache_keys.token);
      // 判断是否参与秒杀并且秒杀开始

      /*if (this.detailData.meta.seckill && this.detailData.meta.seckill.init_status == 1) {
      	if (!this.is_login) {
      		var url = getUrl();
      		wx.showModal({
      			content: '请先登录',
      			success: res => {
      				if (res.confirm) {
      					wx.navigateTo({
      						url: '/pages/user/register/register?url=' + url
      					})
      				}
      			}
      		})
      	} else {
      		this.checkoutSeckillOrder(newData);
      	}
      } else {
      	if (this.is_login) {
      		this.appendToCart(data);
      		this.addStoreNum();
      	} else {
      		data.local = true;
      		data.total = Number(data.qty) * Number(data.price);
      		data.color = data.attributes.color;
      		data.size = data.attributes.size;
      		data.img = data.attributes.img;
      			var locals = this.$cookieStorage.get('cart') || [];
      		locals.unshift(data);
      			var skus = {};
      		var save = [];
      		locals.forEach(v => {
      			let sku, index;
      			if (v.attributes && v.attributes.sku) {
      				sku = v.attributes.sku;
      			} else {
      				sku = v.id;
      			}
      				if (skus[sku] === undefined) {
      				index = save.length;
      				v.index = index;
      				v.checked = true;
      				save.push(v);
      				skus[sku] = index;
      				} else {
      				let i = skus[sku];
      				save[i].qty += v.qty;
      				save[i].total += v.total;
      				save[i].store_count = this.store_count;
      				}
      		});
      		console.log(skus, save)
      			this.$cookieStorage.set('cart', save);
      			this.setData({
      			store_num: 0
      		})
      		this.addStoreNum();
      		this.addCart(true)
      	}
      }*/
    },

    // 订单结算
    checkoutFreeOrder(data) {
      console.log(data);
      var token = this.$cookieStorage.get('user_token');
      this.$http.post({
        api: 'api/shopping/order/checkout?free_id=' + data.free_id,
        header: {
          Authorization: token
        },
        data: data
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            this.$cookieStorage.set('local_order', res.data);
            this.setData({
              loading: false
            });
            wx.navigateTo({
              url: '/pages/store/order/order?type=free&task_id=' + data.task_id
            });
          } else {
            if (res.data && res.data.server_busy) {
              this.setData({
                show_ten: true
              });
            } else if (res.message == 'User unbind mobile') {
              wx.showModal({
                content: '请先绑定手机号',
                showCancel: false,
                success: res => {
                  if (res.confirm || !res.cancel && !res.confirm) {
                    wx.navigateTo({
                      url: '/pages/user/phone/phone?url=' + getUrl()
                    });
                  }
                }
              });
            } else {
              wx.showModal({
                content: res.message || '请求失败',
                showCancel: false
              });
            }

            this.setData({
              loading: false
            });
          }
        } else {
          wx.showModal({
            content: '请求失败',
            showCancel: false
          });
          this.setData({
            loading: false
          });
        }
      });
    },

    // 开始
    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 "call";
</style>