<template>
	<view class="page" :style="{'height':windowHeight}">

		<view class="flex-col" v-if="!equityList">
			<view class="flex-row justify-center">
				<image class="empty" src="/static/imageIcon/empty.png" mode="widthFix"></image>
			</view>
			<view class="emptyText flex-row justify-center">
				<text>暂无内容</text>
			</view>
		</view>

		<scroll-view v-else scroll-y :style="{'height':windowHeight}">
			<view  class="row-list" v-for="(item,index) in equityList" :key="index">
        <view class="flex-row justify-start" @click.stop="showRemark(item)">
          <view class="h-text flex-col justify-center ">
            <view class="money">
              <text>{{item.faceValue}}</text>
            </view>
          </view>

          <view class="h-center-content flex-col justify-around ">
            <view class="h-value">
              <text>{{item.title}}</text>
            </view>
            <view class="title">
              适用项目：{{item.serviceProjectName || ''}}
            </view>
            <view class="title">
              适用门店：{{ item.useStoreDesc || '' }}
            </view>
            <view class="title">
              绑定对象：{{item.serviceObjectName}}
            </view>
            <view class="title">
              结束期限：{{item.effectiveEndTime.substring(0,10)}}
            </view>
          </view>

          <view class=" flex-col justify-center ">
            <image class="h-right-content-img "  :src="item.facePhotoUrl || '/static/logo.png'" mode="aspectFit" @click="magnify(item.facePhotoUrl)"></image>
          </view>
        </view>

        <view class="actionBar flex-row justify-end" >
          <view class="actionBtn renewBtn" v-if="item.isShow" @click.stop="navigateTo(item)">续费</view>
          <view class="actionBtn upgradeBtn" @click.stop="upgrade(item)">升级</view>
        </view>

        <view v-if="showRemarkId == item.id" class="remark" style="text-indent:unset">
          <view v-if="item.unavailableWeeklyTimes || item.unavailableTimeRanges">
            不可用日期:
            <view v-if="item.unavailableWeeklyTimes">{{ parseWeeklyTimes(item.unavailableWeeklyTimes) }}</view>
            <view v-if="item.unavailableTimeRanges">{{ parseTimeRanges(item.unavailableTimeRanges) }}</view>
          </view>
          <view v-if="item.delayEffectiveDays > 0">
            生效时间:
            <text>购买后{{item.delayEffectiveDays}}天生效</text>
          </view>
          <view v-if="item.description !=null">
            使用说明:
            <text>{{ item.description }}</text>
          </view>
          <text v-else class="remarkText">该优惠券暂无使用说明</text>
        </view>
			</view>
		</scroll-view>
		<uni-popup ref="popup">
			<view class="magnifyUrlView">
				<image :src="magnifyUrl" mode="widthFix"></image>
			</view>
		</uni-popup>

		<uni-popup ref="upgradePopup" type="center">
			<view class="upgradePopupView">
				<view class="upgradeTitle">请选择升级活动</view>
				<scroll-view class="upgradeScroll" scroll-y>
					<view class="upgradeItem" v-for="(act,idx) in upgradeActivityList" :key="idx" @click="selectUpgradeActivity(idx)">
						<view class="upgradeItemTitle">{{act.title}}</view>
						<view class="upgradeItemPrice">活动价格：<text class="upgradePrice">{{act.salePrice}}元</text></view>
					</view>
				</scroll-view>
				<view class="upgradeCloseBtn" @click="closeUpgradePopup">取消</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
	import {date} from "@/uni_modules/uv-ui-tools/libs/function/test";

  export default {
		data() {
			return {
        showRemarkId:'',
				magnifyUrl:'',
				windowHeight:'',
				userInfo:{},
				equityList:[],
				upgradeActivityList:[],
				currentUpgradeItem:null,
			};
		},

    computed: {
      // 解析 unavailableWeeklyTimes，将 "3,4,5" 转换为 ["星期二", "星期三", "星期四"]
      parseWeeklyTimes() {
        return function(times) {
          if (!times) return '';
          const arr = times.split(',');
          const weekMap = {
            '1': '星期日',
            '2': '星期一',
            '3': '星期二',
            '4': '星期三',
            '5': '星期四',
            '6': '星期五',
            '7': '星期六'
          };
          return arr.map(item => weekMap[item]).join('、');
        };
      },
      // 解析 unavailableTimeRanges，将 JSON 字符串转换为可读格式
      parseTimeRanges() {
        return function(ranges) {
          if (!ranges) return '';
          try {
            const arr = JSON.parse(ranges);
            return arr.map(item => {
              const begin = item.beginTime?.split?.(' ')?.[0] || '';
              const end = item.endTime?.split?.(' ')?.[0] || '';
              return begin && end ? `${begin} - ${end}` : '';
            }).filter(Boolean).join('；');
          } catch (e) {
            return '';
          }
        };
      }
    },

		onLoad(option) {
			let sysInfo = uni.getSystemInfoSync()
			this.windowHeight =sysInfo.windowHeight - 3 +'px'//除标题栏栏外的屏幕可用高度
			this.userInfo = uni.getStorageSync('userInfo')

			this.myEquityCardList()
		},

		methods: {

      isShow(item){
        if (item.effectiveEndTime){
          let date = new Date(item.effectiveEndTime);
          let now = new Date().getTime();
          const timeDiff = Math.abs(now - date.getTime());
          const ninetyDaysMs = 90 * 24 * 60 * 60 * 1000;
          return timeDiff < ninetyDaysMs;
        }
        return false
      },

      navigateTo(item){
        console.log('+++++++++++++++++++++++++++++++',item)
        if(item.activityId){
          let list = item.activityId.split(',')
          if (list.length == 1){
            uni.navigateTo({
              url:'/orderPages/activityDetail/activityDetail?id=' + item.activityId +'&renewServiceObjectId=' + item.serviceObjectId
            })
          }else {
            uni.navigateTo({
              url:'/orderPages/activityList/activityList?renewServiceObjectId=' + item.serviceObjectId + '&equityCardId=' + item.equityCardId
            })
          }
        }else{
          uni.navigateTo({
            url:'/orderPages/activityList/activityList?renewServiceObjectId=' + item.serviceObjectId
          })
        }

      },

      upgrade(item){
        if (!item.equityCardId){
          uni.showToast({
            title: '当前权益卡暂无可升级活动',
            icon: 'none'
          })
          return
        }
        uni.showLoading({title: '加载中'})
        this.$api.upgradeList(item.equityCardId).then(res=>{
          uni.hideLoading()
          const list = (res && res.data && (res.data.data || res.data.rows)) || []
          if (!list || list.length === 0){
            uni.showToast({
              title: '当前权益卡暂无可升级活动',
              icon: 'none'
            })
            return
          }
          this.currentUpgradeItem = item
          if (list.length === 1){
            this.goUpgradeDetail(list[0], item)
          }else {
            this.upgradeActivityList = list
            this.$refs.upgradePopup.open()
          }
        }).catch(()=>{
          uni.hideLoading()
        })
      },

      selectUpgradeActivity(idx){
        const activity = this.upgradeActivityList[idx]
        console.log(activity, 'activity')
        this.goUpgradeDetail(activity, this.currentUpgradeItem)
        this.closeUpgradePopup()
      },

      goUpgradeDetail(activity, item){
        console.log(activity, item,'activity, item')
        if (!activity || !activity.id){
          return
        }
        let url = '/orderPages/activityDetail/activityDetail?id=' + activity.id + '&upgradeEquityCardId=' + item.id
        if (item.serviceObjectId){
          url += '&renewServiceObjectId=' + item.serviceObjectId
        }
        uni.navigateTo({url})
      },

      closeUpgradePopup(){
        this.$refs.upgradePopup.close()
      },

      showRemark(item) {
        if (this.showRemarkId == item.id) {
          this.showRemarkId = ''

        } else {
          this.showRemarkId = item.id

        }
      },
			magnify(url){
				if (!url){
					return
				}
				this.magnifyUrl = url
				this.$refs.popup.open()
			},

			myEquityCardList(){
				this.$api.myEquityCardList().then(res=>{
					console.log(res)
					this.equityList = res.data.data
          for (let equityListElement of this.equityList) {

            let a = this.isShow(equityListElement)
            console.log(a)
            equityListElement.isShow = this.isShow(equityListElement)
          }
					if (this.equityList){
						this.getImgUrlByBannerOssId(this.equityList)
					}
				})
			},

			// 获取图片
			getImgUrlByBannerOssId(items){
				for(let i = 0; i <items.length; i++) {
					if (items[i].facePhoto){
						this.$api.getImgUrlByOssId({ossId:items[i].facePhoto}).then(res=>{
							console.log('++++++++++++facePhotoUrl+++++++++',res.data.data[0].url.replace(/^http:/, "https:"))
							items[i].facePhotoUrl = res.data.data[0].url.replace(/^http:/, "https:")
							this.$set(this.equityList,i,items[i])
						})
					}
				}
			},

		},
	};
</script>
<style lang="scss" scoped>

	@import '/common/css/common.css';
	@import './index.rpx.scss';

</style>
