import { defineStore } from 'pinia'
import { getPromoListApi, requestCanGiftCode, requestGetSpinActivityData } from '@/api/promo.js'
import { useUserStore } from '@/store/useUserStore'
import { useAppStore } from '@/store/useAppStore'
import { arrSortByKey } from "@/module/utils/sortArray.js"
import { getCurrentDateStr } from '@/module/formatter/date-formatter.js'
import toast from '../module/toast/toast'

const jiliStoreKey = 'APP_PROMO_JILI_STORE_KEY'

export const usePromoStore = defineStore({
	id: 'promo',
	state: () => ({
		promoList: [],
		promoPopupList: [],
		
		community: {
			content: {},
			rewordBonus: 0,
			joinNowLink: ''
		},
		jili: {
			canGet: 0,
			giftCode: null,
			title: '',
			content: {},
			gameList: []
		},
		signup: {
			title: '',
			content: {},
		},
		betrankList: [],
		firstdepositList: [],
		inviterank: {
			title: '',
			content: {},
			tabIndex: 0,
			rulsTabIndex: 0,
			teamTabIndex: 0,
			startTime: '',
			endTime: '',
			isActivityEnd: true,
			uptoRewards: 0,
			topRewards: 0
		},
		turnplate: {
			isOpen: false,
			isNew: false,
			id: 0,
			tabIndex: 0,
			totalRemainTimes: 0,
			remainTimes: 0,
			title: '',
			content: {},
			spinList: [],
			rules: [],
			activityRewardList: []
		},
		rechargeContent: [],
		detailList: [],
	}),
	getters: {
		isShowTurnplate: (state) => {
			return (state.turnplate.isOpen && state.turnplate.isNew) || (state.turnplate.totalRemainTimes > 0)
		}
	},
	actions: {
		async getPromoList () {
			const { code, data } = await getPromoListApi()
			console.log('promoList', data);
			
			if (code !== 200 || !data) { return [] }
			
			const timestamp = new Date().getTime()
			// filter(item => item.displayType == 1).
			let promoList = data.filter((item) => {
				let startTime = new Date(item.displayBeginTime.replace(/-/g, '/')).getTime()
				let endTime = new Date(item.displayEndTime.replace(/-/g, '/')).getTime()
				// let startTime = new Date(item.validBeginTime.replace(/-/g, '/')).getTime()
				// let endTime = new Date(item.validEndTime.replace(/-/g, '/')).getTime()
				return startTime < timestamp && endTime > timestamp
			})
			const rechargeAct = promoList.find(item => item.jumpUrl == 'module:recharge')
			this.rechargeAct = rechargeAct
			const userStore = useUserStore()
			promoList = promoList.filter((item, index) => {
				if (item.jumpUrl === 'module:bigvip') {
					if (userStore.serviceInfo.dedicatedCS > 0 || userStore.vipInfo.vipLevel < userStore.minVipLevel) {
						return false
					}
				}
				return true
			})
			
			// 弹窗列表
			let promoPopupList = []
			promoList.forEach(el => {
				if (!!el.content) {
					const content = JSON.parse(el.content)
					el.content = content
					
					if (content.popup && content.popup !== 'community') {
						promoPopupList.push(content)
					}
				}
			})
			arrSortByKey(promoPopupList, "window_sort")
			
			promoPopupList.forEach((item) => {
			  if (item.popup == "firstdeposit") {
			    let arr = []
			    item.recharge_items.forEach((i) => {
			      arr.push({
			        amount: i[0],
			        reward: i[2],
			      })
			    })
			    this.firstdepositList = arr
			  }
			  if (item.popup == "betrank") {
			    let arr = []
			
			    item.ranks[0].rank_awards.forEach((i, index) => {
			      let listItem = {
			        rank: "",
			        day: "",
			        week: "",
			        month: "",
			      }
			      if (i[0] == i[1]) {
			        listItem.rank = i[0]
			      } else {
			        listItem.rank = i[0] + "-" + i[1]
			      }
			      listItem.day = i[2]
			      listItem.week = item.ranks[1].rank_awards[index][2]
			      listItem.month = item.ranks[2].rank_awards[index][2]
			      arr.push(listItem)
			    })
			    this.betrankList = arr
			  }
			  if (item.popup == "community") {
			  }
			  if (item.popup == "signin") {
			  }
			})
			
			
			// community
			const communityData = promoList.find((el) => {
			  return el.jumpUrl === "module:community"
			})
			if (communityData && communityData.content) {
			  const content = communityData.content
				this.community.content = content
			  this.community.rewordBonus = content.bonus || 0
			  this.community.joinNowLink = content.customer_service || "";
			}
			
			// 注册奖励
			const signupData = data.find(el => {
				return el.jumpUrl === "module:task"
			})
			if (signupData && signupData.content) {
				this.signup.title = signupData.name
				this.signup.content = signupData.content
				this.signup.descList = signupData.content.tasks
			}
			
			// jili
			const jiliData = promoList.find(el => {
				return el.jumpUrl === "module:jilipromo"
			})
			if (jiliData && jiliData.content) {
				const tasks = jiliData.content
				this.jili.title = jiliData.name || ''
				this.jili.content = jiliData.content
				this.jili.gameList = jiliData.content.games || []
			}
			
			// spin
			const turnplateData = promoList.find(el => {
				return el.jumpUrl === "module:spin"
			})
			if (turnplateData && turnplateData.content) {
				const tasks = turnplateData.content
				this.turnplate.title = turnplateData.name || ''
				this.turnplate.content = turnplateData.content
				this.turnplate.spinList = turnplateData.content.spin_award || []
				this.turnplate.rules = turnplateData.content.desc || []
				this.turnplate.id = turnplateData.id
					
				this.turnplate.isOpen = true
				this.getSpinActivityData()
			}
			
			// inviterank
			const inviterankData = promoList.find(el => {
				return el.jumpUrl === "module:inviterank"
			})
			if (inviterankData && inviterankData.content) {
				const tasks = inviterankData.content
				if (tasks && tasks.config) {
					tasks.config.forEach(el => {
						const min = el.rank_range[0]
						const max = el.rank_range[1]
						if (min === max) {
							el.rankRangeShow = min
						} else {
							el.rankRangeShow = `${min}-${max}`
						}
					})
					if (tasks.headConfig && tasks.headConfig.length) {
						const max = tasks.headConfig[tasks.headConfig.length - 1].award
						this.inviterank.uptoRewards = max / tasks.headAwardInviteCount
					}
					if (tasks.config && tasks.config.length) {
						this.inviterank.topRewards = tasks.config[0].award
					}
				}
				this.inviterank.title = inviterankData.name || ''
				this.inviterank.content = tasks
				this.inviterank.startTime = inviterankData.validBeginTime || ''
				this.inviterank.endTime = inviterankData.validEndTime || ''
				const currentTimeInt = (new Date()).getTime()
				const endTimeInt = (new Date(this.inviterank.endTime)).getTime()
				this.inviterank.isActivityEnd = currentTimeInt > endTimeInt ? true : false
			}
			
			const appStore = useAppStore()
			if (appStore.phoneNumberPrefix === '+91' && jiliData) {
				const giftCodeData = await this.getCanGiftCode()
				if (giftCodeData) {
					promoPopupList = [giftCodeData].concat(promoPopupList)
				}
			}
			
			promoList = promoList.filter((item, index) => {
				return item.displayType != 0
			})
			
			this.promoPopupList = promoPopupList
			this.promoList = promoList
			
			return promoList
		},
		async getCanGiftCode () {
			const { code, data } = await requestCanGiftCode({
				claimCode: 0
			})
			if (code !== 200 || !data) { return null }
			this.jili.canGet = data.canGet || 0
			this.jili.giftCode = data.giftCode || ''
			
			const storeDate = uni.getStorageSync(jiliStoreKey)
			const today = getCurrentDateStr(8)
			if (storeDate && storeDate === today) {
				return null
			}
			if (data.canGet === 1 && data.giftCode) {
				return {
					popup: 'giftCode',
					canGet: this.jili.canGet,
					giftCode: this.jili.giftCode
				}
			}
			return null
		},
		async getGiftCode () {
			const { code, data } = await requestCanGiftCode({
				claimCode: 1
			})
			if (code !== 200 || !data) { return null }
			this.jili.canGet = data.canGet || 0
			this.jili.giftCode = data.giftCode || ''
			return true
		},
		setJiliNoShowToday () {
			const today = getCurrentDateStr(8)
			uni.setStorageSync(jiliStoreKey, today)
		},
		async getSpinActivityData () {
			const { code, data } = await requestGetSpinActivityData()
			if (code !== 200) { return null }
			this.turnplate.activityRewardList = data ||[]
			
			let totalRemainTimes = 0
			let isNew = false
			this.turnplate.activityRewardList.forEach(el => {
				totalRemainTimes = totalRemainTimes + el.remainTimes
				if (el.finishStatus === 0 && el.remainTimes === 0) {
					isNew = true
				}
			})
			this.turnplate.isNew = isNew
			this.turnplate.totalRemainTimes = totalRemainTimes
			return true
		}
	}
})
