<template>
	
	<view class="">
		<view id="meal-matched">
			<view class="contents">
				<view class="title">
					<view class="matched">
						搭配套餐
					</view>
	
					<view v-if="userInfo.distribution_status==1 && userInfo.is_agent==1" class="recommand" @tap="jumpShare">
						我要推荐
					</view>
				</view>
				<view class="meal-list">
	
					<view class="meal-list-item" :class="(!item.selected) && isClickOrder?'highlight':''" v-for="(item, index) in mealList.items"
					 :key="index" :data-id="item.item_id" @tap="jumpDetail">
	
	
						<image :src="item.goods.img" v-if="item.item_type=='spu'" alt></image>
						<view class="detail" v-if="item.item_type=='spu'">
							<p class="item-title">{{item.goods.name}}</p>
							<p class="item-size">
								<span v-if="(!item.selected) && isClickOrder" style="color: red">请先选择您的规格</span>
								<span v-else>{{item.selectLabel}}</span>
								<span :data-id="item.goods.id" :data-goods="item.goods" :data-price="item.package_price" @tap.stop="changeSize($event,item.goods)" 
								:class="item.seleckValue?'chanSize':'updateSize'"> 
									<span v-if="!item.seleckValue">选择规格</span>
									<span v-else>更改规格</span>
								</span>
							</p>
						</view>
					</view>
					<view class="all_count">
						<view style="text-align: right">
							<span v-if="mealList.total!=undefined" style="color: red">￥{{mealList.total}}</span>
							/
							<span v-if="mealList.origin_total!=undefined" style="text-decoration: line-through">￥{{mealList.origin_total}}</span></view>
					</view>
				</view>
				<view class="meal-bottom">
					<view class="meal-bottom_detail">
						<p>商品总计:<span v-if="mealList.total!=undefined">￥{{mealList.total}}</span></p>
					</view>
					<view class="meal-bottom_button">
						<view @tap="order">结算</view>
					</view>
				</view>
			</view>
	
			<view class="detail-popup" v-show="!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 :src="select_product.img"></image>
							<!--<image wx:if="{{select_product.img}}" src="{{select_product.img}}" alt="{{select_product.sku}}"></image>-->
							<!--<image wx:if="{{!select_product.img && !select_product.color}}" src="{{commodity.img}} " alt=""></image>-->
						</view>
						<view class="img_box" :style="'background-color: ' + select_product.bac + ';width: 78px;height: 78px;'" v-if="!select_product.img && !!select_product.color"></view>
						<view class="price_item">
							<!--<text >￥ {{price}}</text>-->
							<view>请选择您的尺码和颜色</view>
							<text>库存{{selectSpecs.store_count}}</text>
						</view>
	
					</view>
	
	
					<view class="select_spec">
						<view class="spec_line" v-for="(spec, index) in selectSpecs.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="item.id"
								:data-index="item.index" :data-disabled="item.disabled ? 1 : 0" :data-id="item.id" :data-active="item.active ? 1 : 0" :data-key="index" :data-img="item.img" @tap="selectSpec">
									<view class="spec_text">
										{{item.alias || item.value}}
	
										<view v-if="!!item.active" :style="'border-color: ' + config.mainColor" class="border-color">
	
										</view>
										<!-- <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>-->
									<!--<text wx:if="{{!item.spec_img && !item.color}}">{{item.alias || item.value}}</text>-->
								</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>-->
								1
								<!--<text bindtap="changeCount" data-index="1">+</text>-->
	
							</view>
						</view>
	
						<button class="button disabled" v-if="select_product.select_count==0" type="primary" @tap="confirm">确定</button>
						<button class="button" :style="'background: ' + config.mainColor" type="primary" v-else  @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 class="maks" :class="!show_select ? 'cur' : ''" @tap="closeSelect">
	
			</view>
	
		</view>
	</view>
	
	
	</view>
</template>
<script>

var app = getApp();
import {pageLogin, getUrl,config,is,
// #ifdef MP-WEIXIN
autoLogin
// #endif
} from '@/common/js/utils.js';
import Animation from '@/common/js/animation.js';

export default {
  data() {
    return {
      animationSelect: {},
      isClickOrder: false,
      allPrice: 0,
      discountPrice: 0,
      mealList: "",
      show_select: true,
      submitData: [],
      submitRealData: {},
      select_product: {
        id: "",
        goodsId: "",
        img: "",
        price: "",
        name: "",
        store_count: 0,
        buycount: 1,
        select_count: 0
      },
      specs: [],
      selectSpecs: "",
      suitId: "",
      resultList: [],
      config: '',
      userInfo: '',
	  animation:'',
	  show:'',
	  loading:'',
	  is_login:''
    };
  },


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

    if (token) {
      this.getUserInfo();
    }
  },

  onLoad(e) {
    // 第三方平台配置颜色
    var gbConfig = this.$cookieStorage.get('globalConfig') || '';
    // this.setData({
    //   config: gbConfig
    // });
	
	this.config=gbConfig
	
    var id = e.id;
    this.init(e);
    let token = this.$cookieStorage.get('user_token');
 
    this.queryMealList(id);
 
    
    this.suit_id = id;
  },
  methods: {
    jumpDetail(e) {
      var id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/store/detail/detail?id=' + id
      });
    },

    // 获取初始化数据
    init(e) {
      var token = this.$cookieStorage.get('user_token');
      var agent_code = '';

      if (e.agent_code) {
        agent_code = e.agent_code;
      }

      if (e.scene) {
        var scene = decodeURIComponent(e.scene);
        var sceneArr = scene.split(',');

        if (sceneArr.length > 0) {
          agent_code = sceneArr[1];
        }
      }

      this.$http.get({
        api: 'api/system/init'
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            if (res.data && res.data.other_technical_support) {
              // this.setData({
              //   author: res.data.other_technical_support
              // });
			  
			  this.author=res.data.other_technical_support;
			  
            }
            /*wx.setNavigationBarTitle({
                title: res.data.mini_home_title
            })*/

            this.$cookieStorage.set('init_info', res.data.h5_share);
            this.$cookieStorage.set('service_info', res.data.online_service_data);
            this.$cookieStorage.set('distribution_valid_time', res.data.distribution_valid_time);
            this.$cookieStorage.set('init', res.data);
            this.setCode(e);
			// #ifdef MP-WEIXIN
            if (agent_code && res.data.mini_program_login_type == 'default' && !token) {
              wx.showLoading({
                title: '正在自动登录',
                mask: true
              });
              wx.login({
                success: res => {
                  if (res.code) {
                    app.autoLogin(res.code, agent_code).then(res => {
                      if (res.status) {
                        if (res.data.access_token) {
                          var access_token = res.data.token_type + ' ' + res.data.access_token;
                          this.setData({
                            is_login: access_token
                          });
                        }

                        if (res.data.open_id) {
                          wx.reLaunch({
                            url: '/pages/user/agentlogin/agentlogin?agent_code=' + agent_code + '&open_id=' + res.data.open_id + '&url=' + getUrl()
                          });
                        }
                      }

                      wx.hideLoading();
                    }, err => {
                      wx.hideLoading();
                    });
                  } else {
                    wx.showToast({
                      title: '获取code失败',
                      icon: 'none'
                    });
                  }
                }
              });
            }
			// #endif
			// #ifdef H5
			if(agent_code && !token){
				var env = {
							 isIPad: /ipad/i.test(window.navigator.userAgent),
							 isIphone: /iphone|ipad|ipod/i.test(window.navigator.userAgent),
							 isWechat: /MicroMessenger/i.test(window.navigator.userAgent)
				}
				if(env.isWechat){
					if(e.openid){
						this.$cookieStorage.set('openid',e.openid)
					}
					var openid =  this.$cookieStorage.get('openid') || e.openid;
					if(openid){
						this.postNewQuickLogin(openid,agent_code);
					} else{
						let origin = window.location.origin;
						var url = origin+'/pages/store/meal/meal?agent_code='+agent_code;
						window.location.href = this.$config.GLOBAL.baseUrl+'oauth/wxOauth?redirect_url='+encodeURIComponent(url);
					}
				} else{
					var url = getUrl();
					wx.navigateTo({
						url:'/pages/user/loginType/loginType?url='+url
					})
				}
			}
			// #endif
          } else {
            this.setCode(e);
          }
        } else {
          this.setCode(e);
        }
      });
    },
	
	postNewQuickLogin(open_id,agent_code){
		wx.showLoading({
			title: '正在登录',
			mask: true
		});
		this.$http.post({
			api:'api/oauth/newQuickLogin',
			data:{
				open_id:open_id,
				agent_code:agent_code
			}
	}).then(res=>{
			res = res.data;
			if(res.status){
				if(res.data.access_token){
					var access_token = res.data.token_type + ' ' + res.data.access_token;
					var expires_in = res.data.expires_in || 315360000; 
					this.$cookieStorage.set("user_token", access_token, expires_in);
					//如果用户没有绑定手机号
					if(res.data.has_bind_mobile == 0){
						wx.reLaunch({
							url:'/pages/user/bindingphone/bindingphone'
						})
					} else{
						this.is_login = this.$cookieStorage.get('user_token');
					}
				} else{
					wx.showModal({
						content: res.message || '请求失败，请重试',
						showCancel: false
					});
					
				}
				
			} else{
				wx.showModal({
					content: res.message || '请求失败，请重试',
					showCancel: false
				});
			}
			wx.hideLoading()
		}).catch(rej=>{
			wx.showModal({
				content: rej.message || '请求失败，请重试',
				showCancel: false
			});
			wx.hideLoading()
			
		})
		
	},

    setCode(e) {
      const timeMap = {
        y: 31536000000,
        m: 2592000000,
        d: 86400000,
        h: 3600000,
        n: 60000,
        s: 1000
      }; // 默认有效期为7天

      var valid_time = "";
      var clerk_id = e.clerk_id || "";
      var shop_id = e.shop_id || "";
      var agent_code = e.agent_code || '';

      if (e.scene) {
        var scene = decodeURIComponent(e.scene);
        var sceneArr = scene.split(',');

        if (sceneArr.length > 0) {
          agent_code = sceneArr[0];
        }
      }

      var cook_shop_id = this.$cookieStorage.get('shop_id');

      if (!this.$cookieStorage.get('distribution_valid_time')) {
        valid_time = 10080;
      } else {
        valid_time = this.$cookieStorage.get('distribution_valid_time');
      }

      console.log('这个是时间', valid_time);
      let timeStamp = new Date().getTime();
      timeStamp += timeMap.n * valid_time; // 当url上shop_id与缓存中shop_id不一致时，需要清除clerk_id。以此保证shop_id与clerk_id对应

      var cook_clerk_id = this.$cookieStorage.get('clerk_id');

      if (cook_shop_id != shop_id && cook_clerk_id) {
        this.$cookieStorage.clear('clerk_id');
      }

      if (agent_code) {
        this.$cookieStorage.set('agent_code', agent_code, valid_time + 'n'); // 如果有agent_code就将这次进入的时间缓存

        this.$cookieStorage.set('agent_code_time', timeStamp, valid_time + 'n'); // 如果有agent_code并且有coupon_agent_code就将coupon_agent_code清除，保证agent_code为第一位

        if (this.$cookieStorage.get('coupon_agent_code')) {
          this.$cookieStorage.clear('coupon_agent_code');
        }
      }

      if (clerk_id) {
        this.$cookieStorage.set('clerk_id', clerk_id, valid_time + 'n');
      }

      if (shop_id) {
        this.$cookieStorage.set('shop_id', shop_id, valid_time + 'n'); // 如果有shop_id就将这次进入的时间缓存

        this.$cookieStorage.set('shop_id_time', timeStamp, valid_time + 'n');
      }

      const code = agent_code || this.$cookieStorage.get('agent_code');

      if (code) {// this.getCodeUser(code);
      }
    },

    setCache() {
      const timeMap = {
        y: 31536000000,
        m: 2592000000,
        d: 86400000,
        h: 3600000,
        n: 60000,
        s: 1000
      }; // 默认有效期为7天

      var valid_time = "";

      if (!this.$cookieStorage.get('distribution_valid_time')) {
        valid_time = 10080;
      } else {
        valid_time = this.$cookieStorage.get('distribution_valid_time');
      }

      if (this.agent_code) {
        let code = this.agent_code;
        let timeStamp = new Date().getTime();
        timeStamp += timeMap.n * valid_time;

        if (!!!this.$cookieStorage.get('agent_code')) {
          var suitId = [];
          suitId.push({
            id: this.suit_id,
            time: timeStamp
          });
          this.$cookieStorage.set('agent_code', code, valid_time + "n");
          this.$cookieStorage.set('agent_suit_id', suitId);
        } else {
          if (code == this.$cookieStorage.get('agent_code')) {
            var suitData = this.$cookieStorage.get('agent_suit_id') ? this.$cookieStorage.get('agent_suit_id') : [];
            var flag = false;

            for (var i = 0; i < suitData.length; i++) {
              if (suitData[i].id == this.suit_id) {
                flag = true;
                suitData[i].time = timeStamp;
                break;
              }
            }

            if (!flag) {
              suitData.push({
                id: this.suit_id,
                time: timeStamp
              });
            }

            this.$cookieStorage.set('agent_code', code, valid_time + "n"); //

            this.$cookieStorage.set('agent_suit_id', suitData); //
			
          } else {
            //
            //                 覆盖更新
            //                            var data=[];
            var suitId = []; //

            suitId.push({
              id: this.suit_id,
              time: timeStamp
            });
            this.$cookieStorage.set('agent_code', code, valid_time + "n"); //                            Cache.set(cache_keys.agent_goods_id,data,0);

            this.$cookieStorage.set('agent_suit_id', suitId); // this.$cookieStorage.set('agent_scan',0,valid_time+"n");
          }
        }
      }
    },

    getUserInfo() {
      this.$http.get({
        api: 'api/me',
        header: {
          Authorization: this.$cookieStorage.get('user_token')
        }
      }).then(res => {
        if (res.data.status) {
          this.setData({
            userInfo: res.data.data
          });
        }
      });
    },

    jumpShare() {
      wx.navigateTo({
        url: '/pages/store/mealShare/mealShare?id=' + this.suit_id
      });
    },

    // 处理套餐数据信息
    dealMeal(data) {
      data.items.forEach(val => {
        val.selectLabel = "";
        val.selected = false;
        val.seleckValue = false;
      }); // this.mealList

      this.setData({
        mealList: data
      });
    },

    // 点击选择规格或者更改规格
    changeSize(e,goods) {
      var data = e.currentTarget.dataset;
     
      // #ifdef APP-PLUS || MP-WEIXIN
      this.setData({
        'show_select': false,
        'select_product.img': data.goods.img,
        'select_product.originImg': data.goods.img,
        'select_product.goodsId': data.goods.id,
        'select_product.price': data.price,
        'select_product.name': data.goods.name,
        'select_product.store_count': data.goods.store_nums
      });
      // #endif
	  
	  // #ifdef H5
	  this.setData({
	    'show_select': false,
	    'select_product.img':goods.img,
	    'select_product.originImg':goods.img,
	    'select_product.goodsId':goods.id,
	    'select_product.price': data.price,
	    'select_product.name':goods.name,
	    'select_product.store_count':goods.store_nums
	  });
	  // #endif
	  
	 
	 //    this.show_select=false;
	 //    this.select_product.img=data.goods.img;
	 //    this.select_product.originImg= data.goods.img;
	 //    this.select_product.goodsId= data.goods.id;
	 //    this.select_product.price= data.price;
	 //    this.select_product.name= data.goods.name;
	 //    this.select_product.store_count=data.goods.store_nums;
	 // 
	  

      if (data.goods.no_spec) {
        this.setData({
          'select_product.select_count': 1,
          'select_product.id': ''
        });
      } else {
        this.setData({
          'select_product.store_count': 0
        });
      }

     // #ifdef MP-WEIXIN
     var animation = new Animation('show');
     animation.positionInit();
     // #endif
      let i = this.specs.findIndex(val => {
        return val.id == data.id;
      });

      if (i != -1) {
        this.setData({
          selectSpecs: this.specs[i]
        });
      } else {
        wx.showLoading({ 
          title: "加载中",
          mask: true
        });
        this.queryCommodityMealStore(data.id);
      }
    },

    closeSelect() { 
	 this.setData({
	 	show_select: true
	 })
	 
	 
    },

    queryMealList(id) {
      wx.showLoading({
        title: "加载中",
        mask: true
      });
      this.$http.get({
        api: 'api/suit/' + id + '/list'
      }).then(res => {
        res = res.data; //

        console.log(res);

        if (res.status) {
          this.dealMeal(res.data);
        } else {
          wx.showModal({
            title: "提示",
            content: "套餐数据加载失败"
          });
        }

        this.setCache();
        wx.hideLoading();
      });
    },

    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),
       img:e.currentTarget.dataset.img
      };

      if (spec.img) {
        this.setData({
          'select_product.img': spec.img
        });
      } else {
        this.setData({
          'select_product.img': this.select_product.originImg
        });
      }

      if (spec.disabled) return;
      let specItem = this.selectSpecs;

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

      spec.active = !spec.active;
      specItem.specs[spec.index].values[spec.key].active = !specItem.specs[spec.index].values[spec.key].active;
      specItem.specs[spec.index].select = spec.active ? spec.id : '';
      this.setData({
        "selectSpecs.specs": specItem.specs
      });
      let id = specItem.id;
      let specs = this.specs;
      let i = specs.findIndex(function (val) { 
		  
        return val.id == id;
      }); // console.log("索引号"+i);

      specs.splice(i, 1);
      specs.push(specItem);
      let goodsId = this.select_product.goodsId;
	 
      let idx = this.resultList.findIndex(val => {
        return val.specs.id == goodsId;
      });
	  

      if (idx != -1) {
        this.specStore(this.resultList[idx], spec.index);
      } else {
        this.queryCommodityMealStore(goodsId, spec.index);
      }
    },

    specStore(result, key) {
      var lists = this.resultList;
      lists.push(result);
      this.setData({
        resultList: lists
      }); //计算库存

      if (!key && key != 0) {
        /*this.setData({
            "select_product.store_count":0,
            "select_product.select_count":0
        });
        let store_count=0,
            specs=this.specs,
            selectSpecs=this.selectSpecs;
        for(let k in result.table){
            store_count+=result.table[k].store*1;
        }
        result.specs.store_count=store_count;
        specs.push(result.specs);
        selectSpecs=result.specs;
        this.setData({
            specs:specs,
            selectSpecs:selectSpecs,
            'select_product.store_count':store_count
        });*/
        var specs = this.specs;
        specs.push(result.specs);
        this.setData({
          specs: specs,
          selectSpecs: result.specs
        });
        var allSku = this.selectSpecs.specs;

        if (allSku.length) {
          this.setData({
            'select_product.store_count': 0,
            'select_product.select_count': 0
          });
          var store_count = 0;

          for (let k in result.table) {
            store_count += result.table[k].store * 1;
          }

          ;
          this.setData({
            'select_product.store_count': store_count
          });
        } else {
          this.setData({
            'select_product.select_count': 1
          });
        } // this.setCount(store_count);

      } else {
        // let select_count=0;
        this.setData({
          "select_product.select_count": 0
        });
        let allSku = this.selectSpecs.specs;
	
        this.updateCss(result.data);
        let selectArr = [];
        allSku.forEach(val => {
          if (val.select) {
            selectArr.push(val.select);
          }
        });

        if (selectArr.length == 0) {
          this.setData({
            'select_product.store_count': 0
          });
          let store_count = 0;

          for (var k in result.table) {
            store_count += result.table[k].store;
          }

          this.setData({
            'select_product.store_count': store_count,
            'select_product.select_count': 0
          });
          this.setCount(store_count);
        } else if (selectArr.length == 1 && allSku.length == 2) {
          this.setData({
            'select_product.store_count': result.data[selectArr[0]].count,
            'select_product.select_count': 0
          });
          this.setCount(result.data[selectArr[0]].count);
        } else if (selectArr.length == 1 && allSku.length == 1) {
          // 单规格
          // let count=this.select_product.store_count;
          this.setData({
            'select_product.select_count': 1,
            'select_product.store_count': result.data[selectArr[0]].count
          });
          let str = selectArr.join('-');
          let table = result.table[str] || result.table[str.replace(/(\w+)-(\w+)/g, "$2-$1")];
          this.setData({
            'select_product.id': table.id
          });
        } else {
          let m = selectArr[0];
          let store_count = "";

          for (var i = 1; i < selectArr.length; i++) {
            // this.setData({
            //     'select_product.store_count':result.data[m].specs[selectArr[i]].count
            // })
            store_count = result.data[m].specs[selectArr[i]].count;
          } // let count=this.select_product.store_count;


          this.setData({
            'select_product.select_count': store_count,
            'select_product.store_count': store_count
          });
          let str = selectArr.join('-');
          let table = result.table[str] || result.table[str.replace(/(\w+)-(\w+)/g, "$2-$1")];
          this.setData({
            'select_product.id': table.id
          });
        } // 库存更

      }

      this.setCount(this.select_product.store_count);
    },

    setCount(num) {
      this.setData({
        'selectSpecs.store_count': num
      });
    },

    confirm() {
      if (this.select_product.select_count == 0) {
        return;
      } // 拿到选中商品的id


      let id = this.selectSpecs.id;
      let price = this.select_product.price;
      let label = [],
          skuData = {},
          flag = false,
          specsItem = this.selectSpecs.specs;
      specsItem.forEach(function (val, index) {
        let selectId = val.select;
        val.values.forEach(function (obj, i) {
          if (selectId == obj.id) {
            label.push(obj.alias || obj.value);

            if (val.label_key == "color") {
              skuData['color'] = obj.value;
            } else {
              skuData['size'] = obj.value;
            }
          }
        });
      });
      label = label.join(","); //循环套餐列表

      let mealItems = this.mealList.items;
      let index = mealItems.findIndex(function (val) {
        return val.item_id == id;
      });
	  
      // this.setData({
      //   [`mealList.items[${index}].selected`]: true,
      //   [`mealList.items[${index}].selectLabel`]: label,
      //   [`mealList.items[${index}].seleckValue`]: true,
      //   [`mealList.items[${index}].package_price`]: price
      // }); 
	 
	    this.mealList.items[index].selected=true;
		this.mealList.items[index].selectLabel=label;
	    this.mealList.items[index].selectLabel=label;
	    this.mealList.items[index].seleckValue=true;
	    this.mealList.items[index].package_price=price;
	  
	
	  // 生成对象   商品id，商品数量，商品名称，商品图片，商品单价，商品总价，判断是否是sku商品如果是添加sku_goods_id值

      let data = {};
      data.id = id;
      data.goodsId = id;
      data.name = this.select_product.name;
      data.qty = this.select_product.buycount;
      data.img = this.select_product.img;
      data.price = this.select_product.price * 1;
      data.total = this.select_product.price * this.select_product.buycount;
      data.attributes = {};
      data.sku_goods_id = id;

      if (this.select_product.id) {
        data.attributes['dynamic_sku'] = {};
        data.attributes['dynamic_sku'].id = this.select_product.id;
        data.attributes['dynamic_sku'].color = skuData['color'];
        data.attributes['dynamic_sku'].size = skuData['size'];
      }

      let submitDatas = this.submitData;

      if (submitDatas.length) {
        let index = submitDatas.findIndex(function (val) {
          return val.goodsId == id;
        });

        if (index != -1) {
          submitDatas.splice(index, 1);
          submitDatas.push(data);
        } else {
          submitDatas.push(data);
        }
      } else {
        submitDatas.push(data);
      }

      this.setData({
        "submitData": submitDatas,
        "show_select": true
      });
    },

    // 更新样式
    updateCss(skutable) {
      let select = {};
      let specs = this.selectSpecs.specs;
      specs.forEach(val => {
        if (val.select != '') {
          let arr = skutable[val.select].specs;

          for (var k in arr) {
            if (arr[k].count == 0) {
              select[k] = true;
            } else {
              select[k] = false;
            }
          }
        }
      });
      specs.forEach(val => {
        val.values.forEach(v => {
          v.disabled = select[v.id];
        });
      });
      this.setData({
        'selectSpecs.specs': specs
      });
    },

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

      if (!token) {
        wx.navigateTo({
          url: '/pages/user/register/register?url=' + getUrl()
        });
        return;
      }

      wx.showLoading({
        title: "加载中",
        mask: true
      });
      this.setData({
        "isClickOrder": true
      });

      if (this.submitData.length != this.mealList.items.length) {
        wx.hideLoading();
      } else {
        let submitRealData = this.submitRealData;
        this.submitData.forEach(function (val, index) {
          delete val.goodId;
          submitRealData[index] = val;
        });
        this.setData({
          'submitRealData': submitRealData
        });
        this.checkoutMealOrder(this.suit_id, submitRealData);
      }
    },

    queryCommodityMealStore(id, key) {
      this.$http.get({
        api: 'api/store/detail/' + id + '/stock'
      }).then(res => {
        res = res.data;
        wx.hideLoading();
        if (!res.status || !res.data || !res.data.specs) return; // 规格

        let specs = [];

        if (res.data.specs && typeof key === 'undefined') {
          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; // console.log(value);

            specs.push(value);
          }); // console.log(specs);
          // dispatch(CommoditySpec, specs);
        }

        if (res.data.stores) {
          let data = {}; // console.log(res.data.stores);

          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 += parseInt(value.store);
              value.ids.forEach(i => {
                if (i === id) return;
                data[id].specs[i] = {
                  count: parseInt(value.store)
                };
              });
            });
          }); // console.log(data);

          let result = {
            data,
            table: res.data.stores,
            specs: {
              id,
              specs,
              store_count: 0
            }
          }; // this.add();

          this.specStore(result, key);
        }
      });
    },

    add() {
      console.log("demo");
    },

    checkoutMealOrder(suitId, submitRealData) {
      this.$http.post({
        api: 'api/shopping/order/checkout?suit_id=' + suitId,
        data: submitRealData,
        header: {
          Authorization: this.$cookieStorage.get('user_token')
        }
      }).then(res => {
        res = res.data;

        if (res.status) {
          this.$cookieStorage.set("local_order", res.data);
          this.checkout(true);
        } else {
          this.checkout(false, res.message);
        }
      });
    },

    checkout(success, message) {
      wx.hideLoading();

      if (success) {
        wx.navigateTo({
          url: '/pages/store/order/order?type=order'
        });
      } else {
        wx.showModal({
          title: "提示",
          content: message || "结算失败，请重试"
        });
      }
    },

    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 "meal";
</style>
