<template>
<view id="center">
  <!-- <view class="navbar mx-1px-top">
        <block v-for="(item, index) in tabList" :key="index" >

            <view :id="index" class="navbar-item activity" :hidden="activeIndex != index" :style="'color: ' + config.mainColor" @tap="tabClick">
                <view class="navbar-title">{{item.title}}</view>
            </view>

            <view :id="index" :hidden="activeIndex == index" class="navbar-item" @tap="tabClick">
                <view class="navbar-title">{{item.title}}</view>
            </view>
        </block>
        <view class="navbar-slider" :style="'width: ' + width + 'px; transform: translateX(' + sliderOffset + 'px); -webkit-transform: translateX(' + sliderOffset + 'px); background: ' + config.mainColor"></view>
    </view> -->
    <view class="tab-panel">
        <view class="tab-content" v-if="activeIndex == 0">
			<view v-if="dataList[0] && dataList[0][0] && dataList[0][0].length">
				<view v-for="(items, idx) in dataList[0]" :key="idx" >
				    <view class="coupon" :data-id="item.id" :data-limit="item.usage_limit" @tap="jumpDetailOn" v-for="(item, index) in dataList[0][idx]" :key="index" v-if="item.is_open">
				        <view class="coupon-left" :class="is_coupon != 1 ? 'discount' : ''" :style="'background: ' + config.mainColor">
				            <view class="text-wrap">
				                <view class="text-box">
				                    <view class="text">
				                        <text class="money" v-if="item.action_type.type == 'cash'">￥</text>
				                        <span>{{ item.action_type.value }}</span>
				
				                        <text class="money" v-if="item.action_type.type == 'discount'">折</text>
				                    </view>
				                    <text class="label text">{{ item.label }}</text>
				                </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 class="dot-item">
				
				                </view>
				            </view>
				        </view>
				        <view class="coupon-right">
				            <view class="top">
				                    <!-- <span class="type">
				                        <span v-if="item.channel == 'ec'">商城</span>
				                        <span v-else>门店</span>
				                    </span> -->
				                <text class="info">{{item.title}}</text>
				            </view>
				            <view class="bottom">
				                <view class="bottom-use">
				                    <view class="tiem-box">
				                        <text>{{item.use_start_time}}至{{item.use_end_time}}</text>
				                    </view>
				                    <view v-if="is_coupon == 1 && item.usage_limit !=0">
				                        <view class="btn use" :style="'background: ' + config.mainColor + '; border-color: ' + config.mainColor" :data-code="item.code" :data-index="idx" :data-findex="index" v-if="!item.has_get" @tap.stop="getCoupon">
				                            点击领取
				                        </view>
				                        <view class="btn already" :style="'background: ' + config.mainColor + '; border-color: ' + config.mainColor" v-else :data-id="item.coupon_id" @tap.stop="jumpList">
				                            去使用
				                        </view>
				                    </view>
				
				
				                </view>
				            </view>
				        </view>
				        <view class="cover" v-if="item.usage_limit ==0">
				            <view class="big-circle">
				                <view class="small-circle">
				                    <view :animation="animationData">已领完</view>
				                </view>
				            </view>
				        </view>
				
				    </view>
				</view>
						
			</view>
			<view class="no-list" v-else>
				<i class="iconfont icon-youhuiquan"></i>
				<view>报告主人，这里暂无<span v-if="is_coupon == 1">优惠券~</span><span v-else>促销活动</span></view>
			</view>
		</view>
        <view class="tab-content" v-if="activeIndex == 1">
        <view v-if="dataList[1] && dataList[1][0] && dataList[1][0].length">
			<view v-for="(items, idx) in dataList[1]" :key="idx">
			    <view class="coupon" :data-id="item.id" :data-limit="item.usage_limit" @tap="jumpDetail" v-for="(item, index) in dataList[1][idx]" :key="index" v-if="item.is_open">
			        <view class="coupon-left" :class="is_coupon != 1 ? 'discount' : ''" :style="'background: ' + config.mainColor">
			            <view class="text-wrap">
			                <view class="text-box">
			                    <view class="text">
			                        <text class="money" v-if="item.action_type.type == 'cash'">￥</text>
			                        <span>{{ item.action_type.value }}</span>
			
			                        <text class="money" v-if="item.action_type.type == 'discount'">折</text>
			                    </view>
			                    <text class="label text">{{ item.label }}</text>
			                </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 class="dot-item">
			
			                </view>
			            </view>
			        </view>
			        <view class="coupon-right">
			            <view class="top">
			                    <span class="type">
			                        <span v-if="item.channel == 'ec'">商城</span>
			                        <span v-else>门店</span>
			                    </span>
			                <text class="info">{{item.title}}</text>
			            </view>
			            <view class="bottom">
			                <view class="bottom-use">
			                    <view class="tiem-box">
			                        <text>{{item.use_start_time}}至{{item.use_end_time}}</text>
			                    </view>
			                    <view v-if="is_coupon == 1 && item.usage_limit !=0">
			                        <view class="btn use" :style="'background: ' + config.mainColor + '; border-color: ' + config.mainColor" :data-code="item.code" :data-index="idx" :data-findex="index" v-if="!item.has_get" @tap.stop="getCoupon">
			                            点击领取
			                        </view>
			                        <view class="btn already" :style="'background: ' + config.mainColor + '; border-color: ' + config.mainColor" v-else :data-id="item.id" @tap.stop="jumpDetail">
			                            去使用
			                        </view>
			                    </view>
			
			                </view>
			            </view>
			        </view>
			        <view class="cover" v-if="item.usage_limit ==0">
			            <view class="big-circle">
			                <view class="small-circle">
			                    <view :animation="animationData">已领完</view>
			                </view>
			            </view>
			        </view>
			    </view>
			</view>
			        
		</view>
		<view v-else class="no-list">
			<i class="iconfont icon-youhuiquan"></i>
			<view>报告主人，这里暂无<span v-if="is_coupon == 1">优惠券~</span><span v-else>促销活动</span></view>
		</view>
		</view>
    </view>
    <view class="home" @tap="jumpHome" :style="'background: ' + config.mainColor">
        <i class="iconfont icon--shouye"></i>
        <view>
            首页
        </view>
    </view>
</view>
</template>
<script>
import {pageLogin, getUrl,config} from '@/common/js/utils.js';

export default {
  data() {
    return {
      activeIndex: 0,
      sliderOffset: 0,
      width: 0,
      animationData: {},
      tabList: [{
        title: '线上',
        init: false,
        page: 0,
        more: true
      }, {
        title: '线下',
        init: false,
        page: 0,
        more: true
      }],
      dataList: {
        0: [],
        1: []
      },
      is_coupon: 1,
      // 用于判断是否为优惠券 1：优惠券 0：促销折扣
      config: ''
    };
  },

  onReachBottom(e) {
    var status = this.activeIndex;
    var page = this.tabList[status].page + 1;
    var tabList = `tabList[${status}]`;

    if (this.tabList[status].more) {
      this.queryCouponList(status, page);
    } else {
      wx.showToast({
        image: '../../../static/error.png',
        title: '再拉也没有啦'
      });
    }
  },

  onShow() {
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease'
    });
    this.animation = animation;
    animation.rotate(-30).step();
    this.setData({
      animationData: animation.export()
    });
    wx.getSystemInfo({
      success: res => {
        this.setData({
          width: res.windowWidth / this.tabList.length,
          sliderOffset: res.windowWidth / this.tabList.length * this.activeIndex
        });
      }
    });
  },

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

    if (e.type) {
      this.setData({
        activeIndex: e.type
      });
    }

    ;

    if (e.is_coupon) {
      if (e.is_coupon != 1) {
        wx.setNavigationBarTitle({
          title: '促销折扣中心'
        });
      } else {
        wx.setNavigationBarTitle({
          title: '领券中心'
        });
      }

      this.setData({
        is_coupon: e.is_coupon
      });
    } else {
      var referrerInfo = this.$cookieStorage.get('referrerInfo');

      if (referrerInfo && referrerInfo.extraData && referrerInfo.extraData.is_coupon == 0) {
        wx.setNavigationBarTitle({
          title: '促销折扣中心'
        });
        this.setData({
          is_coupon: 0
        });
      } else {
        wx.setNavigationBarTitle({
          title: '领券中心'
        });
      }
    }

    this.queryCouponList();
  },
  methods: {
    tabClick(e) {
      var status = e.currentTarget.id;
      this.setData({
        sliderOffset: e.currentTarget.offsetLeft,
        activeIndex: status
      });

      if (!this.tabList[status].init) {
        this.queryCouponList(status);
      }
    },

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

    // 跳转详情
    jumpDetailOn(e) {
      var id = e.currentTarget.dataset.id;
      var limit = e.currentTarget.dataset.limit;

      if (limit == 0) {
        return;
      }

      wx.navigateTo({
        url: '/pages/coupon/onDetail/onDetail?id=' + id + '&is_coupon=' + this.is_coupon
      });
    },

    jumpDetail(e) {
      var id = e.currentTarget.dataset.id;
      var limit = e.currentTarget.dataset.limit;

      if (limit == 0) {
        return;
      }

      wx.navigateTo({
        url: '/pages/coupon/offDetail/offDetail?id=' + id + '&is_coupon=' + this.is_coupon
      });
    },

    jumpList(e) {
      var id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/coupon/goods/goods?id=' + id
      });
    },

    // 请求优惠券列表
    queryCouponList(type = 0, page = 1) {
      wx.showLoading({
        title: "加载中",
        mask: true
      });
      var token = this.$cookieStorage.get('user_token') || '';
      this.$http.get({
        api: 'api/discount/list',
        header: {
          Authorization: token
        },
        data: {
          page,
          type,
          is_coupon: this.is_coupon
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            var pages = res.meta.pagination;
            var current_page = pages.current_page;
            var total_pages = pages.total_pages;
			//对象赋值
			this.$set(this.dataList[type],page-1,res.data);
			this.tabList[type].init=true;
			this.tabList[type].page=current_page;
			this.tabList[type].more=current_page < total_pages;
          } else {
            wx.showModal({
              content: res.message || '请求失败',
              showCancel: false
            });
          }
        } else {
          wx.showModal({
            content: res.message || '请求失败',
            showCancel: false
          });
        }

        wx.hideLoading();
      }).catch(rej => {
        wx.hideLoading();
		console.log(rej);
        wx.showModal({
          content: res.message || '请求失败',
          showCancel: false
        });
      });
    },

    // 领取优惠券
    getCoupon(e) {
      var token = this.$cookieStorage.get('user_token');
      var code = e.currentTarget.dataset.code;
      var index = e.currentTarget.dataset.index;
      var findex = e.currentTarget.dataset.findex;

      if (token) {
        this.convertCoupon(code, findex, index);
      } else {
        wx.showModal({
          content: '请先登录',
          showCancel: false,
          success: res => {
            if (res.confirm || !res.cancel && !res.confirm) {
              pageLogin(getUrl());
            }
          }
        });
      }
    },

    // 领取优惠券接口
    convertCoupon(code, findex, index) {
      var token = this.$cookieStorage.get('user_token');
      var activeIndex = this.activeIndex;
      wx.showLoading({
        title: "正在领取",
        mask: true
      });
      this.$http.post({
        api: 'api/coupon/convert',
        header: {
          Authorization: token
        },
        data: {
          coupon_code: code
        }
      }).then(res => {
        wx.hideLoading();

        if (res.statusCode == 200) {
          res = res.data;
          if (res.status) {
			let list = this.dataList[activeIndex][index];
			let item = list[findex];
			item.has_get = true;
			this.$set(this.dataList[activeIndex],index,list);
            wx.showToast({
              title: '领取成功'
            });
			
          } else {
            wx.showToast({
              title: res.message || '领取失败',
              image: '../../../static/error.png'
            });
          }
        } else {
          wx.showToast({
            title: '领取失败',
            image: '../../../static/error.png'
          });
        }
      }).catch(rej => {
		 console.log(rej);
        wx.showToast({
          title: '领取失败',
          image: '../../../static/error.png'
        });
        wx.hideLoading();
      });
    },

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