<template>
	<view class="bg-[var(--page-bg-color)] min-h-[100vh]" :style="themeColor()">

		<mescroll-body ref="mescrollRef" @init="mescrollInit" :down="{ use: false }" height="auto" @up="getListFn"
			:top="mescrollTop">
			<view class="sidebar-margin body-bottom" v-if="relationshipList.length">
				<view class="mb-[15rpx]" v-for="(item,index) in relationshipList" :key="item.id">

					<view class="bg-[#ffffff] rounded-10rpx">
						<view class="head border-0 border-b-1 border-solid border-[#ddd]">
							<view class="flex justify-between p-[20rpx]">
								<view class="u-body-item-title u-line-2">{{item.product.name}}</view>
							</view>
						</view>
						<view class="body">
							<view class="flex justify-start flex-col p-[20rpx]">
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('productSpec') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.product?.spec}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('productUnit') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.product?.productUnit?.name}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									批次号:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.batch_number}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									到期时间:<text class="ml-[20rpx] text-[var(--primary-color)]">{{item.expiry_at}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('warehouseName') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.warehouse?.name}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('inventory') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.inventory}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('freeze') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.freeze}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('updateTime') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.update_time}}</text>
								</view>

							</view>
						</view>
					</view>
				</view>
			</view>
			<mescroll-empty v-if="!relationshipList.length && !loading &&!listLoading"></mescroll-empty>

		</mescroll-body>
		<loading-page :loading="loading"></loading-page>
		<up-popup :show="queryShow" mode="top" @close="queryClose">
			<view class="query-popup">
				<up-form labelPosition="left" :model="queryF" ref="queryForm">
					<up-form-item label="所在仓库" labelWidth="160rpx">
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="queryF.warehouse_id" :localdata="warehouseList" dataKey="name" dataValue="id"
						:clear="true"  placeholder="请选择仓库" @change="warehouseIdChange"/>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="queryF.warehouse_id" :options="warehouseList" clearable dataKey="name" dataValue="id" placeholder="请选择仓库"  :height="38" @change="warehouseIdChange"/>
						<!-- #endif -->
					</up-form-item>
					<up-form-item label="供应商" labelWidth="160rpx">
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="queryF.supplier_id" :localdata="supplierList" dataKey="name" dataValue="id"
						:clear="true" placeholder="请选择供应商" @change="supplierIdChange" />
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="queryF.supplier_id" :options="supplierList" clearable dataKey="name" dataValue="id" placeholder="请选择供应商"  :height="38" @change="supplierIdChange"/>
						<!-- #endif -->
					</up-form-item>
					<up-form-item label="批次号" labelWidth="160rpx">
						<up-input v-model="queryF.batch_number" placeholder="请输入批次号"></up-input>
					</up-form-item>
					<up-form-item label="食材名称" labelWidth="160rpx">
						<up-input v-model="queryF.product_name" placeholder="请输入食材名称"></up-input>
					</up-form-item>
				</up-form>
				<view class="query-btn">
					<up-button @click="resetQuery">重置</up-button>
					<up-button type="primary" @click="submitQuery">确认</up-button>
				</view>
			</view>
		</up-popup>

		<view class="fixed bottom-4 right-4 z-2">
			<up-button @click="querySearch" type="primary" shape="circle"
				:customStyle="{borderRadius: '50%',padding: 0,width: '50px',height: '50px'}">
				<u-icon size="30" color="#fff" name="search"></u-icon>
			</up-button>
		</view>
		<view class="fixed bottom-18 right-4 z-2 smmarie-wprelationship">
			<!-- <up-button @click="smmarieTip" type="primary" shape="circle"
				:customStyle="{borderRadius: '50%',padding: 0,width: '50px',height: '50px'}">
				<u-icon size="30" color="#fff" name="file-text"></u-icon>
			</up-button> -->
			<!-- <view class="sum-total" v-if="sumShow"> -->
			<view class="sum-total">
				<view style="overflow-y: auto;">
					<view class="hd">
						<view>库存总数：</view>
						<view>{{sumF.total_quantity}}</view>
					</view>
					<view class="hd">
						<view>合计金额(元)：</view>
						<view>{{sumF.total_amount}}</view>
					</view>
				</view>
			</view>		
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref } from 'vue'
	import { t } from '@/locale';
	import { redirect, pxToRpx } from '@/utils/common';
	import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
	import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue';
	import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
	import { getWpRelationshipList } from '@/addon/erp/api/inventory';
	import { getWarehouseSelect,getSupplierSelect} from '@/addon/erp/api/base';
	import { onShow, onPageScroll, onReachBottom, onLoad } from '@dcloudio/uni-app';

	const { downCallback, mescrollInit, getMescroll } = useMescroll(onPageScroll, onReachBottom);


	const queryShow = ref(false);
	const sumShow = ref(false);
	
	const sumF = ref({
		 total_quantity: 0,
		 total_amount: 0.00
	})
	const queryF = ref({
		batch_number: '',
		warehouse_id: '',
		product_name: '',
		supplier_id: '',
		hasQuery:0
	})
	
	// 页面加载
	onLoad((option : any) => {
		getWarehouseList()
		getSupplierList();
		queryF.value.hasQuery=0
		sumShow.value=false
	})
	
	const querySearch = () => {
		sumShow.value = false
		queryShow.value = true
	}
	const queryClose = () => {
		queryShow.value = false
	}
	const smmarieTip= ()=>{
		sumShow.value =!sumShow.value
	}
	const resetQuery =()=>{
		Object.keys(queryF.value ).forEach((key: string) => {
			(queryF.value as any)[key] = ""
		})
		queryF.value.hasQuery=0
	}
	const submitQuery =()=>{
		queryShow.value = false
		queryF.value.hasQuery=1
		getMescroll().resetUpScroll();
	}
	
	/**
	 * 仓库
	 */
	const warehouseList = ref<any[]>([]);
	const warehouseIdChange = (e : any) => {
		queryF.value.warehouse_id = e.id;
	}
	// 获取仓库
	const getWarehouseList = () => {
		getWarehouseSelect({}).then((res : any) => {
			warehouseList.value = res.data;
		}).catch(err => {
			// 如果是4001，没有绑定企业账号，强制跳转绑定
			if (err.code == 4001) {
				redirect({ url: '/addon/erp/pages/member/bind' })
			}
		})
	}
	
	/**
	 * 供应商
	 */
	const supplierList = ref<any[]>([]);
	const supplierIdChange = (e : any) => {
		queryF.value.supplier_id = e.id;
	}
	// 获取供应商
	const getSupplierList = () => {
		getSupplierSelect({}).then((res : any) => {
			supplierList.value = res.data;
		}).catch(err => {
			// 如果是4001，没有绑定企业账号，强制跳转绑定
			if (err.code == 4001) {
				redirect({ url: '/addon/erp/pages/member/bind' })
			}
		})
	}
	
	// 获取系统状态栏的高度
	let menuButtonInfo : any = {};
	// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
	// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
	menuButtonInfo = uni.getMenuButtonBoundingClientRect();
	// #endif

	const mescrollTop = "20rpx"

	const relationshipList = ref<Array<any>>([]),
		loading = ref<boolean>(true),
		listLoading = ref<boolean>(true),
		mescrollRef = ref(null);

	interface mescrollStructure {
		num : number,
		size : number,
		endSuccess : Function,
		[propName : string] : any
	}

	const getListFn = (mescroll : mescrollStructure) => {
		listLoading.value = true;
		let data : Object = {
			page: mescroll.num,
			limit: mescroll.size,
			batch_number:queryF.value.hasQuery===1?queryF.value.batch_number:'',
			warehouse_id:queryF.value.hasQuery===1?queryF.value.warehouse_id:'',
			product_name:queryF.value.hasQuery===1?queryF.value.product_name:'',
			supplier_id:queryF.value.hasQuery===1?queryF.value.supplier_id:'',
		};
		 // 重置 sumF 变量
		 sumF.value.total_quantity = 0;
		 sumF.value.total_amount = 0.00;
		getWpRelationshipList(data).then((res : any) => {
			let newArr = res.data.data;
			mescroll.endSuccess(newArr.length);
			//设置列表数据
			if (mescroll.num == 1) {
				relationshipList.value = []; //如果是第一页需手动制空列表
			}
			relationshipList.value = relationshipList.value.concat(newArr);
			relationshipList.value.forEach((item: any) => {
			    sumF.value.total_quantity += Number(item.inventory)
			    const amount = Number(sumF.value.total_amount) + Number(item.inventory) * Number(item.price)
			    sumF.value.total_amount = parseFloat(amount.toFixed(2))
			})
			listLoading.value = false;
			loading.value = false;
		}).catch((err) => {
			// 如果是4001，没有绑定企业账号，强制跳转绑定
			if (err.code == 4001) {
				redirect({ url: '/addon/erp/pages/member/bind' })
			}
			listLoading.value = false;
			loading.value = false;
			mescroll.endErr(); // 请求失败, 结束加载
		})
	}
</script>

<style scoped>
	.query-popup{
		padding: 80rpx 30rpx 40rpx;
	}
	.query-btn{
		margin-top: 60rpx;
		display:flex;
	}
	.smmarie-wprelationship{
		position: fixed;
	}
	.smmarie-wprelationship .sum-total{
		/* position: absolute;
		top: -120rpx;
		right: 10rpx; */
		padding:10rpx;
		width: 260rpx;
		height: 80rpx;
		background: #fff;
		border: 2rpx solid #000;
		border-radius: 10rpx;
		font-size: 24rpx;
		font-weight: 800;
	}
	.sum-total .hd{
		display: flex;
		justify-content: space-between;
	}
/* 	.sum-total::after {
		content: ''; 
		position: absolute;
		bottom: -18rpx;
		left: 86%;
		transform: translateX(-50%);
		border-width: 5px;
		border-style: solid;
		border-color: #000 transparent transparent transparent;
	} */
</style>