<template>
	<!-- 入库订单（待入库） -->
	<view class="bg-[var(--page-bg-color)] min-h-[100vh]" :style="themeColor()">
		<!-- <up-subsection :list="statusList" mode="subsection" :current="subsectionCurrent" @change="handleChange" /> -->
		<mescroll-body ref="mescrollRef" @init="mescrollInit" :down="{ use: false }" height="auto" @up="getListFn"
			:top="mescrollTop">
			<view class="sidebar-margin body-bottom" v-if="orderList.length">
				<view class="mb-[15rpx]" v-for="(item,index) in orderList" :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.code}}</view>
								<view>
									<up-tag v-if="item.storage_status == 2" :text="item.status_text" plain
										size="mini"></up-tag>
									<up-tag v-if="item.storage_status == 3" :text="item.status_text" type="success"
										plain size="mini"></up-tag>
								</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('supplierId') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.supplier?.name}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('contact') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.supplier?.contact}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('phone') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.supplier?.phone}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ '录入人' }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.enter_name }}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ '入库人' }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.store_name}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('createTime') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.create_time}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									<text style="margin-right: 60rpx;">图片:</text>
									<view>
										<up-upload :fileList="listImageList[index]"
											@afterRead="(evnet:any)=>afterRead(evnet,item.id,index)"
											@delete="(evnet:any)=>listImageDelete(evnet,item.id,index)" width="140rpx"
											height="140rpx" multiple :maxCount="5" accept="image"
											:capture="['camera']"></up-upload>
									</view>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									<text style="margin-right: 14rpx;">检验图片:</text>
									<view>
										<up-upload :fileList="inspectionImageList[index]"
											@afterRead="(evnet:any)=>inspectionAfterRead(evnet,item.id,index)"
											@delete="(evnet:any)=>inspectionListImageDelete(evnet,item.id,index)" width="140rpx"
											height="140rpx" multiple :maxCount="5" accept="image"
											:capture="['camera']"></up-upload>
									</view>
								</view>
							</view>
						</view>
						<view class="foot  border-0 border-t-1 border-solid border-[#ddd]">
							<view class="flex justify-end p-[20rpx]">
								<view v-if="hasPermission('erp_manual_inbound_takeOutOfStorage')"><up-button v-if="item.storage_status == 2" size="mini"
										:customStyle="{padding: 0,width: '130rpx',height: '50rpx',marginRight:'20rpx'}"
										type="primary" text="立即入库" @click="handleEnteringWarehouse(item)"></up-button>
								</view>
								<view><up-button size="mini"
										:customStyle="{padding: 0,width: '130rpx',height: '50rpx',marginRight:'10rpx'}"
										type="success" :text=" t('detailGo')"
										@click="redirect({ url: '/addon/erp/pages/inbound/stockPending/detail',param:{id: item.id} })"></up-button>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<mescroll-empty v-if="!orderList.length && !loading &&!listLoading"></mescroll-empty>

		</mescroll-body>
		<loading-page :loading="loading"></loading-page>
		<!-- 立即入库模态框 -->
		<up-modal :show="enteringWarehouseShow" @confirm="enteringWarehouseConfirm" showCancelButton
			@cancel="enteringWarehouseShow = false" :title="'提示'" :content="'确定要入库该数据吗？'"
			ref="enteringWarehouseModal"></up-modal>
		<!-- 图片删除 -->
		<up-modal :show="delWarehouseImgShow" @confirm="delOutWarehouseImgConfirm" showCancelButton
			@cancel="delWarehouseImgShow = false" :title="'提示'" :content="'确定要删除该图片吗？'"
			ref="delWarehouseImgModal"></up-modal>
		<!-- <view class="fixed bottom-4 right-4 z-2">
			<up-button @click="redirect({ url: '/addon/erp/pages/inbound/stockPending/add'})" type="primary"
				shape="circle" :customStyle="{borderRadius: '50%',padding: 0,width: '50px',height: '50px'}">
				<u-icon size="30" color="#fff" name="plus-circle-fill"></u-icon>
			</up-button>
		</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 { getManualList, getManualStatus, getManualInfo, putInStorage, setManualImg } from '@/addon/erp/api/purchase';
	import { onShow, onPageScroll, onReachBottom, onLoad } from '@dcloudio/uni-app';
	import useMemberStore from '@/stores/member'
	import { uploadImage } from '@/app/api/system'
	import { img } from '@/utils/common'
	import usePermission from '@/utils/usePermission'
	const { hasPermission } = usePermission()	
	const { downCallback, mescrollInit, getMescroll } = useMescroll(onPageScroll, onReachBottom);
	interface FileItem {
		url : string;
		status ?: string;
		message ?: string;
	}
	const imgTemp = ref({
		index: 0,
		imgIndex: 0,
		type: 1
	})
	const listImageList = ref<Array<Array<FileItem>>>([]);
	const inspectionImageList = ref<Array<Array<FileItem>>>([]);
	const enteringWarehouseId = ref('')
	const subsectionCurrent = ref(0)
	const enteringWarehouseShow = ref(false);
	const delWarehouseImgShow = ref(false);
	const statusList = ref<any[]>([]);
	const searchParams = ref<any>({
		status: 2,
	});
	const memberStore = useMemberStore()
	// 获取系统状态栏的高度
	let menuButtonInfo : any = {};
	// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
	// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
	menuButtonInfo = uni.getMenuButtonBoundingClientRect();
	// #endif


	onLoad(() => {
		// 获取状态
		getManualStatus().then((res : any) => {
			statusList.value = Object.values(res.data);
			subsectionCurrent.value = statusList.value.findIndex((item : any) => item === '待入库')
		});
		imgTemp.value.index = 0
		imgTemp.value.imgIndex = 0
		listImageList.value = []
		inspectionImageList.value = []
	})
	// 立即入库
	const handleEnteringWarehouse = async (item : any) => {
		enteringWarehouseShow.value = true
		enteringWarehouseId.value = item.id
	}

	// 确认立即入库
	const enteringWarehouseConfirm = () => {
		if (enteringWarehouseId.value == '') {
			uni.showToast({ icon: 'none', title: t("Invalid ID") });
			return false;
		}
		putInStorage(enteringWarehouseId.value)
			.then((res : any) => {
				if (res.code === 1) {
					getMescroll().resetUpScroll();
					enteringWarehouseId.value = '';
					enteringWarehouseShow.value = false;
				}
			}).catch(() => { });
	}

	// 分段器改变事件
	const handleChange = (index : number) => {
		searchParams.value.status = index === 0 ? 2 : 3;
		getMescroll().resetUpScroll();
	}

	const mescrollTop = "20rpx"

	const orderList = 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,
			storage_status: searchParams.value.status
		};
		getManualList(data).then((res : any) => {
			let newArr = res.data.data;
			let newImg = res.data.data.reduce((acc : any, item : any) => {
				let image_arr : any = []
				if (item.inbound_image) {
					const image_split_arr = item.inbound_image.split(',')
					image_split_arr.forEach((arr : any) => {
						image_arr.push({
							status: 'success',
							message: '',
							url: img(arr),
						})
					})
				}
				acc.push(image_arr)
				return acc
			}, [])
			let newImg2 = res.data.data.reduce((acc : any, item : any) => {
				let image_arr : any = []
				if (item.inspection_report_image) {
					const image_split_arr = item.inspection_report_image.split(',')
					image_split_arr.forEach((arr : any) => {
						image_arr.push({
							status: 'success',
							message: '',
							url: img(arr),
						})
					})
				}
				acc.push(image_arr)
				return acc
			}, [])
			mescroll.endSuccess(newArr.length);
			//设置列表数据
			if (mescroll.num == 1) {
				listImageList.value = []
				inspectionImageList.value = []
				orderList.value = []; //如果是第一页需手动制空列表
			}
			orderList.value = orderList.value.concat(newArr);
			listImageList.value = listImageList.value.concat(newImg);
			inspectionImageList.value = inspectionImageList.value.concat(newImg2);
			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(); // 请求失败, 结束加载
		})
	}
	const afterRead = async (event : any, rowId : any, rowIndex : number) => {
		enteringWarehouseId.value = rowId
		imgTemp.value.index = rowIndex
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists : FileItem[] = [].concat(event.file);
		let fileListLen = listImageList.value[rowIndex].length;
		lists = lists.filter((item : FileItem) => item.url);
		lists.map((item : any) => {
			listImageList.value[rowIndex].push({
				url: item.url,
				status: 'uploading',
				message: '上传中',
			});
		})
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			let item = listImageList.value[rowIndex][fileListLen];
			listImageList.value[rowIndex].splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: img(result as string),
			});
			fileListLen++;
		}
		handleSetOutWarehouseImg(rowId, rowIndex)
	}
	const inspectionAfterRead = async (event : any, rowId : any, rowIndex : number) => {
		enteringWarehouseId.value = rowId
		imgTemp.value.index = rowIndex
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists : FileItem[] = [].concat(event.file);
		let fileListLen = inspectionImageList.value[rowIndex].length;
		lists = lists.filter((item : FileItem) => item.url);
		lists.map((item : any) => {
			inspectionImageList.value[rowIndex].push({
				url: item.url,
				status: 'uploading',
				message: '上传中',
			});
		})
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			let item = inspectionImageList.value[rowIndex][fileListLen];
			inspectionImageList.value[rowIndex].splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: img(result as string),
			});
			fileListLen++;
		}
		handleSetOutWarehouseImg(rowId, rowIndex)
	}

	const uploadFilePromise = (url : any) => {
		return new Promise((resolve, reject) => {
			let a = uploadImage({
				filePath: url,
				name: 'file'
			}).then((res : any) => {
				setTimeout(() => {
					resolve(res.data.url as string);
				}, 1000);
			})
		});
	}
	const listImageDelete = (event : any, rowId : any, rowIndex : number) => {
		if (event.index !== undefined && event.file !== undefined) {
			delWarehouseImgShow.value = true
			imgTemp.value.imgIndex = event.index
			imgTemp.value.index = rowIndex
			imgTemp.value.type = 1
			enteringWarehouseId.value = rowId
		}
	}
	const inspectionListImageDelete = (event : any, rowId : any, rowIndex : number) => {
		if (event.index !== undefined && event.file !== undefined) {
			delWarehouseImgShow.value = true
			imgTemp.value.imgIndex = event.index
			imgTemp.value.index = rowIndex
			imgTemp.value.type = 2
			enteringWarehouseId.value = rowId
		}
	}
	// 删除照片确认
	const delOutWarehouseImgConfirm = () => {
		const { imgIndex, index, type } = imgTemp.value
		const currentFileList = getCurrentFileList(type, index);
		currentFileList.splice(imgIndex, 1);
		updateListImageList(type, currentFileList);
		delWarehouseImgShow.value = false
		handleSetOutWarehouseImg(enteringWarehouseId.value, index)
	}
	// 获取当前文件列表
	const getCurrentFileList = (type : number, index : number) : any[] => {
		return type === 1 ? listImageList.value[index] : inspectionImageList.value[index];
	}
	// 更新 listImageList 或 inspectionImageList
	const updateListImageList = (type : number, fileList : any[]) => {
		if (type === 1) {
			listImageList.value = [...listImageList.value];
		} else {
			inspectionImageList.value = [...inspectionImageList.value];
		}
	}
	// 保存入库单的照片
	const handleSetOutWarehouseImg = (id : any, rowIndex : number) => {
		let param = {
			inbound_image: '',
			inspection_report_image: '',
		}
		if (listImageList.value[rowIndex].length > 0) {
			const imgUrls = listImageList.value[rowIndex].map((item : any) => {
				return `upload${item.url.split('upload')[1]}`
			})
			param.inbound_image = imgUrls.join(',')
		}
		if (inspectionImageList.value[rowIndex].length > 0) {
			const imgUrls = inspectionImageList.value[rowIndex].map((item : any) => {
				return `upload${item.url.split('upload')[1]}`
			})
			param.inspection_report_image = imgUrls.join(',')
		}
		setManualImg(id, param).then((res : any) => {
			if (res.code === 1) {
				getOutWarehouseInfo(id)
			}
		}).catch(() => { getOutWarehouseInfo(id) });
	}
	//根据入库单id获取详情
	const getOutWarehouseInfo = async (id : number) => {
		const res : any = await getManualInfo(id);
		if (res.code === 1) {
			const { data } = res
			const { index } = imgTemp.value
			if (data.inbound_image) {
				const image_split_arr = data.inbound_image.split(',')
				let image_arr : any = []
				image_split_arr.forEach((arr : any) => {
					image_arr.push({
						status: 'success',
						message: '',
						url: img(arr),
					})
				})
				listImageList.value[index] = image_arr
			} else {
				listImageList.value[index] = []
			}
			if (data.inspection_report_image) {
				const image_split_arr = data.inspection_report_image.split(',')
				let image_arr : any = []
				image_split_arr.forEach((arr : any) => {
					image_arr.push({
						status: 'success',
						message: '',
						url: img(arr),
					})
				})
				inspectionImageList.value[index] = image_arr
			} else {
				inspectionImageList.value[index] = []
			}
		}
	}
</script>

<style scoped>
</style>