<script setup>
	/**
	 * 投流推广
	 */
	import {
		onMounted,
		ref,
		computed,
		reactive,
		getCurrentInstance,
		watch,
		defineExpose,
	} from 'vue';
	import {
		useStore,
	} from 'vuex'
	// 
	import util from '@/common/js/util';
	// api
	import api from '@/api/index.js'
	import {
		onLoad,
		onReady,
		onHide,
		onUnload,
	} from '@dcloudio/uni-app'

	// 顶部
	import apex from '@/components/header/apex.vue';
	// 视频菜单
	import videoMenu from '@/components/index/videoMenu.vue';
	// 
	import payPwd from '@/components/mine/payPwd.vue';

	const {
		proxy
	} = getCurrentInstance()

	const store = useStore()
	// 榴莲果兑换播放量数量
	const durainView = ref(0)
	// 用户信息
	const userinfo = computed(() => store.state.userinfo)
	// 列表数据
	const list = reactive({
		data: [],
		pageSize: 10,
		pageNum: 1,
		total: 0,
	})
	// 表单
	const form = reactive({
		userId: userinfo.value.userId,
		videoId: [],
		reason: '',
		context: '',
		pic: [],
	})
	// 表单
	const apply = reactive({
		author: '',
		mobile: '',
		mail: '',
		address: '',
	})
	// 收藏的视频
	const collectVideo = ref({})
	// 已选择的自己的视频列表id
	const myVideoIds = reactive([])
	// 播放量
	const viewCount = ref('')
	// 播放量消耗的榴莲果
	const viewTotal = computed(() => {
		let total = Number(viewCount.value) || 0
		let count = myVideoIds.length
		if (collectVideo.value.id) count++
		return total * count
	})
	// 已选择的自己视频列表
	const myVideos = computed(() => {
		let result = myVideoIds.map(item => {
			return list.data.find(node => node.id == item) || {}
		})
		return result
	})
	// 已选择的视频id
	const videoIds = computed(() => {
		let result = [...myVideoIds]
		if (collectVideo.value.id) result.push(collectVideo.value.id)
		return result
	})
	// 钱包
	const purse = computed(() => store.state.purse)

	onLoad(() => {
		// 获取列表
		getList()
		// 开启监听
		addListener()
		// 获取果子兑换播放量的比例
		getDurainViews()
		// 获取钱包
		util.getPurse()
	})

	onUnload(() => {
		removeListener()
	})

	// 开启监听
	function addListener() {
		// 选择投流的收藏视频
		uni.$on('selectPushCollectVideo', (item) => {
			collectVideo.value = item
		})
	}

	// 关闭监听
	function removeListener() {
		uni.$off('selectPushCollectVideo')
	}

	// 获取果子兑换播放量的比例
	function getDurainViews() {
		api.durian.getDurainViews({}).then(rs => {
			if (rs.code == 200) {
				// 榴莲果兑换
				durainView.value = rs.data.proportion
				return
			}
			util.alert({
				content: rs.msg,
				showCancel: false,
			})
		})
	}

	// 刷新列表
	function refreshList() {
		list.pageNum = 1
		getList()
	}

	// 获取更多列表
	function getMoreList() {
		if (list.data.length >= list.total) return
		list.pageNum++
		getList()
	}

	// 获取列表
	function getList() {
		// 
		api.video.myWorks({
			query: {
				userId: userinfo.value.id,
				pageSize: list.pageSize,
				pageNum: list.pageNum,
			}
		}).then(rs => {
			if (rs.code == 200) {
				if (list.pageNum == 1) list.data.length = []
				list.data.push(...rs.rows)
				list.total = rs.total
				return
			}
			util.alert({
				content: rs.msg,
				showCancel: false,
			})
		})
	}

	// 展示播放
	function handleShowView() {
		console.log('videoIds', videoIds.value)
		if (videoIds.value.length < 1) {
			util.alert({
				content: "请选择投流视频",
				showCancel: false,
			})
			return
		}
		// 
		proxy.$refs.views.open()
	}

	// 推送视频
	function pushVideo() {
		if (purse.value.fruit <= videoIds.value.length * 10) {
			util.alert({
				content: "榴莲果不足",
				showCancel: false,
			})
			return
		}
		proxy.$refs.views.close()
		proxy.$refs.payPwdRef.open()
	}

	// 完播申请
	function applyVideo() {
		if (videoIds.value.length < 1) {
			util.alert({
				content: "请选择投流视频",
				showCancel: false,
			})
			return
		}

		if (userinfo.value.fruit <= videoIds.value.length * 10) {
			util.alert({
				content: "榴莲果不足",
				showCancel: false,
			})
			return
		}

		api.video.applyVideo({
			data: {
				videoIds: videoIds.value.join(","),
				author: apply.author,
				mobile: apply.mobile,
				address: apply.address,
				mail: apply.mail
			}
		}).then(rs => {
			if (rs.code === 200) {
				proxy.$refs.applyRef.close()
				util.alert('申请成功，请等待后台审核')
				util.getUserinfo()
				return
			}

			util.alert({
				content: rs.msg,
				showCancel: false,
			})
		})
	}

	/**
	 * 确认取消投流
	 * @param {Object} item
	 * @param {Object} index
	 */
	function handleCancel(item, index) {
		util.alert({
			content: `确认取消投流${item.title}`,
		}).then(rs => {
			if (!rs.confirm) return
			collectVideo.value = {}
		})
	}

	// 推流收藏视频
	function pushCollect() {
		link(util.setUrl('/pages/index/dataCenter/pushVideoCollects', {
			ids: collectVideo.value.id,
		}))
	}

	// 跳转
	function link(path) {
		uni.navigateTo({
			url: path
		})
	}

	// 二级密码确认
	function handlePwdConfirm(ev) {
		// 榴莲果交易
		api.durian.consume({
			data: {
				// 更新用户信息
				userId: userinfo.value.id,
				// 交易类型
				transactionType: 5,
				// 榴莲果交易数量
				fruitAmount: viewTotal.value,
				// 交易值
				totalAmount: viewTotal.value,
				// 二级密码
				secondPassword: ev,
				// 视频id
				videoIds: videoIds.value,
			}
		}).then(rs => {
			if (rs.code === 200) {
				util.getPurse()
				uni.navigateBack()
				return
			}

			util.alert({
				content: rs.msg,
				showCancel: false,
			})
		})
	}
</script>

<template>
	<view class="app">
		<apex title="投流推广">
			<template #right>
				<view class="c333 f28" @click="link('/pages/index/dataCenter/pushHistory')">历史推流</view>
			</template>
		</apex>

		<!--  -->
		<view class="first oh mtb30 mlr20 plr20 bfff br10">
			<view class="rows mtb30 c333 f36">
				<view class="col">
					<view class="df aic">
						<view class="">我想投流的视频</view>
						<uni-icons type="bottom" />
					</view>
					<view class="hint mt10 f28">点击选择视频，已选择{{myVideos.length}}个</view>
				</view>

				<view class="line uploadBox">
					<view class="key" @click="$refs.select.open()">选择视频</view>
				</view>
			</view>

			<view class="listBox mtb30" v-if="myVideos[0]">
				<scroll-view scroll-x="true" class="scroll">
					<view class="list df">
						<view class="item oh pr fs0 mr20 br20" v-for="(item,index) in myVideos" :key="index">
							<image class="poster br20" :src="item.coverUrl" mode="aspectFill" />
							<!-- <view class="window pfull"></view> -->
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 须知 -->
			<!-- <view class="notice f28 c666">种了很多榴莲果树 ，大家都来买</view> -->
		</view>

		<view class="second oh mtb30 mlr20 ptb25 plr30 c333 f36 br10 bfff" @click="pushCollect">
			<view class="fmid">
				<view>我想投流Ta的视频</view>
				<uni-icons type="right" color="#666" size="28rpx" />
				<view class="c666 f28">我的收藏</view>
			</view>

			<!-- 限制只能分享别人的视频限制一个 -->
			<view class="collectList" v-if="collectVideo.id">
				<view class="item df mtb30">
					<view class="poster oh pr fs0 mr20 br10">
						<image class="image br10" :src="collectVideo.coverUrl" mode="aspectFill" />
						<!-- <view class="window pfull br10"></view> -->
					</view>

					<view class="f1 df jcsb fdc">
						<view class="f1">
							<view class="f38 b">{{collectVideo.title}}</view>
							<view class="mtb20 c666 f28">{{collectVideo.userNickname}}</view>
							<!-- 如果是商家发布的带链接的视频 增加显示 商家出让佣金 -->
							<view class="cFF9B27 f24" v-if="collectVideo.productId">商家出让佣金 {{collectVideo.commission}}
							</view>
						</view>
						<view class="">
							<view class="btn bar black w200" @click.stop="handleCancel(collectVideo,index)">取消</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 我想要 -->
		<view class="second oh mtb20 ml20 plr20 c333 f36 br10 bfff">
			<view class="title mtb20">我想要</view>

			<view class="list mtb20">
				<view class="item fmid fdc br10" @click="handleShowView">
					<view class="">展示播放量</view>
					<view class="mtb10 c666 f20">无需平台审核</view>
					<view class="button btn black">投流</view>
				</view>

				<view class="item fmid fdc br10" @click="$refs.applyRef.open()">
					<view>完播播放量</view>
					<view class="mtb10 c666 f20">需申请平台审核</view>
					<view class="button btn black">申请</view>
				</view>
			</view>
		</view>

		<view class="fill" style="height: 210rpx;"></view>

		<!-- 填充 -->
		<view class="footerBar footer bfff shadow">
			<view class="hint ptb10 plr30 c333">消耗{{videoIds.length}}*1 榴莲果可提升 {{videoIds.length}}*{{durainView}}+ 展示量
			</view>
			<view class="content rows pt30 plr30">
				<view class="f1 c333 f48">当前拥有{{userinfo.fruit}}榴莲果</view>
				<!-- <view class="btn colourful f1">一键投放</view> -->
			</view>
		</view>
	</view>

	<!-- 二级支付 -->
	<payPwd ref="payPwdRef" :price="viewTotal" unitKey="durian" @confirm="handlePwdConfirm" />

	<!-- 展播量 -->
	<uni-popup ref="views" type="center">
		<view class="viewAlt popMid plr30 bfff">
			<view class="title mt50 mb30 tac">
				<view>展示播放量</view>
			</view>

			<view class="form f28">
				<view class="row mtb20">
					<view class="key">消耗榴莲果投流视频/个</view>
					<view class="value inputBox f1 mt10 plr20">
						<input v-model="viewCount" type="number" placeholder="单个视频消耗榴莲果数量" />
					</view>
				</view>
			</view>

			<view class="c999 f26">总消耗{{viewTotal}}个榴莲果，给{{videoIds.length}}个视频投流</view>

			<view class="btn lg black mt10 mb40" @click="pushVideo">推流</view>
		</view>
	</uni-popup>

	<!-- 申请表单 -->
	<uni-popup ref="applyRef" type="center">
		<view class="applyAlt popMid plr60 c333 f36 bfff">
			<view class="title mt50 mb30 tac">
				<view>完播播放量</view>
				<view class="">消耗10颗榴莲果</view>
			</view>

			<view class="form f28">
				<view class="row rows mtb20">
					<view class="key">视频作者：</view>
					<view class="value inputBox f1 plr20">
						<input v-model="apply.author" type="text" placeholder="请输入视频作者" />
					</view>
				</view>
				<view class="row rows mtb20">
					<view class="key">手机号：</view>
					<view class="value inputBox f1 plr20">
						<input v-model="apply.mobile" type="text" placeholder="请输入手机号" />
					</view>
				</view>
				<view class="row rows mtb20">
					<view class="key">邮箱号：</view>
					<view class="value inputBox f1 plr20">
						<input v-model="apply.mail" type="text" placeholder="请输入邮箱号" />
					</view>
				</view>
				<view class="row rows mtb20">
					<view class="key">地址：</view>
					<view class="value inputBox f1 plr20">
						<input v-model="apply.address" type="text" placeholder="请输入地址" />
					</view>
				</view>
			</view>

			<view class="notice mt30 f20">不论是否申请成功，榴莲果直接销毁</view>
			<view class="btn lg black mt10 mb40" @click="applyVideo">提交申请</view>
		</view>
	</uni-popup>

	<!-- 选择自己的视频 -->
	<uni-popup ref="select" type="bottom">
		<view class="selectAlt popBot df fdc bfff">
			<view class="header rows ptb20 plr20">
				<view class="title plr30 c333 f34">
					<text>作品</text>
					<text class="ml10">{{list.total}}</text>
				</view>

				<view class="fmid c999 f28" @click="refreshList">
					<uni-icons type="refreshempty" color="" />
					<text>刷新</text>
				</view>
			</view>

			<!-- 视频菜单 -->
			<scroll-view scroll-y="true" class="scroll" @scrolltolower="getMoreList">
				<videoMenu :list="list.data" v-model:ids="myVideoIds" mode="checkbox" />
			</scroll-view>
		</view>
	</uni-popup>
</template>

<style lang="scss" scoped>
	// 第一
	.first {
		.hint {
			color: #868686;
		}

		.item {
			width: 220rpx;
			height: 280rpx;
			background-color: #F4F4F4;
		}

		.poster {
			width: 100%;
			height: 100%;
		}

	}

	// 第二
	.second {
		.list {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			grid-gap: 20rpx;

			.item {
				height: 200rpx;
				background-color: #F4F4F4;
			}

			.button {
				padding: 10rpx;
				width: 80rpx;
				font-size: 20rpx;
			}
		}
	}

	// 收藏的视频列表
	.collectList {
		.item {
			.poster {
				height: 288rpx;
				// height: 192rpx;
				width: 162rpx;
				// width: 108rpx;

				.image {
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	// 底部
	.footerBar {
		padding-top: 0;

		.hint {
			background-color: #e2e2e2;
		}
	}

	.applyAlt {
		.notice {
			color: #b4b4b4;
		}
	}

	// 
	.selectAlt {

		.scroll {
			height: 70vh;
		}
	}
</style>