<template>
<view id="store-cart">
	<lf-nav title="购物车"></lf-nav>
    <view class="discount-box">
        <!--登录状态-->
        <view class="is-login" v-if="(is_login && discounts.length) || (is_login && coupons.length)">
            <view class="promotion-box">
                <view class="promotion" @tap="changeDiscounts" v-if="discounts.length">
                    <view class="title" :style="'color: ' + config.mainColor + '; border-color: ' + config.mainColor">
                        {{discounts[0].tags}}
                    </view>
                    <view>
                        {{discounts[0].label}} >
                    </view>
                </view>
            </view>
            <view class="coupon mx-1px-left" :style="'color: ' + config.mainColor + ';'" @tap="changeCoupons" v-if="coupons.length">
                优惠券
            </view>
        </view>
        <!--未登录状态-->
        <div class="no-login" v-if="!is_login" @tap="goLogin">
            <div class="left">
                <i class="iconfont icon-warning"></i>
                <div>
                    <span>登录</span>后查看是否享受优惠
                </div>
            </div>
            <div class="right">
                登录 >
            </div>
        </div>
    </view>
	<view class="no-goods" v-if="list && list.length == 0">
		<image mode="widthFix" src="https://cdn.guojiang.club/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20200323164958.png"></image>
	</view>
    <view class="goods-box" v-if="list && list.length">
        <checkbox-group @change="changeCheck">
            <view class="goods-item mx-1px-bottom" v-for="(item, index) in list" :key="index">
                <view class="input">
                    <label class="checkbox">
                        <!-- #ifdef APP-PLUS -->
                        <checkbox :value="String(index)" color="red" :checked="item.checked"></checkbox>
                        <!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<checkbox :value="String(index)" color="#FFFFFF" :checked="item.checked"></checkbox>
						<!-- #endif -->
						<!-- #ifdef H5 -->
						<checkbox :value="String(index)" color="red" :checked="item.checked"></checkbox>
						<!-- #endif -->
						{{item.value!=undefined?item.value:''}}
                    </label>
                </view>
                <view class="img-box" :data-id="item.com_id" @tap.stop="jump">
                    <image :src="item.img"></image>
                </view>
                <view class="item-info">
                    <view class="name" :data-id="item.com_id" @tap.stop="jump">
                        {{item.name}}
                    </view>
                    <view class="money-box" :data-id="item.com_id" @tap.stop="jump">
                        <view class="model">
                            {{item.color}} <span v-if="item.color && item.size">,</span> {{item.size}}
                        </view>
                        <view class="money">
                            ￥{{item.total}}
                        </view>
                    </view>
                    <view class="mun-box">
                        <view class="change-num">
                            <view class="ul-list-content">
                                <view class="item" :data-index="index" data-change="0" @tap="changeCount">-</view>
                                <view class="item"><input type="number" :value="item.qty" :data-index="index" @change="modifyCount" /></view>
                                <view class="item" :data-index="index" data-change="1" @tap="changeCount">+</view>
                            </view>
                        </view>
                        <view class="remove" @tap="removeFromCart" :data-index="index">
                            移除

                        </view>
                    </view>
                </view>
            </view>

        </checkbox-group>
    </view>
    <view class="buy-box">
        <label class="checkbox">
           <!-- #ifdef APP-PLUS -->
            <checkbox value="all" color="red" :checked="allCheck" @tap="selectAll"></checkbox>
           <!-- #endif -->
		   <!-- #ifdef MP-WEIXIN -->
		   <checkbox value="all" color="#FFFFFF" :checked="allCheck" @tap="selectAll"></checkbox>
		   <!-- #endif -->
		   <!-- #ifdef H5 -->
		   <checkbox value="all" color="red" :checked="allCheck" @tap="selectAll"></checkbox>
		   <!-- #endif -->
            <text>全选</text>
        </label>
        <view class="money-box">
            商品总计：<text>￥{{select_products.total!=undefined?select_products.total:''}}</text>
        </view>
        <button class="num-box" :style="'background: ' + config.mainColor" @tap="order" :loading="loading">
            结算<text>{{'('+ select_products.count + ')' || 0}}</text>
        </button>
    </view>



    <!--选择优惠券部分-->
    <view class="maks" :class="show_coupons ? 'cur' : ''" @tap="showCoupons">

    </view>
    <view class="select-coupon-box" :class="show_coupons ? 'cur' : ''">
        <view class="select-coupon">
            <view class="select-coupon-top">
                <view class="title">
                    领取优惠券

                    <view class="close" @tap="showCoupons">
                        X
                    </view>
                </view>
            </view>

            <view class="select-coupon-bottom">
                <view class="title">
                    可领优惠券
                </view>
                <view class="coupon-box">
                    <view class="coupon-item" v-for="(item, index) in coupons" :key="index" v-if="item.is_open">
                        <view class="coupon">
                            <view class="coupon-left">
                                <view class="text-wrap">
                                    <view class="text-box">
                                        <view class="text">
                                            <span class="money" v-if="item.action_type.type == 'cash'">￥</span>
                                            <span class="num">{{ item.action_type.value }}</span>


                                            <span class="money" v-if="item.action_type.type == 'discount'">折</span>
                                        </view>
                                        <span class="label text">{{ item.label }}</span>
                                    </view>

                                </view>
                                <view class="dot-wrap">
                                    <view class="dot-item">

                                    </view>
                                    <view class="dot-item">

                                    </view>
                                    <view class="dot-item">

                                    </view>
                                    <view class="dot-item">

                                    </view>
                                    <view class="dot-item">

                                    </view>
                                </view>
                            </view>
                            <view class="coupon-right">
                                <view class="top">
                                <span>
                                    <span class="type" v-if="item.channel == 'ec'">商店</span>
                                    <span class="type" v-if="item.channel == 'shop'">门店</span>
                                </span>
                                    <span class="info">{{item.title}}</span>
                                </view>
                                <view class="bottom">
                                    <view class="bottom-use">
                                        <view class="tiem-box">
                                            <text>{{item.use_start_time}}至{{item.use_end_time}}</text>
                                        </view>
                                        <view class="btn use" :style="'background: ' + config.mainColor + '; border-color: ' + config.mainColor" :data-code="item.code" :data-index="index" v-if="!coupons[index].receive" @tap="getCoupon">
                                            点击领取

                                        </view>
                                        <view class="btn already" v-else>
                                            已领取

                                        </view>

                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

            </view>

        </view>
    </view>


    <!--查看促销部分-->

    <view class="maks" :class="show_discounts ? 'cur' : ''" @tap="showDiscounts">

    </view>

    <view class="see-discounts-box" :class="show_discounts ? 'cur' : ''">
        <view class="select-discounts">
            <view class="select-discounts-top">
                <view class="title">
                    促销
                    <view class="close" @tap="showDiscounts">
                        X
                    </view>
                </view>
            </view>

            <view class="select-discounts-bottom">
                <view class="discounts-box">
                    <view class="disconts-item mx-1px-bottom" v-for="(item, index) in discounts" :key="index">
                        <view class="discounts-tags-title" :style="'color: ' + config.mainColor + '; border-color: ' + config.mainColor">
                            {{item.tags}}
                        </view>
                        <view class="tags-item">
                            {{item.label}}
                        </view>
                    </view>
                </view>
            </view>

        </view>
    </view>
</view>


</template>
<script>
import {pageLogin, getUrl,config} from '@/common/js/utils.js';
import lfNav from '@/components/lf-nav/lf-nav.vue';

export default {
  data() {
    return {
      is_login: '',
      list: [],
      groupList: [],
      select_products: {},
      allCheck: true,
      channel: 'normal',
      loading: false,
      show_coupons: false,
      // 领取优惠券
      show_discounts: false,
      // 查看促销活动
      goodsList: [],
      // 购物车里存在的商品id
      config: '',
      author: config.PACKAGES.author,
	  discounts:'',
	  coupons:''
    };
  },

  onShow() {
    // var oauth = Cache.get(cache_keys.token);
    // var locals = Cache.get(cache_keys.cart);
    var is_login = this.$cookieStorage.get('user_token');
    this.setData({
      is_login: is_login,
      loading: false
    });
    var oauth = this.is_login; 

    var locals = this.$cookieStorage.get('cart');

    if (oauth && locals && locals.length) {
      // 提交本地购物车
      this.appendToCart(locals);
    } else {
      this.queryCartList();
    } // let app =getApp();
    // app.isBirthday().then(()=>{
    //     if(this.$cookieStorage.get("birthday_gift")){
    //         var giftData=this.$cookieStorage.get("birthday_gift").data;
    //         new app.ToastPannel().__page.showText(giftData);
    //     }
    // });

  },

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

  components: {
	  lfNav
  },
  props: {},
  methods: {
    jump(e) {
      var id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/store/detail/detail?id=' + id
      });
    },

    select_product() {
      var data = {
        count: 0,
        total: 0,
        __ids: []
      };
      this.list.forEach(v => {
        if (v.checked) {
          data.count += parseInt(v.qty);
          data.total += Number(v.total);

          data.__ids.push(v.__raw_id || v.index);
        } else {
          this.setData({
            allCheck: false
          });
        }
      });
      this.setData({
        select_products: data
      });
    },

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

      if (success) {
        this.$cookieStorage.clear('cart'); // wx.removeStorageSync('cart')
        // TODO
        //this.$emit('readyCheckout');

        this.queryCartList();
      } else {
        this.$cookieStorage.clear('cart'); // wx.removeStorageSync('cart')

        wx.showModal({
          title: message || '保存本地购物车失败,请重试！'
        });
      }
    },

    order() {
      var data = this.select_products;

      if (!data.count) {
        // this.$refs.button.finish();
        return;
      }

      ;
      this.setData({
        loading: true
      });
      var oauth = this.is_login;

      if (!oauth) {
        // 滚去登录
        var url = getUrl(); // this.$router.go({ name: 'user-quick-login', query: { source: this.$route.path } });

        wx.navigateTo({
          url: '/pages/user/register/register?url=' + url
        });
        return;
      } // var locals = wx.getStorageSync('cart');


      var locals = this.$cookieStorage.get('cart');

      if (locals && locals.length) {
        // 提交本地购物车
        this.appendToCart(locals);
        return;
      }

      this.readyCheckout();
    },

    readyCheckout() {
      var ids = this.select_products.__ids;
      var type = this.channel;
      this.checkoutOrder(ids, type);
    },

    checkoutOrder(ids, type) {
      var oauth = this.is_login;
      var cart_ids = ids.filter(id => id);
      var wechat_group_id = this.$cookieStorage.get('openGId') || '';
      var that = this;
      this.$http.post({
        api: `api/shopping/order/checkout`,
        data: {
          cart_ids,
          type,
          wechat_group_id
        },
        header: {
          Authorization: oauth
        },
        method: 'POST'
      }).then(res => {
        res = res.data;

        if (res.status) {
          // Cache.set(cache_keys.order, res.data);
          // wx.setStorageSync('local_order',res.data)
          this.$cookieStorage.set('local_order', res.data);
          that.checkout(true);
        } else {
          that.checkout(false, res.message);
        }
      }).catch(() => {
        that.checkout(false);
      });
    },

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

      if (success) {
        // this.$router.go({ name: 'store-order'});
        wx.navigateTo({
          url: '/pages/store/order/order'
        });
      } else {
        // this.$Alert(message || '结算失败，请重试!');
        if (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: message || '结算失败,请重试！',
            showCancel: false
          });
        }
      }
    },

    queryCartList() {
      // var data = wx.getStorageSync('cart') || [];
      var data = this.$cookieStorage.get('cart') || []; // var oauth = Cache.get(cache_keys.token);

      var oauth = this.is_login;

      if (!oauth) {
        this.setData({
          list: data
        });
        this.select_product();
        this.groupListF();
        return;
      }

      var that = this;
      this.$http.get({
        api: `api/shopping/cart`,
        header: {
          Authorization: oauth
        }
      }).then(res => {
        res = res.data;
        var data = [];

        if (res.status && res.data) {
          data = Object.keys(res.data).map(key => {
            res.data[key].checked = true;
            return res.data[key];
          }).concat(data); // 购物车领券

          if (data.length) {
            var list = [];
            data.forEach(v => {
              if (that.goodsList.indexOf(v.com_id) == -1) {
                list.push(v.com_id);
              }

              ;
            });
            this.setData({
              goodsList: list
            });
            this.cardDiscount(list);
          }
        }

        that.setData({
          list: data
        });
        that.select_product();
        that.groupListF();
      }).catch(rej=> {
        this.addCart(false);
      });
    },

    updated(success, data, item, index) {
      if (success) {
        item.qty = data.qty;
        item.total = data.total;
      } else {
        // TODO;
        item.qty = data.qty;
        item.total = item.qty * Number(item.price);
        wx.showToast({
          title: '超过最大库存',
          image: '../../../static/error.png'
        });
      }

      var list = this.list;
      list[index] = item;
      this.setData({
        list: list
      });
      this.select_product();
      this.groupListF();
    },

    change(item, data, index) {
      

      if (item.local) {
        var locals = uni.getStorageInfo('cart') || [];
        locals[item.index].qty = data.qty;
        locals[item.index].total = data.total; // Cache.set(cache_keys.cart, locals, 0, null);
        // wx.setStorageSync('cart',locals)

        this.$cookieStorage.set('cart', locals); // this.$emit('updated', true, data, item);

        this.updated(true, data, item, index);
      } else {
        // clearTimeout(this.countTimer);
        //
        // this.countTimer = setTimeout(() => {
        //     this.updateToCart(data, item);
        // }, 200);
        this.updateToCart(data, item, index);
      }
    },

    modifyCount(e) {
      var index = e.currentTarget.dataset.index;
      var item = this.list[index];
      var val = e.detail.value;
      var store_count = item.store_count;

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

      if (store_count != undefined) {
        if (val > store_count) {
          val = store_count;
          wx.showToast({
            title: '超过最大库存'
          });
        }
      }

      var data = {
        qty: val,
        total: val * Number(item.price)
      };
      this.change(item, data);
    },

    updateToCart(attr, data, index) {
      var oauth = this.is_login;
      var that = this;
      this.$http.ajax({
        api: `api/shopping/cart/${data.__raw_id}`,
        data: {
          attributes: {
            qty: attr.qty
          }
        },
        method: 'PUT',
        header: {
          Authorization: oauth
        }
      }).then(res => {
        res = res.data;

        if (res.status !== false) {
          // this.$emit('updated', true, attr, data);
          that.updated(true, attr, data, index);
        } else {
          // this.$emit('updated', false, { qty: res.data.stock_qty }, data);
          that.updated(false, {
            qty: res.data.stock_qty
          }, data, index);
        }
      });
    },

    changeCount(e) {
		
		
      var index = e.currentTarget.dataset.index,
          change = e.currentTarget.dataset.change,
          list = this.list,
          val = (parseInt(list[index].qty) || 0) + (parseInt(change) ? 1 : -1),
          store_count = list[index].store_count;
		  
      if (store_count == undefined) {
        if (val > 0 && val <= 99) {
          var data = {
            qty: val,
            total: val * Number(list[index].price)
          };
          this.change(list[index], data, index);
        }
      } else {
        if (val > 0 && val <= store_count) {
          var data = {
            qty: val,
            total: val * Number(list[index].price)
          };
          this.change(list[index], data, index);
        } else {
          wx.showToast({
            title: '超过最大库存',
            image: '../../../static/error.png'
          });
        }
      }
    },

    groupListF() {
      if (this.list) {
        var data = [];
        var groups = {};
        this.list.forEach((v, i) => {
          let channel = v.channel || 'normal';

          if (groups[channel] !== undefined) {
            data[groups[channel]].items.push(v);
            data[groups[channel]].index.push(i);
          } else {
            groups[channel] = data.length;
            data.push({
              channel,
              items: [v],
              checked: [],
              index: [i]
            });
          }
        });
      }

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

    appendToCart(data) {
      // var oauth = Cache.get(cache_keys.token);
      var oauth = this.is_login;
      if (!oauth) return;

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

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

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

    removeFromCart(e) {
      var oauth = this.is_login;
      var index = e.currentTarget.dataset.index;
      var list = this.list;
      var data = list[index];

      if (list[index].local) {
        // var locals = wx.getStorageSync('cart') || [];
        var locals = this.$cookieStorage.get('cart') || [];

        for (let i = 0; i < locals.length; i++) {
          if (locals[i].index === list[index].index) {
            locals.splice(i, 1);
            break;
          }
        }

        if (locals.length) {
          this.$cookieStorage.set('cart', locals); // wx.setStorageSync('cart',locals)
        } else {
          this.$cookieStorage.clear('cart'); // wx.removeStorageSync('cart')
        }

        this.removed(true, index);
      } else {
        this.$http.ajax({
          api: `api/shopping/cart/${data.__raw_id}`,
          header: {
            Authorization: oauth
          },
          method: 'DELETE'
        }).then(res => {
          res = res.data;
          this.removed(true, index);
        }).catch(rej => {
          this.removed(false);
        });
      }
    },

    removed(success, index) {
      if (success) {
        var list = this.list;
        var product = list.splice(index, 1)[0];
        this.setData({
          list: list
        });
        this.select_product();
        this.groupListF();
      } else {
        wx.showToast({
          title: '删除购物车商品失败！',
          image: '../../../static/error.png'
        });
      }
    },

    changeCheck(e) {
      var ids = e.detail.value;
      var list = this.list;
      list.forEach(item => {
        item.checked = false;
      });
      ids.forEach(item => {
        list[item].checked = true;
      });
      this.setData({
        list: list
      });
      this.select_product();
      this.groupListF();
    },

    selectAll(e) {
      var allCheck = this.allCheck;
      var list = this.list;
      this.setData({
        allCheck: !allCheck
      });
      list.forEach(item => {
        item.checked = this.allCheck ? true : false;
      });
      this.setData({
        list: list
      });
      this.select_product();
      this.groupListF();
    },

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

    // 领取优惠券
    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) {
			this.coupons[index].receive = true;
            wx.showToast({
              title: '领取成功'
            });
          } else {
            wx.showToast({
              title: res.message,
              image: '../../../static/error.png'
            });
          }
        } else {
          wx.showToast({
            title: '领取失败',
            image: '../../../static/error.png'
          });
        }
      });
    },

    goLogin() {
      var url = getUrl();
      wx.navigateTo({
        url: '/pages/user/register/register?url=' + url
      });
    },

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

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

    // 购物车领券
    cardDiscount(ids) {
      var wechat_group_id = this.$cookieStorage.get('openGId') || '';
      wx.request({
        url: config.GLOBAL.baseUrl + 'api/shoppingCart/discount',
        method: 'POST',
        data: {
          ids: ids,
          wechat_group_id: wechat_group_id
        },
        success: res => {
          if (res.statusCode == 200) {
            res = res.data;

            if (res.status && res.data) {
              res.data.coupons.forEach(v => v.receive = false);
              // this.setData({
              //   coupons: res.data.coupons,
              //   discounts: res.data.discounts
              // });
			   this.coupons=res.data.coupons;
			   this.discounts=res.data.discounts;
            }
          }
        }
      });
    },

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