<template>
	<HeaderNav title="优惠在这" :is-back="true" :nav-to-url="navToUrl"></HeaderNav>
	<view class="app-wallpaper" :style="{
		backgroundImage:'url('+staticImage.wallpaperBgImage+')'
		}">

		<view class="capsule-container row">
			<view class="capsule" :class="{active:item.value === couponType,'col-6':(types.length >1),'col-12':(types.length === 1)}" @click="couponTypeToggle(item)" v-for="item in types">
				{{ item.title }}
			</view>
		</view>
		<view class="coupons-list" v-if="type === 'lists'">
			<view v-for="item in couponsList" class="coupons-item-container" :style="{
					backgroundImage:'url('+((item.status > 0)?staticImage.couponsGrayBackground:staticImage.couponsBackground)+')'
					}">
				<view class="coupons-item row">
					<view class="coupons-left ">
						<view class="coupons-big-title-group row">
							<view class="coupons-big-title">
                <u-text :text="item.price" :size="item.price>99?60:90" color="#ffffff" align="center" line-height="90" bold></u-text>
<!--                {{item.price}}-->
              </view>
							<view class="coupons-big-desc">元</view>
						</view>
						<view class="coupons-cause">
							{{item.type_name}}
						</view>
					</view>
					<view class="coupons-right col row">
						<view class=" ">
							<view class="coupons-title col-12">{{item.title}}</view>
							<view class="coupons-desc col-12">
                <text v-if="item.number !== 0 && item.number !== -1">剩余:</text>
                <text v-if="item.number === 0">不限数量</text>
                <text v-if="item.number !== 0 && item.number !== -1">{{item.number}}</text>
                <text v-if="item.number === -1">已领取完</text>
                <text v-if="item.number !== 0 && item.number !== -1">张</text>
              </view>
						</view>
						<view class="coupons-gq " v-show="item.status === 2">
							<image class="img" :src="staticImage.couponsGQ" mode="aspectFill" />
						</view>
						<view class="coupons-gq " v-show="item.status === 1">
							<image class="img" :src="staticImage.couponsUse" mode="aspectFill" />
						</view>
						<view class="coupons-bottom col-12 row">
							<view class="coupons-rule row col" @click="showCoupons(item)">查看使用规则 <u-icon class="arrow-right" size="24rpx" color="#999999" name="arrow-right"></u-icon></view>
							<view class="coupons-button">
								<MzButton
                    title="立即领取"
                    @click="clickCoupons(item)"
                    button-width="145rpx"
                    :button-color="(item.status > 0  || item.number === -1)?'#CACACA':'#4DC3B8'"
                    font-color="#fff"
                    font-size="26rpx"
                    :is-background="false"
                    padding-tb="2rpx"
                    :btn-style="{
                      boxShadow:((item.status > 0  || item.number === -1)?'2rpx -5rpx 0rpx 0rpx rgba(199,199,199,0.35)':'2rpx -5rpx 0rpx 0rpx rgba(77,195,184,0.35)')
                    }"></MzButton>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
    <u-loadmore v-if="type === 'lists'"
                :status="status" fontSize="28"
                color="#ACB4B6"
                line
                line-color="#ACB4B6"
                marginBottom="30" marginTop="30" @loadmore="getCouponsList(++this.page)"/>
    <Draw v-if="type === 'draw'"></Draw>
	</view>
  <uv-popup ref="agreement" mode="bottom" round="20rpx" closeable safeAreaInsetTop safeAreaInsetBottom custom-style="position:relative;">
    <view class="title row" style="position:absolute;justify-content: center;width:100%;top:20rpx;left:0;">
      <view class="value col" style="position: relative;text-align: center;">

        <!--        <u-text text="协议内容" size="38" color="#191919"></u-text>-->
        <view class="" style="position: relative;display:inline-block;">
          <view style="color:#191919;font-size:38rpx;display:inline-block;position: relative;z-index: 2;">使用说明</view>
          <view class="background" style="width:100%;height:50%;position: absolute;bottom:0;left:0;background-color:rgba(227, 191, 119, 0.6);display:inline-block;z-index:1;"></view>
        </view>
      </view>
    </view>
    <view style="padding:30rpx;max-height:700rpx;overflow: auto;" v-if="couponsContent!==''">
      <u-parse :content="couponsContent"></u-parse>
    </view>
  </uv-popup>
  <uv-popup z-index="10000" ref="notOpenPop" mode="center" round="20rpx" closeable safeAreaInsetTop safeAreaInsetBottom custom-style="width:80%;position:relative;">
    <view class="title row" style="position:absolute;justify-content: flex-start;width:100%;top:20rpx;left:0;">
      <view class="value col" style="position: relative;text-align: center;">

        <!--        <u-text text="协议内容" size="38" color="#191919"></u-text>-->
        <view class="" style="position: relative;display:inline-block;">
          <view style="color:#191919;font-size:38rpx;display:inline-block;position: relative;z-index: 2;">提示</view>
          <view class="background" style="width:100%;height:50%;position: absolute;bottom:0;left:0;background-color:rgba(227, 191, 119, 0.6);display:inline-block;z-index:1;"></view>
        </view>
      </view>
    </view>
    <view style="padding:30rpx 30rpx 0;max-height:700rpx;overflow: auto;">
      <view style="height:100rpx;display: flex;align-items: center;justify-content: center;">当前不在活动时间内 </view>
      <view class="row">
<!--        <view class="col-6">-->
<!--          <MzButton title="取消" @click="() => {}"></MzButton>-->
<!--        </view>-->
        <view class="col-12">
          <MzButton title="确认" @click="navTo('/pages/Index/index')" button-color="#4DC3B8" font-color="#fff"></MzButton>
        </view>
      </view>
    </view>
  </uv-popup>
  <uv-popup z-index="10000" ref="notLoginPop" mode="center" round="20rpx" closeable safeAreaInsetTop safeAreaInsetBottom custom-style="width:80%;position:relative;">
    <view class="title row" style="position:absolute;justify-content: flex-start;width:100%;top:20rpx;left:0;">
      <view class="value col" style="position: relative;text-align: center;">

        <!--        <u-text text="协议内容" size="38" color="#191919"></u-text>-->
        <view class="" style="position: relative;display:inline-block;">
          <view style="color:#191919;font-size:38rpx;display:inline-block;position: relative;z-index: 2;">提示</view>
          <view class="background" style="width:100%;height:50%;position: absolute;bottom:0;left:0;background-color:rgba(227, 191, 119, 0.6);display:inline-block;z-index:1;"></view>
        </view>
      </view>
    </view>
    <view style="padding:30rpx 30rpx 0;max-height:700rpx;overflow: auto;">
      <view style="height:100rpx;display: flex;align-items: center;justify-content: center;">当前未登录，是否前往登录 </view>
      <view class="row">
        <view class="col-6" style="padding:0 15rpx;">
          <MzButton title="取消" @click="navTo('/pages/Index/index')"></MzButton>
        </view>
        <view class="col-6" style="padding:0 15rpx;">
          <MzButton title="确认" @click="() => {
            this.navTo('/pages/Login/index');
            this.$refs.notLoginPop.close();
          }" button-color="#4DC3B8" font-color="#fff"></MzButton>
        </view>
      </view>
    </view>
  </uv-popup>
  <!-- <RightNav></RightNav> -->
</template>

<script>
	import {
		imghost
	} from '@/config/host.js'
	import HeaderNav from '@/components/HeaderNav/Index.vue';
	import FooterNav from '@/components/FooterNav/Index.vue';
	import RightNav from '@/components/RightNav/Index.vue';
	import MzButton from '@/components/MzButton/Index.vue';
	import Draw from '@/pages/Draw/index.vue';
  import {userCoupons, userDetail, userExtends} from "../../api/user";
  import {getConfig} from "@/api/other";
  import {couponsList, obtainCoupons} from "@/api/coupons";
  import {drawList} from "@/api/draw";
  import {error} from "@/uni_modules/uv-ui-tools/libs/function";
  import api from "@/utils/functions";
  import {UserCache} from "@/config/config";
	export default {
		components: {
			HeaderNav,
			FooterNav,
			RightNav,
			MzButton,
      Draw
		},
		data() {
			return {
        showModal:false,
				title: 'Hello',
				loading: true,
				staticImage: {
					screenActiveImg: imghost + '/order-screen-active.png',
					orderCardBackground: imghost + '/order-card-background.png',
					wallpaperBgImage: imghost + '/background.png',
					couponsBackground: imghost + '/coupons-bg.png',
					couponsGrayBackground: imghost + '/coupons-gray-bg.png',
					couponsGQ: imghost + '/coupons-gq.png',
					couponsUse: imghost + '/coupons-use.png',
				},
				indexBanner: [{
					image: imghost + '/banner.png',
					url: '',
				}],
				user: {
					avatar: imghost + '/banner.png',
					nickname: '清晨的风',
					coupons: 221,
					id: 88685
				},
				isTop: false,

				petImage: imghost + '/pet_avatar1.jpeg',
				couponsList: [ ],
        type:'lists',
				couponType:2,
        types:[
					{title:'省点银子', value: 2},
				],
				page:1,
				status:'loadmore',
        navToUrl:'',
        couponsContent:'',
        is_open_draw:false,
			}
		},
		onLoad(option) {
      this.type = option.type||'lists'
      this.navToUrl = option.url || ''
      this.couponType = parseInt(option.coupon_type) || 2
		},
    onShareAppMessage() {
      // if(!this.is_open_draw){
      //   return false;
      // }
      return {
        title:'优惠在这',
        path:'/pages/Coupons/index?coupon_type=1&type=draw',
      }
    },
    onShareTimeline() {
      // if(!this.is_open_draw){
      //   return false;
      // }
      return {
        title:'优惠在这',
        path:'/pages/Index/index?coupon_type=1&type=draw',
      }
    },
		methods: {
      getDrawList(){
        drawList().then(data => {
          if(data.code === 200){
            if(data.data.goodslists.length > 0){

              this.types = [
                {title:'省点银子', value: 2},
                {title:'宝藏挖掘机', value: 1},
              ];
            }else {
              if(this.type === 'draw'){
                this.$refs.notOpenPop.open();
              }
            }
          }
        }).catch(err => {
          this.$refs.notLoginPop.open();
        });
      },
      showCoupons(item){
        console.log(item)
        console.log(item.use_info)
          this.couponsContent = item.use_info;
        this.$refs.agreement.open();
      },
      clickCoupons(item){
        if(item.number !== -1){
          obtainCoupons({
            coupons_id:item.id,
            number:1
          }).then(res => {
            api.success('领取成功')
              userExtends().then(res => {
                this.$store.commit('userExtends', UserCache.extSetAndReturn(res.data));
              })
          }).catch(err => {
            api.error(err.msg)
          })
        }
      },
      navTo(url){
        uni.navigateTo({
          url:url
        })
      },
      getCouponsList(page = 1){
				if (this.status === 'nomore'){
					return;
				}else{
					this.status = 'loading';
				}
        couponsList({
          page:page,
					limit:10,
					is_buy:this.couponType
        }).then((res) => {
					let couponsList = res.data.map((row) => {
            let type_name;
            switch (row.type){
              case 1:
                type_name = '满减券';
                break;
              case 2:
                type_name = '折扣券';
                break;
              case 3:
                type_name = '抵扣券';
                break;
            }
						return {
							id:row.id,
							price:parseFloat(row.deduction),
							title:row.title,
							type_name: type_name,
							number: row.number,
							cause:'满'+parseFloat(row.min_price)+'使用',
              status: row.status,
              use_info: row.use_info,
						}
					});
					this.status = couponsList.length < 10 ? 'nomore' : 'loadmore';

					if (page === 1) {
						this.couponsList = couponsList;
						return;
					}
          this.couponsList.push(...couponsList);
        }).catch(err => {
          this.$refs.notLoginPop.open();
        });
      },
			couponTypeToggle(item){
				this.couponType = item.value;
				this.page = 1;
				this.status = 'loadmore';
        if(item.value === 1){
          this.type = 'draw';
          this.is_open_draw = true;
          return;
        }else{
          this.type = 'lists';
          this.is_open_draw = false;
        }
				this.getCouponsList();
			}
		},
		onPageScroll(res) {
			if (res.scrollTop <= 20) {
				uni.$emit('isTop', true);
			} else {
				uni.$emit('isTop', false);
			}
		},
		onReachBottom() {
			this.getCouponsList(++this.page);
		},
		created() {
			// this.pagePadding = (api.navHeight().navPaddingTop +
			// api.navHeight().navHeight + (api.navHeight().headerPadding * 2))
		},
    onShow() {
      this.getCouponsList();
      this.getDrawList();
    }
  }
</script>

<style lang="scss">
	@import './components/index.scss';
</style>