import { defineStore } from 'pinia'
import { requestChargeInfo, requestGetPayChannel } from '@/api/deposit.js'
import { useI18n } from 'vue-i18n'
import { useAppStore } from './useAppStore'

export const useDepositStore = defineStore({
	id: 'deposit',
	state: () => ({
		chargeInfo: {},
		payChannelInfo: {},
		showDepositClosePopup: false,

		showCrypto: 0,  // 数字货币充值 开关
		showTranfer: 0, // 转账充值 开关
		giftSwitch: 1, // 在线充值 开关
		agentRechargeSwitch: 0, // 代理充值 开关
		rechargeTypes: [],  // 1在线支付  2转账 3代理充值  4 数字货币
		fillOrderSwitch: 0,  // 自主补单开关

		tabList: [],

		agentsV2: [],
		typeA: {},
		typeB: {},
		isTypeB: false,

		rechargeTypeList: [],

		// 在线支付页面数据
		onlinePaymentData: {
			depositAmount: '',
			depositChannel: 1,
			depositMethod: '',
			depositMethodName: '',
			depositMethodSelectItem: {},
			depositMethodList: [],
			rechargeName: '',
			payType: '',
			payMethod: ''
		},
		// 渠道列表
		payType: '',

		// 转账支付页面数据
		transferDeposit: {
			depositAmount: '',
			depositPaymentMethod: 1,
		},

		impsInfo: {},
		impsRechargeList: [],
		upiInfo: {},
		upiRechargeList: [],

		cryptoList: [],
		walletTab: [],
		walletPayList: [],
		awardList: [],
		activeType: 1
	}),
	getters: {
		onlineDepositMax: (state) => {
			if (state.isTypeB && state.typeB.amountList && state.typeB.amountList.length) {
				return state.typeB.amountList[state.typeB.amountList.length - 1]
			} else if (state.typeA.amountList && state.typeA.amountList.length) {
				return state.typeA.amountList[state.typeA.amountList.length - 1]
			} else {
				return 0
			}
		},
		onlineDepositMin: (state) => {
			if (state.isTypeB && state.typeB.amountList && state.typeB.amountList.length) {
				return state.typeB.amountList[0]
			} else if (state.typeA.amountList && state.typeA.amountList.length) {
				return state.typeA.amountList[0]
			} else {
				return 0
			}
		},
		onlineDepositType: (state) => {
			return state.isTypeB ? state.typeB : state.typeA
		}
	},
	actions: {
		changeActiveType(type) {
			this.activeType = type
		},
		changeTab(type) {
			this.changeActiveType(type)
			const pidx = this.onlinePaymentData.depositMethodList.findIndex(item => item.type == type)
			if (pidx !== -1) {
				this.onlinePaymentData.depositMethod = this.onlinePaymentData.depositMethodList[pidx].type
				this.onlinePaymentData.depositMethodName = this.onlinePaymentData.depositMethodList[pidx].name
				this.onlinePaymentData.depositMethodSelectItem = this.onlinePaymentData.depositMethodList[pidx]
				this.onlinePaymentData.rechargeName = this.onlinePaymentData.depositMethodList[pidx].name
				this.onlinePaymentData.payType = this.onlinePaymentData.depositMethodList[pidx].payType?.split(',')?.[0]
				this.payType = this.onlinePaymentData.depositMethodList[pidx].payType
			} else {
				this.onlinePaymentData.depositMethod = ''
				this.onlinePaymentData.depositMethodName = ''
				this.onlinePaymentData.depositMethodSelectItem = {}
				this.onlinePaymentData.rechargeName = ''
				this.onlinePaymentData.payType = ''
				this.payType = ''
			}
		},
		async getChargeInfo() {
			const { t } = useI18n()

			const { code, data } = await requestChargeInfo()
			if (code !== 200) { return {} }
			const chargeInfo = data || {}
			this.chargeInfo = chargeInfo

			this.showCrypto = chargeInfo.showCrypto
			this.showTranfer = chargeInfo.showTranfer
			this.giftSwitch = chargeInfo.giftSwitch
			this.agentRechargeSwitch = chargeInfo.agentRechargeSwitch
			this.fillOrderSwitch = chargeInfo.fillOrderSwitch || 0

			this.agentsV2 = JSON.parse(chargeInfo.agentsV2)
			this.typeA = chargeInfo.typeA
			this.typeB = chargeInfo.typeB
			this.rechargeTypeList = chargeInfo.rechargeTypeList || []
			const bank = this.rechargeTypeList.filter(el => el.type === 1)
			const wallet = this.rechargeTypeList.filter(el => el.type === 2)
			const arr = []
			if(bank.length > 0) {
				arr.push({
					type: bank[0].type,
					label: t("deposit.tab.bank"),
					iconUrl: bank[0]?.iconUrl,
					fuUrl: bank[0]?.fuUrl
				})
			}
			if(wallet.length > 0) {
				arr.push({
					type: wallet[0].type,
					label: t("deposit.tab.wallet"),
					iconUrl: wallet[0]?.iconUrl,
					fuUrl: wallet[0]?.fuUrl
				})
			}
			// if(chargeInfo.showCrypto) {
			// 	arr.push({
			// 		type: 4,
			// 		label: t("deposit.tab.crypto"),
			// 		iconUrl: chargeInfo.cryptoConfig[0]?.iconUrl,
			// 		fuUrl: chargeInfo.cryptoConfig[0]?.fuUrl
			// 	})
			// }
			this.walletTab = arr
			// this.rechargeTypeList.forEach(el => {
			// 	if (el.isDefault === 1) {
			// 		this.onlinePaymentData.depositMethod = el.type
			// 		this.onlinePaymentData.depositMethodName = el.name
			// 		this.onlinePaymentData.depositMethodSelectItem = el
			// 	}
			// })
			this.awardList = this.typeA.amountList.map((item, index) => {
				return {
					amount: item,
					award: this.typeA.giftList[index]
				}
			})
			
			let minAbsFlag = 0
			this.typeA.amountList.forEach(el => {
				const minAbs = Math.abs(el - chargeInfo.defaultIndex)
				if (minAbs < minAbsFlag) {
					minAbsFlag = minAbs
					this.onlinePaymentData.depositAmount = el + ''
				}
				if (minAbsFlag === 0) {
					minAbsFlag = minAbs
					this.onlinePaymentData.depositAmount = el + ''
				}
			})

			const appStore = useAppStore()
			if (appStore.phoneNumberPrefix === '+91') {
				this.computeMethodList()
			} else {
				this.rechargeTypeList.forEach(el => {
					if (el.isDefault === 1) {
						this.onlinePaymentData.depositMethod = el.type
						this.onlinePaymentData.depositMethodName = el.name
						this.onlinePaymentData.depositMethodSelectItem = el
						this.onlinePaymentData.rechargeName = el.name
						this.onlinePaymentData.payType = el.payType?.split(',')[0]
						this.payType = el.payType
					}
				})
			}



			this.cryptoList = chargeInfo.cryptoConfig || []

			if (chargeInfo.cards && chargeInfo.cards.length) {
				chargeInfo.cards.forEach(el => {
					if (el.type === 'imps') {
						this.impsInfo = el
						this.impsRechargeList = el.rechargeItems.split('|')
						this.transferDeposit.depositAmount = this.impsRechargeList.length ? this.impsRechargeList[0] : ''
					} else if (el.type === 'upi') {
						this.upiInfo = el
						this.upiRechargeList = el.rechargeItems.split('|')
						this.transferDeposit.depositAmount = this.impsRechargeList.length ? this.impsRechargeList[0] : ''
					}
				})
			}

			const tabList = []
			if (chargeInfo.rechargeTypes) {
				chargeInfo.rechargeTypes.forEach(el => {
					if (el === 1 && chargeInfo.giftSwitch) {
						tabList.push({
							title: t('deposit.onlinePayment'),
							key: 1,
							badge: ''
						})
					}
					if (el === 2 && chargeInfo.showTranfer) {
						let badge = ''
						if (chargeInfo.transferGift && chargeInfo.transferGiftSwitch) {
							badge = `+${chargeInfo.transferGift * 100}%`
						}
						tabList.push({
							title: t('deposit.transferDeposit'),
							key: 2,
							badge: badge
						})
					}
					if (el === 3 && chargeInfo.agentRechargeSwitch) {
						let badge = ''
						if (chargeInfo.agentRechargeGift && chargeInfo.agentRechargeSwitch) {
							badge = `+${chargeInfo.agentRechargeGift * 100}%`
						}
						tabList.push({
							title: t('deposit.agencyDeposit'),
							key: 3,
							badge: badge
						})
					}
					if (el === 4 && chargeInfo.showCrypto) {
						let badge = ''
						if (chargeInfo.cryptoGift) {
							badge = `+${chargeInfo.cryptoGift * 100}%`
						}
						tabList.push({
							title: t('deposit.crypto'),
							key: 4,
							badge: badge
						})
					}
				})
			}
			this.tabList = tabList

			return this.chargeInfo
		},
		async getPayChannelInfo() {
			const { code, data } = await requestGetPayChannel()
			if (code === 200) {
				this.channelInfo = data || {}
			}
			return this.channelInfo
		},
		computeMethodList() {
			let name = this.onlinePaymentData.rechargeName
			const limit = this.chargeInfo.rechargeTypeLimit || 0
			const amount = Number(this.onlinePaymentData.depositAmount || 0)

			let canChoose = false
			if (this.rechargeTypeList.length > 0) {
				let depositMethodList = this.rechargeTypeList
				depositMethodList.forEach(el => {
					el.disable = true
					if (el.amountRange) {
						const arr = JSON.parse(el.amountRange)
						const min = arr[0]
						const max = arr[1]
						if (amount >= min && amount <= max) {
							el.disable = false
							canChoose = true
						}
					}
				})
				// pay order by showWeight
				// if (amount > limit) {
				// 	depositMethodList.sort((a, b) => {
				// 		return a.showWeight - b.showWeight
				// 	})
				// } else {
				// 	depositMethodList.sort((a, b) => {
				// 		return a.showOffset - b.showOffset
				// 	})
				// }
				// always first element
				let idx = 0
				const filtered = depositMethodList.filter(item => !item.disable)
				// const len = filtered.findIndex(item => item.name === name)
				// if (len !== -1) {
				// 	idx = len
				// }
				
				this.onlinePaymentData.depositMethodList = depositMethodList
				if (filtered.length && canChoose) {
					const obj = filtered[idx]
					this.onlinePaymentData.depositMethod = obj.type
					this.onlinePaymentData.depositMethodName = obj.name
					this.onlinePaymentData.depositMethodSelectItem = obj
					this.onlinePaymentData.rechargeName = obj.name
					this.onlinePaymentData.payType = obj.payType?.split(',')[0]
					this.payType = obj.payType
				} else {
					this.onlinePaymentData.depositMethod = ''
					this.onlinePaymentData.depositMethodName = ''
					this.onlinePaymentData.depositMethodSelectItem = {}
					this.onlinePaymentData.rechargeName = ''
					this.onlinePaymentData.payType = ''
					this.payType = ''
				}
			}
		}
	}
})