<template>
	<view class="container">
		<up-navbar class="inde-nav-bar" :bgColor="navBgColor">
			<template #left>
				<view class="back_extend" @click="handleFunctionClick('/pages/index/index','我的商城')">
					<uni-icons type="left" size="22" color="#333"></uni-icons>
					 <view class="">
					 	返回商城
					 </view>
				</view>
			</template>
			<template #center>
				<view class="page-title">门店主页</view>
			</template>
		</up-navbar>
		<!-- 顶部用户信息 -->
		<view class="user-header jianbianBG">
			<view class="user-info">
				<view class="user-main">
					<view>
						<image class="avatar" :src="isHttpsImage(merchantInfo?.merchantLogo)"></image>
					</view>
					<view class="user-detail">
						<view class="name-vip" v-if="appStore.isLogin">
							<text class="name">{{ merchantInfo?.merchantName }}</text>
							<view class="phone">{{hidePhoneNumber(merchantInfo?.merchantPhone)}}</view>
							<!--              <image class="vip-tag" v-if="appStore.$userInfo?.svip" mode="widthFix" src="@/static/images/setting/vip.png">VIP</image>-->
						</view>
						<view class="name-vip" v-else @click="navigateTo('/pages/users/login/index')">
							<text class="name">未登录</text>
						</view>

						<!--            <text class="vip-expire" v-if="appStore.$userInfo?.svip">到期时间：{{ appStore.$userInfo?.svipExpireTime }}</text>-->
					</view>
				</view>
				<view class="btn-content" @click="handleEdit()">
					<image class="setting" :src="HTTP_REQUEST_URL_IMG+'setting.png'" mode="widthFix"></image>
					<text class="btn-text">编辑资料</text>
				</view>
			</view>
		</view>

		<!-- 经营概况 -->
		<view class="wallet-section">
			<view class="section-header">
				<text class="section-title">经营概况</text>
			</view>

			<view class="business">
				<view class="business-item" v-for="business in businessOverview" :key="business.name">
					<view class="business-num">
						<text>{{business.num}}</text>
					</view>
					<text class="business-name">{{ business.name }}</text>
				</view>
			</view>
		</view>
		<!-- 订单状态 -->
		<view class="order-section">
			<view class="section-header">
				<text class="section-title">我的订单</text>
				<view class="more" @click="viewAllOrders">全部订单<uni-icons style="margin-left: 10rpx;" type="right"
						size="16" color="#666666"></uni-icons></view>
			</view>

			<view class="order-status">
				<view class="status-item" v-for="order in orderStatus" :key="order.name" @click="viewOrders(order.id)">
					<view class="status-icon">
						<image class="img" :src="order.src" mode="widthFix"></image>
					</view>
					<text class="status-name">{{ order.name }}</text>
				</view>
			</view>
		</view>

		<!-- 日常经营 -->
		<view class="common-functions">
			<view class="section-header">
				<text class="section-title">日常经营</text>
			</view>

			<view class="functions">
				<template v-for="func in commonFunctions" :key="func.name">
					<view class="function-item" @click="handleFunctionClick(func.pageUrl,func.name)" v-if="func.show">
						<view class="function-icon">
							<image class="img" :src="func.src" mode="widthFix"></image>
						</view>
						<text class="function-name">{{ func.name }}</text>
					</view>
				</template>

			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		watch,
		computed
	} from 'vue'
	import {
		onLoad,
		onShow,
		onPageScroll
	} from "@dcloudio/uni-app";
	import UniIcons from "../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
	import {
		isHttpsImage
	} from "@/utils/util";
	import {
		useAppStore
	} from "@/stores/app";
	import {
		useToast
	} from "@/hooks/useToast";
	import {
		merchantSalesSummary
	} from "@/api/merchant.js";
	import {
		toLogin
	} from "@/libs/login.js";
	import {
		HTTP_REQUEST_URL_IMG
	} from "@/config/app";
	import {
		footprintScan
	} from "@/api/merchant.js";

	const appStore = useAppStore();
	const {
		Toast
	} = useToast();
	const isLogin = appStore.isLogin;
	const showIcons = ref(false);
	const wxConfig = ref({});
	const tradeList = ref([]);
	const useList = ref([]);
	const wdsyShow = ref(false);
	const kcglShow = ref(false);

	const navBgColor = ref('rgba(255,255,255,0)');

	// 经营概况
	const businessOverview = ref([{
			name: '在售商品数',
			num: 123
		},
		{
			name: '待发货订单',
			num: 123
		},
		{
			name: '累计订单量',
			num: 123
		},
		{
			name: '累计销售额（元）',
			num: 123.00
		}
	])
	// 主要功能列表
	const mainFunctions = ref([{
			src: `${HTTP_REQUEST_URL_IMG}setting/mailiao.png`,
			name: '买料',
			pageUrl: '/pages/users/vault/buy?type=buygold'
		},
		{
			src: `${HTTP_REQUEST_URL_IMG}setting/mailiao2.png`,
			name: '卖料',
			pageUrl: '/pages/users/vault/storeMetal/index?type=soldgold'
		},
		{
			src: `${HTTP_REQUEST_URL_IMG}setting/cunliao.png`,
			name: '存料',
			pageUrl: '/pages/users/vault/storeMetal/goldBullionStock?type=savegold'
		},
		{
			src: `${HTTP_REQUEST_URL_IMG}setting/tiliao.png`,
			name: '提料',
			pageUrl: '/pages/users/vault/storeMetal/metalExchange?type=materialdeduction'
		}
	])

	// 订单状态
	const orderStatus = ref([{
			src: `${HTTP_REQUEST_URL_IMG}setting/daifukuan.png`,
			name: '待付款',
			id: 0
		},
		{
			src: `${HTTP_REQUEST_URL_IMG}setting/daifahuo.png`,
			name: '待发货',
			id: 1
		},
		{
			src: `${HTTP_REQUEST_URL_IMG}setting/daishouhuo.png`,
			name: '待收货',
			id: 2
		},
		{
			src: `${HTTP_REQUEST_URL_IMG}setting/tuikuan.png`,
			name: '退款/换货',
			id: 5
		},
		{
			src: `${HTTP_REQUEST_URL_IMG}setting/yiwancheng.png`,
			name: '已完成',
			id: 4
		},
	])
	// 常用功能

	const commonFunctions = computed(() => {
		const baseFunctions = [{
				src: `${HTTP_REQUEST_URL_IMG}setting/fabu.png`,
				name: '发布商品',
				pageUrl: '/pages/merchantCenters/postInformation',
				show: true
			},
			{
				src: `${HTTP_REQUEST_URL_IMG}setting/shangpin.png`,
				name: '商品管理',
				pageUrl: '/pages/merchantCenters/productManagement',
				show: true
			},
			{
				src: `${HTTP_REQUEST_URL_IMG}setting/kucun.png`,
				name: '库存管理',
				pageUrl: '/pages/users/user_asset/asset_info/asset_info',
				show: !kcglShow.value
			},
			{
				src: `${HTTP_REQUEST_URL_IMG}setting/jinqian.png`,
				name: '我的收益',
				pageUrl: '/pages/users/vault/wallet',
				show: wdsyShow.value
			},
			{
				src: `${HTTP_REQUEST_URL_IMG}setting/kabao.png`,
				name: '卡包管理',
				pageUrl: '/pages/users/card_page/index',
				show: !kcglShow.value
			},
			{
				src: `${HTTP_REQUEST_URL_IMG}setting/mendian.png`,
				name: '门店推广',
				pageUrl: '/pages/users/my_merchant/index',
				show: true
			},
			{
				src: `${HTTP_REQUEST_URL_IMG}setting/dianpu.png`,
				name: '我的商城',
				pageUrl: `/pages/index/index`,
				show: true
			},
		];

		// 根据 show 值过滤
		return baseFunctions.filter((func) => func.show);
	});
	const params = ref({
		page: 1,
		limit: 10,
	});
	const merchantInfo = ref({})


	// 页面加载
	onShow(() => {
		console.log(appStore.userInfo)
		kcglShow.value = appStore?.$wxConfig?.storeAuditModeEnabled;
		merchantInfo.value = appStore.userInfo.merchant;
		if (appStore.merchantId || appStore.userInfo?.merchant?.id) {
			wdsyShow.value = true;
		} else {
			wdsyShow.value = false;
		}
		getMerchantSalesSummary()
	})

	onPageScroll((e) => {
		if (e.scrollTop > 0) {
			navBgColor.value = '#ffe079';
		} else {
			navBgColor.value = 'rgba(252,255,255,0)';
		}
	})

	// 编辑资料
	const editProfile = () => {
		uni.showToast({
			title: '编辑资料',
			icon: 'none'
		})
	}

	// 经营状况
	const getMerchantSalesSummary = async () => {
		let obj = {
			merchantId: parseInt(merchantInfo.value.id)
		}
		const {
			data
		} = await merchantSalesSummary(obj);

		businessOverview.value[0].num = data.onSaleProductCount;
		businessOverview.value[1].num = data.toBeShippedOrderCount;
		businessOverview.value[2].num = data.totalOrderCount;
		businessOverview.value[3].num = formatMoney(data.totalSalesAmount);
	}
	// 功能点击
	const handleFunctionClick = (url, name) => {
		if (!url) return;
		if (name == '库存管理' || name == '卡包管理'|| name == '我的收益') {
			goDetail(url);
		} else if (name == '我的商城') {
			console.log(appStore.userInfo.merchant.id)
			let obj = {
				merchantId: appStore.userInfo.merchant.id,
				userId: appStore.userInfo.userId
			}
			footprintScan(obj).then(()=>{
				appStore.userInfo.lastVisitedMerchantId = appStore.userInfo.merchant.id;
				appStore.setIndexRefersh(true)
				appStore.USERINFO();
				uni.switchTab({
					url
				})
			})
			
		} else {
			uni.navigateTo({
				url
			});
		}

	}
	const goDetail = (url) => {
		console.log('url', url);
		const webviewPageUrl = `/pages/webview/index?path=${url}`;
		uni.navigateTo({
			url: webviewPageUrl,
			fail: (err) => {
				console.error("跳转到webview页面失败：", err);
				uni.showToast({
					title: "跳转失败，请重试",
					icon: "none",
					duration: 1500,
				});
			},
		});
	};
	// 查看商家
	const viewStore = (store) => {
		if (!store.merchantId) {
			return;
		}
		uni.navigateTo({
			url: "/pages/merchant/index?merchantId=" + store.merchantId
		});
	}

	// 查看全部订单
	const viewAllOrders = () => {
		uni.navigateTo({
			url: "/pages/order_list/index"
		});
	}

	// 查看订单
	const viewOrders = (status) => {
		uni.navigateTo({
			url: "/pages/order_list/index?status=" + status
		});
	}
	const navigateTo = (url) => {
		if (!url) return;
		uni.navigateTo({
			url
		});
	};
	// 用户面板事件处理
	function handleEdit() {
		// console.log("编辑资料");
		uni.navigateTo({
			url: "/pages/users/personal_info/personal_info"
		});
	}
	// 手机号隐藏中间4位
	function hidePhoneNumber(phone) {
		if (!phone || phone.length !== 11) return phone;
		return phone.substring(0, 3) + '****' + phone.substring(7);
	}

	function formatMoney(value) {
		// 处理非数字情况
		if (isNaN(value)) {
			return '0.00';
		}

		// 转换为数字并保留两位小数
		const num = parseFloat(value);
		if (isNaN(num)) {
			return '0.00';
		}

		// 处理负数
		const absoluteValue = Math.abs(num);
		const roundedValue = Math.round(absoluteValue * 100) / 100;
		const fixedValue = roundedValue.toFixed(2);

		return num < 0 ? `-${fixedValue}` : fixedValue;
	}
</script>

<style scoped lang="scss">
	
	.back_extend{
		display: flex;
		justify-content: flex-start;
		align-items: center;
		color: #333;
		font-size: 28rpx;
	}
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 180rpx;
	}

	/* 顶部用户信息 */
	.user-header {
		height: 600rpx;
		//background-image: url("https://sb-admin.oss-cn-shenzhen.aliyuncs.com/shuibei-mini/new-mini/jianbianBG.png");
		background-size: 100% 100%;
		padding: 180rpx 20rpx 20rpx;
		color: #fff;
		border-radius: 0 0 20rpx 20rpx;
		box-sizing: border-box;
	}

	.user-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.user-main {
		display: flex;
		align-items: center;
	}

	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		background-color: #fff;
		margin-right: 30rpx;
	}

	.name-vip {
		//display: flex;
		//align-items: center;
		//margin-bottom: 16rpx;
	}

	.name {
		font-size: 32rpx;
		color: #333;
	}

	.phone {
		font-size: 28rpx;
		color: #666666;
		margin-top: 16rpx;
	}

	.vip-tag {
		width: 100rpx;
		margin-left: 16rpx;
	}

	.vip-expire,
	.login-tip {
		font-size: 28rpx;
		color: #666;
	}

	.btn-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.setting {
			width: 40rpx;
			height: 40rpx;
		}

		.btn-text {
			font-size: 24rpx;
			color: #333;
			line-height: 1.5;
		}
	}

	/* 会员开通提示 */
	.vip-promote {
		height: 108rpx;
		width: 100%;
		height: 108rpx;
		padding: 0 30rpx;
		box-sizing: border-box;

		.vipBG {
			width: 100%;
			height: 100%;
			border-radius: 48rpx 48rpx 0 0;
		}

		.vip-text {
			margin-top: -108rpx;
			display: flex;
			width: 100%;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			box-sizing: border-box;

			.title {
				font-size: 28rpx;
				color: #BDAD8E;
				display: flex;
				justify-content: flex-start;
				align-items: center;

				.vipIcon {
					width: 70rpx;
					margin-right: 10rpx;
				}

				.bigText {
					font-size: 32rpx;
					color: #FACD8D;
					margin: 0 10rpx;
				}
			}

			.open-vip {
				width: 144rpx;
				height: 60rpx;
				line-height: 60rpx;
				font-size: 24rpx;
				color: #5D3D03;
				background: linear-gradient(270deg, #FEE2A3 0%, #FDEBCC 100%);
				border-radius: 16rpx 16rpx 16rpx 16rpx;

				.bofang {
					width: 24rpx;
					margin-left: 10rpx;
				}
			}
		}
	}

	.desc {
		font-size: 22rpx;
		opacity: 0.9;
	}

	/* 钱包余额 */
	.wallet-section {
		background: #fff;
		margin: -280rpx 20rpx 20rpx;
		border-radius: 24rpx;
		padding: 30rpx;
	}

	.wallet-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

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

	.transaction-detail {
		color: #666;
		font-size: 24rpx;
		display: flex;
		align-items: center;
	}


	.balance {
		font-size: 48rpx;
		font-weight: bold;
		text-align: center;
		margin: 10rpx 0;
		color: #333;
	}

	.assets {
		display: flex;
		justify-content: space-between;
		margin-top: 40rpx;
	}

	.asset-item {
		text-align: center;
		flex: 1;
	}

	.asset-name {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 16rpx;
		display: block;
	}

	.asset-amount {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		display: block;
	}

	.wallet-actions {
		display: flex;
		justify-content: space-between;
		margin-top: 50rpx;
	}

	.wallet-btn {
		flex: 1;
		text-align: center;
		height: 88rpx;
		line-height: 88rpx;
		margin: 0 10rpx;
		border-radius: 16rpx;
		font-size: 32rpx;
	}

	/* 功能入口 */
	.function-grid {
		background: #fff;
		margin: 30rpx;
		border-radius: 24rpx;
		padding: 40rpx;
	}

	.functions {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 40rpx;
		margin-top: 40rpx;
	}

	.function-item {
		text-align: center;
	}

	.function-icon {
		.img {
			width: 60rpx;
			height: 60rpx;
		}
	}

	.function-name {
		font-size: 24rpx;
		color: #333;
	}

	.business {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		margin-top: 40rpx;
	}

	.business-item {
		text-align: center;
		margin-bottom: 30rpx;
	}

	.business-num {
		color: #333333;
		font-size: 40rpx;
		font-weight: bold;
	}

	.business-name {
		color: #333333;
		font-size: 24rpx;
	}

	/* 最近访问 */
	.recent-visit,
	.order-section,
	.common-functions {
		background: #fff;
		margin: 20rpx;
		border-radius: 16rpx;
		padding: 30rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.section-title {
		font-size: 32rpx;
		color: #333;
	}

	.more {
		font-size: 24rpx;
		color: #666;
	}

	.store-item {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		padding: 20rpx;
		border-bottom: 2rpx solid #f0f0f0;
		background-color: #F9F7F0;
		border-radius: 16rpx;
	}

	.store-item:last-child {
		border-bottom: none;
	}

	.store-logo {

		.img {
			width: 100rpx;
			height: 100rpx;
			border-radius: 16rpx;
			margin-right: 30rpx;
		}
	}

	.store-name {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}

	.store-desc {
		font-size: 24rpx;
		color: #666;
		display: block;
	}

	/* 订单状态 */
	.order-status {
		display: flex;
		justify-content: space-between;
	}

	.status-item {
		text-align: center;
		flex: 1;
	}

	.status-icon {
		.img {
			width: 60rpx;
			height: 60rpx;
		}
	}

	.status-name {
		font-size: 24rpx;
		color: #333;
	}

	/* 常用功能 */
	.common-functions .functions {
		grid-template-columns: repeat(4, 1fr);
	}

	.page-title {
		font-size: 36rpx;
		color: #333;
	}
</style>