<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="sellReturnList.length">
				<view class="mb-[15rpx]" v-for="(item,index) in sellReturnList" :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.status == 1" :text="item.status_text" type="warning" plain
										size="mini"></up-tag>
									<up-tag v-if="item.status == 2" :text="item.status_text" type="error" plain
										size="mini"></up-tag>
									<up-tag v-if="item.status == 3" :text="item.status_text" plain size="mini"></up-tag>
									<up-tag v-if="item.status == 5" :text="item.status_text" type="success" plain
										size="mini"></up-tag>
									<up-tag v-if="item.status == 4" :text="item.status_text" type="error" 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('customerName') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.customer?.name}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									联系人:<text class="ml-[20rpx] text-[var(--primary-color)]">{{item.contact}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									联系电话:<text class="ml-[20rpx] text-[var(--primary-color)]">{{item.phone}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									仓库名称:<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('returnQuantity') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.total_num}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('billingTime') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.billing_time}}</text>
								</view>

							</view>
						</view>
						<view class="operate">
							<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,'audit')"></up-button>
							<up-button v-if="item.status == 1" size="mini"
								:customStyle="{padding: 0,width: '130rpx',height: '50rpx',marginRight:'20rpx',fontSize:'20rpx'}"
								type="error" text="拒绝" @click="handleOperateOrder(item,'notAudit')"></up-button>
							<up-button v-if="item.status == 3" size="mini"
								:customStyle="{padding: 0,width: '130rpx',height: '50rpx',marginRight:'20rpx',fontSize:'20rpx'}"
								type="primary" text="立即入库" @click="handleOperateOrder(item,'storage')"></up-button>
							<up-button v-if="item.status == 3" size="mini"
								:customStyle="{padding: 0,width: '130rpx',height: '50rpx',marginRight:'20rpx',fontSize:'20rpx'}"
								type="error" text="拒绝入库" @click="handleOperateOrder(item,'notStorage')"></up-button>
							<up-button v-if="item.status == 3" size="mini"
								:customStyle="{padding: 0,width: '130rpx',height: '50rpx',marginRight:'20rpx',fontSize:'20rpx'}"
								type="error" text="撤销审核" @click="handleOperateOrder(item,'backout')"></up-button>
							<up-button size="mini"
								:customStyle="{padding: 0,width: '130rpx',height: '50rpx',marginRight:'10rpx'}"
								type="success" text="详情"
								@click="redirect({ url: '/addon/erp/pages/canteen/return/detail',param:{id: item.id} })"></up-button>

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

		</mescroll-body>
		<loading-page :loading="loading"></loading-page>
		<!-- 通过审核模态框 -->
		<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="backoutOrderShow" @confirm="backoutOrderConfirm" showCancelButton
			@cancel="backoutOrderShow = false" :title="'提示'" :content="'确定要撤销审核该数据吗？'"
			ref="backoutOrderModal"></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>
		<!-- 拒绝入库模态框 -->
		<up-modal :show="notStorageOrderShow" @confirm="notStorageOrderConfirm" showCancelButton
			@cancel="notStorageOrderShow = false" :title="'提示'" ref="notStorageOrderModal">
			<view class="slot-content">
				<view>确定要拒绝立即入库该数据吗？</view>
				<u-input fontSize="28rpx" v-model.trim="refuseReason" clearable placeholderStyle="color: #888"
					placeholder="请输入拒绝原因" />
			</view>
		</up-modal>
		<view class="fixed bottom-4 right-4 z-2">
			<up-button @click="redirect({ url: '/addon/erp/pages/canteen/return/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 {
		getManualReturnList, updateManualReturnStatus,
		updateManualReturnStorageStatus, antiManualReturnStatus,
		getManualReturnStatus

	} from '@/addon/erp/api/sell';
	import { onShow, onPageScroll, onReachBottom, onLoad } from '@dcloudio/uni-app';
	import { checkBtnPermission } from '@/utils/auth';
	import useMemberStore from '@/stores/member'

	interface SellReturnItem {
		id : number;
	}
	const memberStore = useMemberStore()
	const { downCallback, mescrollInit, getMescroll } = useMescroll(onPageScroll, onReachBottom);
	const auditOrderItem = ref<SellReturnItem | null>(null);
	const auditOrderShow = ref(false);
	const notAuditOrderShow = ref(false);
	const notStorageOrderShow = ref(false);
	const storageOrderShow = ref(false);
	const backoutOrderShow = ref(false);
	const refuseReason = ref("")
	const subsectionCurrent = ref(0)
	const mescrollTop = "20rpx"
	const statusList = ref<any[]>([]);
	const statusValList = ref<any[]>([]);
	const searchParams = ref<any>({
		status: 3,
	});
	const sellReturnList = 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
	}

	onLoad(() => {
		// 获取状态
		getManualReturnStatus().then((res : any) => {
			statusList.value = Object.values(res.data);
			statusValList.value = Object.keys(res.data);
			subsectionCurrent.value = statusList.value.findIndex((item : any) => item === '待入库')
		});
	})
	// 分段器改变事件
	const handleChange = (index : number) => {
		searchParams.value.status = statusValList.value[index];
		getMescroll().resetUpScroll();
	}
	// 操作
	const handleOperateOrder = (item : any, type : string) => {
		if (type === 'audit') {
			const hasPermission = checkBtnPermission(memberStore.btnPermission, 'erp_inbound_return_updateStatus')
			if (!hasPermission) return
			auditOrderShow.value = true
		} else if (type === 'notAudit') {
			const hasPermission = checkBtnPermission(memberStore.btnPermission, 'erp_inbound_return_updateStatus')
			if (!hasPermission) return
			notAuditOrderShow.value = true
		} else if (type === 'storage') {
			const hasPermission = checkBtnPermission(memberStore.btnPermission, 'erp_inbound_return_updateStorageStatus')
			if (!hasPermission) return
			storageOrderShow.value = true
		} else if (type === 'notStorage') {
			const hasPermission = checkBtnPermission(memberStore.btnPermission, 'erp_inbound_return_updateStorageStatus')
			if (!hasPermission) return
			notStorageOrderShow.value = true
		} else if (type === 'backout') {
			const hasPermission = checkBtnPermission(memberStore.btnPermission, 'erp_inbound_return_anti')
			if (!hasPermission) return
			backoutOrderShow.value = true
		}
		refuseReason.value = ""
		auditOrderItem.value = item
	}

	// 确认审核
	const auditOrderConfirm = () => {
		if (!auditOrderItem.value) {
			uni.showToast({
				title: '数据不存在',
				icon: 'none'
			});
			return;
		}
		updateManualReturnStatus({ 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;
		}
		updateManualReturnStorageStatus({ id: auditOrderItem.value.id, type: 'pass' })
			.then((res : any) => {
				if (res.code === 1) {
					getMescroll().resetUpScroll();
					auditOrderItem.value = null;
					storageOrderShow.value = false;
				}
			}).catch(() => { });
	}
	// 确认撤销审核
	const backoutOrderConfirm = () => {
		if (!auditOrderItem.value) {
			uni.showToast({
				title: '数据不存在',
				icon: 'none'
			});
			return;
		}
		antiManualReturnStatus(auditOrderItem.value.id)
			.then((res : any) => {
				if (res.code === 1) {
					getMescroll().resetUpScroll();
					auditOrderItem.value = null;
					backoutOrderShow.value = false;
				}
			}).catch(() => { });
	}
	// 确认拒绝入库
	const notStorageOrderConfirm = () => {
		if (!auditOrderItem.value) {
			uni.showToast({
				title: '数据不存在',
				icon: 'none'
			});
			return;
		}
		updateManualReturnStorageStatus({ id: auditOrderItem.value.id, type: 'reject', why: refuseReason.value })
			.then((res : any) => {
				if (res.code === 1) {
					getMescroll().resetUpScroll();
					auditOrderItem.value = null;
					notStorageOrderShow.value = false;
				}
			}).catch(() => { });
	}
	// 确认拒绝通过审核
	const notAuditOrderConfirm = () => {
		if (!auditOrderItem.value) {
			uni.showToast({
				title: '数据不存在',
				icon: 'none'
			});
			return;
		}
		updateManualReturnStatus({ 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 getListFn = (mescroll : mescrollStructure) => {
		listLoading.value = true;
		let data : Object = {
			page: mescroll.num,
			limit: mescroll.size,
			status: searchParams.value.status
		};
		getManualReturnList(data).then((res : any) => {
			let newArr = res.data.data;
			mescroll.endSuccess(newArr.length);
			//设置列表数据
			if (mescroll.num == 1) {
				sellReturnList.value = []; //如果是第一页需手动制空列表
			}
			sellReturnList.value = sellReturnList.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>
	.operate {
		display: flex;
		justify-self: end;
		padding-bottom: 20rpx;
	}
</style>