<template>
	<view class="bg-[var(--page-bg-color)] min-h-[100vh]" :style="themeColor()">
		<up-subsection :list="statusList" mode="subsection" :current="0" @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="inventoryList.length">
				<view class="mb-[15rpx]" v-for="(item,index) in inventoryList" :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 :text="item.type" type="warning" 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]">
									食材名称:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.product?.name}}</text>
								</view>
								<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]">
									{{ 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]">
									批次号:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.inventory?.batch_number}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('surfaceNum') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.surface_num}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									操作数量:<text class="ml-[20rpx] text-[var(--primary-color)]">{{item.number}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('realNum') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.real_num}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									状态:<text class="ml-[20rpx] text-[var(--primary-color)]">{{item.status_text}}</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 class="foot  border-0 border-t-1 border-solid border-[#ddd]">
							<view class="flex justify-end p-[20rpx]">
								<view v-if="hasPermission('erp_inventory_check_updateStatus')"><up-button
										v-if="item.status == 0" size="mini"
										:customStyle="{padding: 0,width: '130rpx',height: '50rpx',marginRight:'20rpx',fontSize:'20rpx'}"
										type="primary" text="通过" @click="handleOperateOrder(item,'audit')"></up-button>
								</view>
								<view v-if="hasPermission('erp_inventory_check_updateStatus')"><up-button
										v-if="item.status == 0" size="mini"
										:customStyle="{padding: 0,width: '130rpx',height: '50rpx',marginRight:'20rpx',fontSize:'20rpx'}"
										type="error" text="拒绝" @click="handleOperateOrder(item,'notAudit')"></up-button>
								</view>
								<view v-if="hasPermission('erp_inventory_check_putInStorage')"><up-button
										v-if="item.status == 1" size="mini"
										:customStyle="{padding: 0,width: '130rpx',height: '50rpx',marginRight:'20rpx',fontSize:'20rpx'}"
										type="primary" text="立即入库"
										@click="handleOperateOrder(item,'storage')"></up-button></view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<mescroll-empty v-if="!inventoryList.length && !loading &&!listLoading"></mescroll-empty>

		</mescroll-body>
		<loading-page :loading="loading"></loading-page>
		<!-- <view class="fixed bottom-4 right-4 z-2">
			<up-button @click="redirect({ url: '/addon/erp/pages/inventory/inventory/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> -->
		<!-- 通过审核模态框 -->
		<up-modal :show="auditOrderShow" @confirm="auditOrderConfirm" showCancelButton @cancel="auditOrderShow = false"
			:title="'提示'" :content="'确定要通过审核该数据吗？'" ref="auditOrderModal"></up-modal>
		<!-- 立即入库模态框 -->
		<up-modal :show="storageOrderShow" @confirm="storageOrderConfirm" showCancelButton
			@cancel="storageOrderShow = false" :title="'提示'" :content="'确定要立即入库该数据吗？'"
			ref="storageOrderModal"></up-modal>
		<!-- 拒绝审核模态框 -->
		<up-modal :show="notAuditOrderShow" @confirm="notAuditOrderConfirm" showCancelButton
			@cancel="notAuditOrderShow = false" :title="'提示'" ref="notAuditOrderModal">
			<view class="slot-content">
				<view>确定要拒绝该数据吗？</view>
				<u-input fontSize="28rpx" v-model.trim="refuseReason" clearable placeholderStyle="color: #888"
					placeholder="请输入拒绝原因" />
			</view>
		</up-modal>
	</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 { getCheckList, getCheckTypeList, updateCheckStatus, putInStorage } from '@/addon/erp/api/inventory';
	import { onShow, onPageScroll, onReachBottom, onLoad } from '@dcloudio/uni-app';
	import useMemberStore from '@/stores/member'
	import usePermission from '@/utils/usePermission'
	const { hasPermission } = usePermission()
	const { downCallback, mescrollInit, getMescroll } = useMescroll(onPageScroll, onReachBottom);

	const memberStore = useMemberStore()

	const auditOrderItem = ref<SellReturnItem | null>(null);
	const auditOrderShow = ref(false);
	const notAuditOrderShow = ref(false);
	const storageOrderShow = ref(false);
	const refuseReason = ref("")
	const statusList = ref<any[]>([]);
	const searchParams = ref<any>({
		status: '增加',
	});
	onLoad(() => {
		// 获取状态
		getCheckTypeList().then((res : any) => {
			statusList.value = Object.values(res.data);
		});
	})
	// 操作
	const handleOperateOrder = async (item : any, type : string) => {
		if (type === 'audit') {
			auditOrderShow.value = true
		} else if (type === 'notAudit') {
			notAuditOrderShow.value = true
		} else if (type === 'storage') {
			storageOrderShow.value = true
		}
		refuseReason.value = ""
		auditOrderItem.value = item
	}
	// 确认审核
	const auditOrderConfirm = () => {
		if (!auditOrderItem.value) {
			uni.showToast({
				title: '数据不存在',
				icon: 'none'
			});
			return;
		}
		updateCheckStatus({ id: auditOrderItem.value.id, type: 'pass' })
			.then((res : any) => {
				if (res.code === 1) {
					getMescroll().resetUpScroll();
					auditOrderItem.value = null;
					auditOrderShow.value = false;
				}
			}).catch(() => { });
	}
	// 确认立即入库
	const storageOrderConfirm = () => {
		if (!auditOrderItem.value) {
			uni.showToast({
				title: '数据不存在',
				icon: 'none'
			});
			return;
		}
		putInStorage(auditOrderItem.value.id)
			.then((res : any) => {
				if (res.code === 1) {
					getMescroll().resetUpScroll();
					auditOrderItem.value = null;
					storageOrderShow.value = false;
				}
			}).catch(() => { });
	}
	// 确认拒绝通过审核
	const notAuditOrderConfirm = () => {
		if (!auditOrderItem.value) {
			uni.showToast({
				title: '数据不存在',
				icon: 'none'
			});
			return;
		}
		updateCheckStatus({ id: auditOrderItem.value.id, type: 'reject', reject_reason: refuseReason.value })
			.then((res : any) => {
				if (res.code === 1) {
					getMescroll().resetUpScroll();
					auditOrderItem.value = null;
					notAuditOrderShow.value = false;
				}
			}).catch(() => { });
	}
	// 分段器改变事件
	const handleChange = (index : number) => {
		searchParams.value.status = index === 0 ? '增加' : '减少';
		getMescroll().resetUpScroll();
	}

	// 获取系统状态栏的高度
	let menuButtonInfo : any = {};
	// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
	// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
	menuButtonInfo = uni.getMenuButtonBoundingClientRect();
	// #endif

	const mescrollTop = "20rpx"

	const inventoryList = 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,
			type: searchParams.value.status
		};
		getCheckList(data).then((res : any) => {
			let newArr = res.data.data;
			mescroll.endSuccess(newArr.length);
			//设置列表数据
			if (mescroll.num == 1) {
				inventoryList.value = []; //如果是第一页需手动制空列表
			}
			inventoryList.value = inventoryList.value.concat(newArr);
			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>
</style>