<template>
	<view class="asset_container">
		<view class="asset_refresh_box">
			<view class="refresh_time">
				更新于：{{refreshTime}}
			</view>
			<view class="refresh_btn" @click="refreshClickHandle">
				<image src="/static/images/refresh_icon.png" mode="heightFix" class="refresh_icon"></image>
				<text>刷新</text>
			</view>
		</view>
		<view class="asset_info">
			<view class="asset_item" v-if="metalType==1">
				<view class="asset_title">
					<image src="/static/images/au_icon.png" mode="widthFix" class="title_icon"></image>
					<view class="">
						黄金资产
					</view>
				</view>
				<view class="asset_count">
					<view class="total_count">
						<view class="count_title">
							累计进货
						</view>
						<view class="count_num">
							{{auStock.total || 0}}g
						</view>
					</view>
					<view class="total_count">
						<view class="count_title">
							可用库存
						</view>
						<view class="count_num" :class="{green: Number(auStock.useful)<0}">
							{{auStock.useful || 0}}g
						</view>
					</view>
					<view class="total_count">
						<view class="count_title">
							累计销售
						</view>
						<view class="count_num">
							{{auStock.used || 0}}g
						</view>
					</view>
				</view>
			</view>

			<view class="asset_item" v-if="metalType==2">
				<view class="asset_title">
					<image :src="HTTP_REQUEST_URL_IMG+'pt_icon.png'" mode="widthFix" class="title_icon"></image>
					<view class="">
						铂金资产
					</view>
				</view>
				<view class="asset_count">
					<view class="total_count">
						<view class="count_title">
							累计进货
						</view>
						<view class="count_num">
							{{ptStock.total || 0}}g
						</view>
					</view>
					<view class="total_count">
						<view class="count_title">
							可用库存
						</view>
						<view class="count_num" :class="{green: Number(ptStock.useful)<0}">
							{{ptStock.useful || 0}}g
						</view>
					</view>
					<view class="total_count">
						<view class="count_title">
							累计销售
						</view>
						<view class="count_num">
							{{ptStock.used || 0}}g
						</view>
					</view>
				</view>
			</view>

			<view class="asset_item" v-if="metalType==3">
				<view class="asset_title">
					<image src="/static/images/ag_icon.png" mode="widthFix" class="title_icon"></image>
					<view class="">
						白银资产
					</view>
				</view>
				<view class="asset_count">
					<view class="total_count">
						<view class="count_title">
							累计进货
						</view>
						<view class="count_num">
							{{agStock.total || 0}}g
						</view>
					</view>
					<view class="total_count">
						<view class="count_title">
							可用库存
						</view>
						<view class="count_num" :class="{green: Number(agStock.useful)<0}">
							{{agStock.useful || 0}}g
						</view>
					</view>
					<view class="total_count">
						<view class="count_title">
							累计销售
						</view>
						<view class="count_num">
							{{agStock.used || 0}}g
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="menu">
			<view class="menu_btn" :class="{active: menuType==1}" @click="toggleMenu(1)">
				<view class="menu_title">
					交易记录
				</view>
				<view class="menu_bar">

				</view>
			</view>
			<view class="menu_btn btn_rt" :class="{active: menuType==2}" @click="toggleMenu(2)">
				<view class="menu_title">
					入库审核
				</view>
				<view class="menu_bar">

				</view>
			</view>
		</view>
		<view class="list_filter" v-if="menuType==1">
			<view class="filter_title">

			</view>
			<picker @change="bindPickerChange" :value="cValue" :range="filterRange">
				<view class="filter_btn">
					<image src="/static/images/filter_icon.png" mode="heightFix" class="filter_icon"></image>
					<text>筛选</text>
				</view>
			</picker>
			<!-- <view class="filter_btn" @click="refreshClickHandle">
				<image src="/static/images/filter_icon.png" mode="heightFix" class="filter_icon"></image>
				<text>筛选</text>
			</view> -->
		</view>
		<scroll-view class="asset_list" scroll-y="true" v-show="menuType==1" :lower-threshold='100'
			:scroll-top='recordScrollTop' @scrolltolower="nextPageRecord" @scroll="scrollRecord">
			<view class="list_container">
				<view class="record_card" v-for="(item,index) in recordList" :key="item.id">
					<view class="record_left">
						<view class="record_title">
							<view class="record_name">
								{{item.metalTypeName}}-{{item.typeName}}
							</view>
						</view>
						<view class="record_time">
							{{item.createTime}}
						</view>
					</view>
					<view class="record_right" :class="{green: item.type==0}">
						{{item.type==0?'-':'+'}}{{item.weight}}g
					</view>
				</view>
			</view>
			<view class="noMore" v-if="recordList.length>0&&!recordParams.hasMore">
				到底了
			</view>
			<view class="empty" v-if="!recordList||recordList.length==0">
				暂无数据
			</view>

		</scroll-view>
		<scroll-view class="asset_list" scroll-y="true" v-show="menuType==2" :lower-threshold='100'
			:scroll-top='approveScrollTop' @scrolltolower="nextPageApprove" @scroll="scrollApprove">
			<view class="list_container">
				<view class="record_card" v-for="(item,index) in approveList" :key="item.id">
					<view class="record_left">
						<view class="record_title">
							<view class="record_name">
								{{item.metalType==1?'黄金':item.metalType==2?'铂金':item.metalType==3?'白银':'其他'}}-入库
							</view>
							<view class="record_status"
								:class="item.auditStatus==2?'danger':item.auditStatus==0?'warn':'success'">
								{{item.auditStatus==2?'审核拒绝':item.auditStatus==0?'审核中':'审核通过'}}
							</view>
						</view>
						<view class="record_time reject_reason" v-if="item.auditStatus==2">
							拒绝原因：{{item.rejectReason}}
						</view>
						<view class="record_time">
							{{item.createTime}}
						</view>
					</view>
					<view class="record_right">
						+{{item.restockWeight}}g
					</view>
				</view>
			</view>
			<view class="noMore" v-if="approveList.length>0&&!approveParams.hasMore">
				到底了
			</view>
			<view class="empty empty-1" v-if="!approveList||approveList.length==0">
				暂无数据
			</view>

		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReachBottom
	} from "@dcloudio/uni-app";

	import {
		restockSubmitAPI,
		fetchMerchantMetalBalanceAPI,
		fetchMerchantRecordAPI,
		fetchMerchantRestockListAPI
	} from '@/api/merchant';

	import {
		useImageUpload
	} from "@/hooks/useImageUpload";
	import {
		useToast
	} from "@/hooks/useToast";

	import {
		throttle
	} from '@/uni_modules/uview-plus';
  import { HTTP_REQUEST_URL_IMG } from "@/config/app";


	onLoad((params) => {
		metalType.value = params.type
		console.log("asset_list page =====>  Loaded")
		fetchBalance();
		fetchRecordList();
		fetchApproveList();
	})

	const auStock = ref({
		total: '-',
		useful: '-',
		used: '-',
	})
	const ptStock = ref({
		total: '-',
		useful: '-',
		used: '-',
	})
	const agStock = ref({
		total: '-',
		useful: '-',
		used: '-',
	})
	const cValue = ref(3)
	const filterRange = ref(['出库', '入库', '全部'])

	const refreshTime = ref()

	const metalType = ref(1)

	const menuType = ref(1)

	const recordScrollTop = ref(0)
	const approveScrollTop = ref(0)

	const recordParams = ref({
		page: 1,
		limit: 10,
		hasMore: true,
		type: ''
	})

	const approveParams = ref({
		page: 1,
		limit: 10,
		hasMore: true,
	})

	const recordList = ref([]);

	const approveList = ref([])
	
	
	function scrollRecord(e){
		// console.log(e.detail.scrollTop,recordScrollTop.value)
		// oldScroll1 = e.detail.scrollTop
	}
	
	function scrollApprove(e){
		// console.log(e.detail.scrollTop,approveScrollTop.value)
		// oldScroll2 = e.detail.scrollTop
	}


	/**
	 * 获取当前登录商户金属资产明细
	 */
	function fetchBalance(isRefresh) {
		fetchMerchantMetalBalanceAPI().then(res => {
			console.log(res)
			const {
				data,
				code
			} = res
			console.log(data, code)
			if (isRefresh) {
				uni.showToast({
					title: '刷新成功',
					icon: 'none',
					duration: 800
				})
			}

			if (code === 200 && data.length > 0) {
				refreshTime.value = fetchCurrentTime()

				data.forEach(item => {
					console.log(item);
					switch (item.metalType) {
						case 1:
							auStock.value = {
								total: item.totalIncreaseWeight,
								useful: item.availableStock,
								used: item.totalDecreaseWeight
							}
							break;
						case 2:
							ptStock.value = {
								total: item.totalIncreaseWeight,
								useful: item.availableStock,
								used: item.totalDecreaseWeight
							}
							break;
						case 3:
							agStock.value = {
								total: item.totalIncreaseWeight,
								useful: item.availableStock,
								used: item.totalDecreaseWeight
							}
							break;
						default:
							break;
					}
				})
			}
		}).catch(err => {
			console.log(err);
		})
	}

	function nextPageRecord() {
		console.log("到底了")
		if (!recordParams.value.hasMore) {
			// uni.showToast({
			// 	title: "没有更多了",
			// 	icon: "none",
			// 	duration: 1000
			// })
			return 
		}
		recordParams.value.page += 1;
		fetchRecordList()

	}

	function nextPageApprove() {
		// console.log("到底了")
		if (!approveParams.value.hasMore) {
			// uni.showToast({
			// 	title: "没有更多了",
			// 	icon: "none",
			// 	duration: 1000
			// })
			return 
		}
		approveParams.value.page += 1;
		fetchApproveList()

	}

	function bindPickerChange(e) {
		console.log('picker发送选择改变，携带值为', e.detail.value)
		recordParams.value = {
			type: e.detail.value == 2 ? '' : e.detail.value,
			page: 1,
			limit: 10,
			hasMore: true
		}
		fetchRecordList()
	}

	function fetchRecordList() {
		uni.showLoading({
			title: "加载中"
		})
		fetchMerchantRecordAPI({
			...recordParams.value,
			metalType: metalType.value
		}).then(res => {
			console.log(res);
			uni.hideLoading()
			if (recordParams.value.page == 1) {
				recordList.value = res?.data?.list || [];
				recordScrollTop.value = 1
				setTimeout(()=>{
					recordScrollTop.value = 0
				},100)
			} else {
				recordList.value = recordList.value.concat(res?.data?.list || []);
			}
			recordParams.value.hasMore = res?.data?.totalPage > recordParams.value.page
		}).catch(err => {
			console.log(err)
			try {
				uni.hideLoading()
			} catch (error) {
				//TODO handle the exception
			}
		})
	}

	function fetchApproveList() {
		uni.showLoading({
			title: "加载中"
		})
		fetchMerchantRestockListAPI({
			...approveParams.value,
			metalType: metalType.value
		}).then(res => {
			console.log(res);
			uni.hideLoading()
			if (approveParams.value.page == 1) {
				approveList.value = res?.data?.list || [];
				approveScrollTop.value = 1
				setTimeout(()=>{
					approveScrollTop.value = 0
				},100)
			} else {
				approveList.value = approveList.value.concat(res?.data?.list || []);
			}
			approveParams.value.hasMore = res?.data?.hasNextPage
		}).catch(err => {
			console.log(err)
			try {
				uni.hideLoading()
			} catch (error) {
				//TODO handle the exception
			}
		})
	}

	function toggleMenu(type) {
		menuType.value = type
	}

	function fetchCurrentTime() {
		const now = new Date();
		let year = now.getFullYear(),
			month = now.getMonth() + 1,
			day = now.getDate(),
			hour = now.getHours(),
			min = now.getMinutes(),
			sec = now.getSeconds();

		month = month < 10 ? ('0' + month) : (month)
		day = day < 10 ? ('0' + day) : (day)
		hour = hour < 10 ? ('0' + hour) : (hour)
		min = min < 10 ? ('0' + min) : (min)
		sec = sec < 10 ? ('0' + sec) : (sec)

		return `${year}-${month}-${day} ${hour}:${min}:${sec}`
	}

	function recordClickHandle(type) {
		uni.navigateTo({
			url: `/pages/users/user_asset/record_list/record_list?type=${type}`
		})
	}

	function stockInClickHandle(type) {
		uni.navigateTo({
			url: `/pages/users/user_asset/stock_in/stock_in?type=${type}`
		})
	}

	function refreshClickHandle() {
		throttle(() => {
			fetchBalance(1);
			recordParams.value.page = 1
			recordParams.value.hasMore = true
			approveParams.value.page = 1
			approveParams.value.hasMore = 1
			fetchRecordList()
			fetchApproveList()
		}, 1000)
	}
</script>

<style scoped lang="scss">
	uni-page-body {
		height: 100%;
	}

	.asset_refresh_box {
		width: 750rpx;
		display: flex;
		justify-content: space-between;
		padding: 0 0 0 32rpx;
		height: 76rpx;
		align-items: center;
		// position: absolute;
		// top:0;
		// left: 0;

		background-color: #FEF8E6;

		.refresh_time {
			font-size: 28rpx;
			color: #333;
		}

		.refresh_btn {
			display: flex;
			align-items: center;
			padding: 20rpx 32rpx 20rpx 20rpx;
			font-size: 24rpx;
			line-height: 32rpx;
			color: #F8C008;

			.refresh_icon {
				// width: 32rpx;
				height: 32rpx;
				margin-right: 8rpx;
			}
		}
	}

	.asset_container {
		// padding-top: 92rpx;
		background-color: #F9F7F0;
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: center;

		.asset_info {
			width: 100%;
			padding: 16rpx 16rpx 0;
		}

		.list_filter {
			width: 100%;
			padding: 16rpx 16rpx 0;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.filter_title {
				font-size: 32rpx;
				color: #333;
				font-weight: bold;
			}

			.filter_btn {
				display: flex;
				align-items: center;
				padding: 10rpx 32rpx 10rpx 20rpx;
				font-size: 24rpx;
				line-height: 32rpx;
				color: #F8C008;

				.filter_icon {
					width: 32rpx;
					height: 32rpx;
					margin-right: 8rpx;
				}
			}
		}

		.asset_item {
			width: 100%;
			border-radius: 16rpx;
			background-color: #fff;
			min-height: 200rpx;
			padding: 20rpx;

			.asset_title {
				width: 100%;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				font-size: 32rpx;
				color: #333;
				font-weight: bold;

				.title_icon {
					width: 48rpx;
					height: 48rpx;
					margin-right: 8rpx;
				}
			}

			.asset_count {
				width: 100%;
				padding: 16rpx;
				border-radius: 16rpx;
				background-color: #F9F7F0;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 20rpx;

				.total_count {
					display: flex;
					flex: 1;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					min-width: 160rpx;
					flex-shrink: 0;

					.count_title {
						font-size: 24rpx;
						color: #333;
						margin-bottom: 10rpx;
					}

					.count_num {
						font-size: 40rpx;
						color: #3D3D3D;
						font-weight: bold;
						max-width: 200rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;

						&.green {
							color: #2DAB6C;
						}
					}
				}
			}

			.asset_tips {
				width: 100%;
				height: 80rpx;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				background-color: #FEEAEA;
				border-radius: 16rpx;
				padding: 18rpx;
				font-size: 28rpx;
				line-height: 32rpx;
				color: #F52929;
				margin: 20rpx 0;

				.warn_icon {
					// width: 32rpx;
					height: 32rpx;
					margin-right: 16rpx;
				}
			}

			.asset_btns {
				width: 100%;
				display: flex;
				justify-content: space-between;
				margin-top: 20rpx;

				.record_list {
					width: 330rpx;
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
					color: #333;
					font-size: 28rpx;
					border-radius: 18rpx;
					background-color: rgba(248, 192, 8, 0.10);
				}

				.stock_in {
					width: 330rpx;
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
					color: #333;
					font-size: 28rpx;
					border-radius: 18rpx;
					background-color: #F8C008;

				}
			}
		}

		.asset_list {
			width: 100%;
			background-color: #F9F7F0;
			height: 400rpx;
			flex: 1;
			padding: 16rpx 16rpx 16rpx;

			.list_container {
				padding-bottom: 20rpx;
			}


		}
	}


	.record_card {
		width: 100%;
		display: flex;
		justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 16rpx;

		.record_left {
			margin-right: 20rpx;

			.record_title {
				display: flex;
				justify-content: flex-start;
				align-items: center;
				margin-bottom: 10rpx;

				.record_name {
					font-size: 28rpx;
					color: #333;
					margin-right: 16rpx;
				}

				.record_status {
					height: 40rpx;
					line-height: 40rpx;
					padding: 0 16rpx;
					font-size: 24rpx;
					border-radius: 8rpx;

					&.success {
						background-color: #EAF9F0;
						color: #2DAB6C;
					}

					&.warn {
						background-color: #FFF7EC;
						color: #FDB03C;
					}

					&.danger {
						background-color: #FEEAEA;
						color: #F52929;
					}
				}
			}

			.record_time {
				font-size: 24rpx;
				color: #333;
				margin-top: 10rpx;
			}
			.reject_reason{
				font-size: 28rpx;
				line-height: 34rpx;
				margin-bottom: 10rpx;
			}
		}

		.record_right {
			font-size: 32rpx;
			color: #F52929;
			display: flex;
			align-items: center;

			&.green {
				color: #2DAB6C;
			}
		}
	}

	.menu {
		width: 100%;
		height: 88rpx;
		display: flex;
		margin-top: 20rpx;

		.menu_btn {
			width: 50%;
			background-color: #fff;
			border-radius: 32rpx 0 0 0;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;


			.menu_title {
				font-size: 28rpx;
				color: #333;
			}

			&.active {
				.menu_title {
					color: #F8C008;
					font-weight: bold;
				}

				.menu_bar {
					width: 48rpx;
					height: 4rpx;
					background-color: #F8C008;
					border-radius: 0;
					margin-top: 10rpx;
				}
			}

			&.btn_rt {
				border-radius: 0 32rpx 0 0;
			}
		}
	}
	.empty{
		width: 100%;
		text-align: center;
		padding: 200rpx 0;
		color:#dedede;
		&.empty-1{
			padding-top: 268rpx;
		}
	}
	.noMore{
		width: 100%;
		color:#dedede;
		text-align: center;
		line-height: 40rpx;
		padding-bottom: 20rpx;
	}
</style>