<template>
<view class="">
	<view class="content">
	    <view class="top-image">
	        <swiper indicator-dots="true" autoplay="true" circular="true">
	            <swiper-item v-for="(item, index) in detailData.data.photos" :key="index">
	                <image :src="item.url"  :data-url="item.url" class="slide-image" @tap="bigImg"></image>
	            </swiper-item>
	        </swiper>
	    </view>
	    <view class="basic-information">
	
	        <view class="basic-top">
	            {{detailData.data.name}}
	        </view>
	
	        <view class="basic-bottom">
	            <text class="price">{{detailData.data.redeem_point}} 积分</text>
	        </view>
	
	    </view>
	    <view class="detail-item-box">
	
	        <!--商品详情-->
	        <view>
	            <view class="title mx-1px-bottom" data-type="commodity" @tap="change">
	                <view class="title-text">
	                    图文详情
	                </view>
	                <view>
	
	                </view>
	            </view>
	            <view class="content" v-if="expands.commodity">
	                <!--<wxparser rich-text="{{detailData.data.content}}" />-->
					
					<u-parse :content="detailData.data.content"  v-if="detailData.data.content" />
         
	            </view>
	        </view>
	    </view>
	    <!--<view class="to-top" hidden="{{!showToTop}}" bindtap="goTop">-->
	        <!--<i class="iconfont icon-xiangshang"></i>-->
	    <!--</view>-->
	
	    <view class="tabbar">
	        <view class="tabbar-item item_3" :class="cart_status.status ? 'globalBgcolor' : 'btn_1'" :style="'background: ' + config.mainColor" @tap="showSelect">
	            {{cart_status.message}}
	        </view>
	    </view>
	</view>
	<view class="maks" :class="!show_select ? 'cur' : ''" @tap="closeSelect">
	
	</view>
	
	<view class="detail-popup" :class="!show_select ? 'detail-active' : ''" :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>{{detailData.data.redeem_point}} 积分</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="spec_block" :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 !== ''">
	                            {{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 @tap="changeCount" data-index="0">-</text>
	                    <view class="none_border">
	                        <input @input="modifyCount" :value="select_count" type="number" confirm-type="done"></input>
	                    </view>
	                    <text @tap="changeCount" data-index="1">+</text>
	
	                </view>
	            </view>
	
	            <button class="button" :class=" canBuy ? 'disabled' : '' " :loading="loading" :style="'background: ' + config.mainColor" @tap="confirm">确定</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>
var app = getApp();
//import { config, getUrl, weapp, cookieStorage, connect, bindActionCreators, store, actions, sandBox } from '../../../lib/myapp.js';
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';
import Animation from '@/common/js/animation.js';
import uParse from '@/components/gaoyia-parse/parse.vue';
import ten from "@/components/ten/ten";


export default {
  data() {
    return {
      cart_status: {
        status: false,
        message: '商品缺货中'
      },
      id: '',
      skuTable: {},
      price: 0,
      commodity: {},
      detailData: {},
      specs: [],
      detail: '',
      attributesList: {
        top: [],
        bottom: []
      },
      expands: {
        parameter: true,
        //商品参数
        recommend: true,
        //推荐搭配
        commodity: true,
        //商品详情
        story: true,
        //产品故事
        interest: true,
        //TA们也感兴趣
        like: true,
        //猜你喜欢
        history: true //历史浏览

      },
      showToTop: false,
      show_select: true,
      //选尺寸
      select_product: {},
      //当前选中商品
      store_count: 0,
      store_num: 0,
      select_count: 1,
      is_login: true,
      canBuy: false,
      query: {},
      animationSelect: {},
      loading: false,
      coupons: [],
      // 可领取的优惠券信息
      discounts: [],
      // 可享受的优惠折扣信息
      show_coupons: false,
      // 领取优惠券
      show_discounts: false,
      // 查看促销活动
      show_cart: false,
      // 加入购物车弹窗
      message: '',
      purchaseInfo: {
        status: false,
        num: 0
      },
      // 限购
      active: false,
      type: 0,
      endTime: {
        interval: '',
        day: 0,
        hour: 0,
        minute: 0,
        second: 0,
        count: 0
      },
      startsTime: {
        interval: '',
        day: 0,
        hour: 0,
        minute: 0,
        second: 0,
        count: 0
      },
      show_ten: false,
      // 网络繁忙弹窗
      config: '',
	  animation:'',
	  show:''
    };
  },

    components: {
        ten,
        uParse
    },

  onLoad(e) {
    // 第三方平台配置颜色
    var gbConfig = this.$cookieStorage.get('globalConfig') || '';
    this.setData({
      config: gbConfig
    });
    wx.showLoading({
      title: "加载中",
      mask: true
    });
    if (!e.id) wx.redirectTo({
      url: '/pages/store/list/list'
    });
    var is_login = this.$cookieStorage.get('user_token');
    this.setData({
      id: e.id,
      query: e,
      is_login: is_login
    }); // this.queryDiscounts(e.id);

    this.getGoodsDetail({
      api: `api/store/detail/${e.id}`,
      data: {
        include: 'photos,oneComment,guessYouLike,point'
      }
    }).then(() => {
      console.log(this.commodity);
      this.attributesListF(this.detailData.meta);
      wx.setNavigationBarTitle({
        title: this.detailData.data.name
      });
      this.setData({
        price: Number(this.commodity.sell_price).toFixed(2),
        store_count: this.commodity.store_nums
      });
      this.changeText();
      this.disallow_cart();
      this.queryCommodityStore(e.id);
      this.queryFavoriteStatus(e.id, 'goods');
    }); // 用户登录后请求限购接口

    if (this.is_login) {
      this.goodsPurchase(this.id);
    }
  },

  onShareAppMessage(res) {
    return {
      title: this.commodity.name,
      // path: '/' + this.router + '?id=' + this.id,
      path: `/${this.route}?id=${this.id}`,
      imageUrl: this.commodity.img,
      success: function (res) {
        wx.showModal({
          content: '转发成功',
          showCancel: false
        });
      },
      fail: function (res) {
        wx.showModal({
          content: '转发取消',
          showCancel: false
        });
      }
    };
  },

  props: {},
  methods: {
    changeStatus() {
      var token = this.$cookieStorage.get('user_token');

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

    // 网络繁忙倒计时
    HideTen() {
      this.setData({
        show_ten: false
      });
    },

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

      if (!commodity) {
        return;
      }

      if (commodity.is_del != 0) {
        ret = {
          status: false,
          message: '商品已下架'
        };
      } else if (commodity.store_nums <= 0) {
        ret = {
          status: false,
          message: '商品缺货中'
        };
      } else {
        ret = {
          status: true,
          message: '立即兑换'
        };
      }

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

    //    		活动开始的倒计时
    countTime() {
      var d = 86400000,
          h = 3600000,
          n = 60000,
          end = this.detailData.meta.seckill.ends_at,
          server = this.detailData.meta.seckill.server_time,
          arr = String(end).split(/\D/),
          newArr = String(server).split(/\D/);
      newArr = newArr.map(Number);
      arr = arr.map(Number);
      var serverTime = new Date(newArr[0], newArr[1] - 1, newArr[2], newArr[3], newArr[4], newArr[5]).getTime(); //		        var nowTime = new Date().getTime();

      var endTime = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]).getTime(); //		        组件才秒杀列表页使用时，没有重新请求列表，服务器时间应该加上未开始倒计时的时间

      if (this.mold == 'list') {
        serverTime = serverTime + this.startsTime.count;
      } //		        计算开始时间跟结束时间的差值


      var timeDiff = endTime - serverTime; //		        在本地计算倒计时

      var allTime = this.endTime.count + 1000;
      this.setData({
        'endTime.count': allTime
      }); // this.endTime.count += 1000;

      var interval = timeDiff - this.endTime.count;

      if (interval < 0) {
        //		        	活动结束
        this.isEnd(); // 			this.$emit('end',this.index)
      } else {
        var day = Math.floor(interval / d);
        Math.floor(interval -= day * d);
        var hour = Math.floor(interval / h);
        Math.floor(interval -= hour * h);
        var minute = Math.floor(interval / n);
        var second = Math.floor(interval % n / 1000);
        this.setData({
          'endTime.day': day,
          'endTime.hour': hour,
          'endTime.minute': minute,
          'endTime.second': second
        }); // this.endTime.day = day;
        // this.endTime.hour = hour;
        // this.endTime.minute = minute;
        // this.endTime.second = second;
      }
    },

    //            活动未开始的倒计时
    countStartsTime() {
      var d = 86400000,
          h = 3600000,
          n = 60000,
          sta = this.detailData.meta.seckill.starts_at,
          server = this.detailData.meta.seckill.server_time,
          arr = String(sta).split(/\D/),
          newArr = String(server).split(/\D/);
      newArr = newArr.map(Number);
      arr = arr.map(Number);
      var serverTime = new Date(newArr[0], newArr[1] - 1, newArr[2], newArr[3], newArr[4], newArr[5]).getTime();
      var staTime = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]).getTime();
      var timeDiff = staTime - serverTime;
      var allTime = this.startsTime.count + 1000;
      this.setData({
        'startsTime.count': allTime
      }); // this.startsTime.count += 1000;

      var interval = timeDiff - this.startsTime.count; //		        var interval = staTime - nowTime;
      //		        时间差小于一天

      if (interval < d) {
        this.setData({
          type: 1
        });

        if (interval < 0) {
          //			        	代表活动已经开始了，需要执行活动开始倒计时
          var interval = setInterval(this.countTime, 1000);
          this.setData({
            active: true,
            'endTime.interval': interval
          });
          this.isStarts(); // this.active = true;
          //			        	this.startsTime.count = -(this.startsTime.count - 1000)
          // 				this.$emit('starts',this.index);
          // this. = setInterval(this.countTime,1000);
          //                        清除掉倒计时,以免重复分发事件

          clearInterval(this.startsTime.interval);
        } else {
          var day = Math.floor(interval / d);
          Math.floor(interval -= day * d);
          var hour = Math.floor(interval / h);
          Math.floor(interval -= hour * h);
          var minute = Math.floor(interval / n);
          var second = Math.floor(interval % n / 1000);
          this.setData({
            'startsTime.day': day,
            'startsTime.hour': hour,
            'startsTime.minute': minute,
            'startsTime.second': second
          }); // this.startsTime.day = day;
          // this.startsTime.hour = hour;
          // this.startsTime.minute = minute;
          // this.startsTime.second = second;
        }
      } else {
        this.setData({
          message: `${arr[1]} 月 ${arr[2]} 日，${arr[3]} : ${arr[4]} 开始`
        }); // this.message = `${arr[1] - 1} 月 ${arr[2]} 日，${arr[3]} : ${arr[4]} 开始`
      }
    },

    // 秒杀结束执行
    isEnd() {
      if (this.detailData.meta.seckill) {
        var id = this.id;
        this.getGoodsDetail({
          api: `api/store/detail/${id}`,
          data: {
            include: 'photos,products,oneComment,guessYouLike,whoLike,point'
          }
        });
        this.queryCommodityStore(id);
      }
    },

    isStarts() {
      if (this.detailData.meta.seckill.init_status == 2) {
        var id = this.id;
        this.getGoodsDetail({
          api: `api/store/detail/${id}`,
          data: {
            include: 'photos,products,oneComment,guessYouLike,whoLike,point'
          }
        });
        this.queryCommodityStore(id);
      }
    },

    // onStateChange(nextState){
    //     console.log(nextState)
    //     if (!app.isEmptyObject(nextState.detailData)) {
    //         Wxparse.wxParse('detailI', 'html', nextState.detailData.data.content, this, 0);
    //         this.attributesListF(nextState.detailData.meta);
    //         wx.setNavigationBarTitle({
    //             title: nextState.detailData.data.name
    //         })
    //         this.setData({
    //             detailData: nextState.detailData,
    //             commodity: nextState.detailData.data
    //         })
    //         wx.hideLoading()
    //     }
    //
    //     // if (nextState.commoditySpec.length > 0 ) {
    //     //
    //     //     this.setData({
    //     //         specs:nextState.commoditySpec
    //     //     })
    //     // }
    //     //
    //     // if (!app.isEmptyObject(nextState.resultStore)) {
    //     //     this.specStore(nextState.resultStore,nextState.resultStore.key)
    //     //
    //
    //     // }
    //
    // },
    change(e) {
      var expands = this.expands[e.currentTarget.dataset.type];
      this.setData({
        [`expands.${e.currentTarget.dataset.type}`]: !expands
      });
    },

    showSelect(e) {
      this.setData({
        show_select: false
      });
	  
	  // #ifdef MP-WEIXIN
	  var animation = new Animation('show');
	  animation.positionInit();
	  // #endif
    },

    closeSelect() {
		
		// #ifdef MP-WEIXIN
		var animation = new Animation('show');
		animation.up().then(() => {
		  this.setData({
		    show_select: true
		  });
		});
		// #endif
		
		
		// #ifdef H5 || APP-PLUS
		this.show_select=true
		// #endif
		
      
    },

    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
        });

        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.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.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
      });
    },

    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
        }
      }; // if (this.channel) data.attributes.channel = 'employee';

      if (select_product.sku) data.attributes.sku = select_product.sku; // 判断是否登录
      // var is_login = !!Cache.get(cache_keys.token);

      var datas = {
        product_id: select_product.id,
        quantity: select_count
      };

      if (!select_product.id) {
        datas.goods_id = this.id;
      }

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

      if (!token) {
        this.setData({
          loading: false
        });
        wx.showModal({
          content: '请先登录',
          showCancel: false,
          success: res => {
            if (res.confirm || !res.cancel && !res.confirm) {
              wx.navigateTo({
                url: '/pages/user/register/register?url=' + getUrl()
              });
            }
          }
        });
      } else {
        this.pointSore(datas);
      }
    },

    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]);
      }

      this.setData({
        price: Number(select_product.price).toFixed(2),
        select_product: select_product
      });
      return false;
    },

    attributesListF(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
      });
    },

    jump(e) {
      if (e.currentTarget.dataset.type == 'shop') {
        wx.switchTab({
          url: '/pages/index/index/index'
        });
      } else if (e.currentTarget.dataset.type == 'cart') {
        wx.switchTab({
          url: '/pages/store/cart/cart'
        });
      } else {
        wx.navigateTo({
          url: '/pages/store/detail/detail?id=' + e.currentTarget.dataset.id
        });
      }
    },

    jumpToDetail(e) {
      var id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: `/pages/store/detail/detail?id=${id}`
      });
    },

    jumpMeal(e) {
      var id = e.currentTarget.dataset.suitid;
      wx.navigateTo({
        url: `/pages/store/meal/meal?id=${id}`
      });
    },

    bigImg(e) {
      var srcList = [];
      var src = e.currentTarget.dataset.url;
      this.detailData.data.photos.forEach(i => {
        srcList.push(i.url);
      });

      if (src && srcList.length) {
        wx.previewImage({
          current: src,
          urls: srcList
        });
      }
    },

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

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

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

    // 查询是否收藏改商品
    queryFavoriteStatus(id, type) {
      var token = this.$cookieStorage.get('user_token');
      if (!token) return;
      this.$http.get({
        api: 'api/favorite/isfav',
        header: {
          Authorization: token
        },
        data: {
          favoriteable_id: id,
          favoriteable_type: type
        }
      }).then(res => {
        res = res.data;

        if (res.status) {
          // this.setData({
          //   is_Fav: !!res.data.is_Fav
          // });
		
		  this.is_Fav=!!res.data.is_Fav;
		 
        } else {
          wx.showToast({
            image: '../../../static/error.png',
            title: res.message
          });
        }
      }).catch(rej => {
        console.log(rej);
      });
    },

    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
          // });
		  this.result=result;
		  
          that.specStore(result, key); // this.$emit('specStore', result, key);
        }
      }).catch(err => {});
    },

    queryShoppingCount() {
      var oauth = this.is_login;
      this.$http.get({
        api: `api/shopping/cart/count`,
        header: {
          Authorization: oauth
        }
      }).then(res => {}).catch(rej => {});
    },

    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: '添加到购物车失败，请重试'
          });
        }
      }
    },

    pointSore(data) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.post({
        api: 'api/shopping/order/checkout/point',
        header: {
          Authorization: token
        },
        data: data
      }).then(res => {
        res = res.data;

        if (res.status) {
          this.setData({
            loading: false
          });
          this.$cookieStorage.set('point_order', res.data);
          wx.navigateTo({
            url: '/pages/pointStore/order/order'
          });
        } 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()
                  });
                }
              }
            });
            this.setData({
              loading: false
            });
            return;
          }

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

    changeFavorite(id, type) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.post({
        api: 'api/favorite/store',
        header: {
          Authorization: token
        },
        data: {
          favoriteable_id: id,
          favoriteable_type: type
        }
      }).then(res => {
        res = res.data;

        if (res.status) {
          this.setData({
            is_Fav: !this.is_Fav
          });
        }
      });
    },

    getGoodsDetail(obj) {
      var that = this;
      return new Promise((resolve, reject) => {
        this.$http.get(obj).then(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();
        });
      });
    },

    // 查询商品详情页优惠折扣信息
    // queryDiscounts(id) {
    //    wx.request({
    //        url: config.GLOBAL.baseUrl + 'api/store/detail/' + id + '/discount',
    //        success: res => {
    //            if (res.statusCode == 200) {
    //                res = res.data;
    //                if (res.status) {
    //                    res.data.coupons.forEach(v => v.receive = false);
    //                    this.setData({
    //                         coupons: res.data.coupons,
    //                         discounts: res.data.discounts
    //                    })
    //                }
    //            }
    //        }
    //    })
    // },
    // 领取优惠券
    goodsConvertCoupon(code, index) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.post({
        api: 'api/coupon/convert',
        header: {
          Authorization: token
        },
        data: {
          coupon_code: code
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            var coupons = `coupons[${index}]`;
            this.setData({
              [`${coupons}.receive`]: true
            });
            wx.showToast({
              title: '领取成功'
            });
          } else {
            wx.showToast({
              title: res.message,
              image: '../../../static/error.png'
            });
          }
        } else {
          wx.showToast({
            title: '领取失败',
            image: '../../../static/error.png'
          });
        }
      });
    },

    // 秒杀结算
    checkoutSeckillOrder(data) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.post({
        api: 'api/shopping/order/checkout?seckill_item_id=' + data.seckill_item_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=seckill'
            });
          } 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
            });
          }
        }
      });
    },

    // 商品限购
    goodsPurchase(id) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.get({
        api: 'api/store/goods/purchase/' + id,
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            if (res.data) {
              this.setData({
                'purchaseInfo.status': true,
                'purchaseInfo.num': res.data.user_limit
              });
            }
          } else {
            wx.showModal({
              content: res.message || '接口错误',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: '请求失败',
            showCancel: false
          });
        }
      });
    },

    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>
	.detail-active {
    transition: transform 350ms linear 0ms;
    transform: translate3d(0px, -55px, 0px);
    transform-origin: 50% 50% 0px;
  }
</style>

<style rel="stylesheet/less" lang="less">
	@import "detail";
</style>
