<template>
	<view class="bg-[var(--page-bg-color)] min-h-[100vh]" :style="themeColor()">
		<view class="classify-box">
			<u-form labelPosition="left" :model="productQuery" errorType='toast' ref="formRef" labelWidth="140rpx">
				<u-form-item label="食材分类" prop="type_name" required @click="showPicker">
					<u-input fontSize="28rpx" v-model.trim="productQuery.type_name" readonly clearable
						placeholderStyle="color: #888" placeholder="请选择分类" suffixIcon="arrow-down-fill"
						suffixIconStyle="font-size: 22rpx;color: #c0c4cc" />
				</u-form-item>
			</u-form>
		</view>
		<mescroll-body ref="mescrollRef" @init="mescrollInit" :down="{ use: false,auto:false }" :up="{ auto:false }"
			height="auto" @up="getListFn" :top="mescrollTop">
			<view class="sidebar-margin body-bottom" v-if="productList.length">
				<view class="mb-[15rpx]" v-for="(item,index) in productList" :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.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('code') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.code}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('productTypeId') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.productType?.name}}</text>
								</view>
								<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
									{{ t('spec') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.spec}}</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('productUnitId') }}:<text
										class="ml-[20rpx] text-[var(--primary-color)]">{{item.productUnit?.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>
						</view>
						<view class="foot  border-0 border-t-1 border-solid border-[#ddd]">
							<view class="flex justify-end p-[20rpx]">
								<view><up-button :text="t('info')" size="mini"
										@click="redirect({ url: '/addon/erp/pages/product/product/detail',param:{id: item.id} })"></up-button>
								</view>
								<view v-if="hasPermission('erp_product_add')"><up-button type="error"
										@click="hanldeDelete(item.id)" :text="t('delete')" size="mini"></up-button>
								</view>
							</view>
						</view>
					</view>
					<!-- 删除模态框 -->
					<up-modal :show="show" @confirm="confirm" showCancelButton @cancel="show = false"
						:title="t('delete')" :content="t('productDeleteTips')" ref="uModal"></up-modal>
				</view>
			</view>
			<mescroll-empty v-if="!productList.length && !loading &&!listLoading"></mescroll-empty>

		</mescroll-body>
		<loading-page :loading="loading"></loading-page>
		<view v-if="hasPermission('erp_product_delete')" class="fixed bottom-4 right-4 z-2">
			<up-button @click="redirect({ url: '/addon/erp/pages/product/product/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>
		<ba-tree-picker ref="treePicker" :multiple='false' @select-change="selectChange" title="选择食材分类"
			:localdata="productClassifyTreeList" valueKey="id" textKey="name" childrenKey="children" />
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, computed, nextTick } from 'vue'
	import { topTabar } from '@/utils/topTabbar';
	import { t } from '@/locale';
	import { redirect, pxToRpx } from '@/utils/common';
	import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue"
	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 { getProductList, deleteProduct, getProductClassifyTreeList } from '@/addon/erp/api/product';
	import { onShow, onPageScroll, onReachBottom } from '@dcloudio/uni-app';
	import usePermission from '@/utils/usePermission'
	const { hasPermission } = usePermission()
	const { downCallback, mescrollInit, getMescroll } = useMescroll(onPageScroll, onReachBottom);


	const show = ref(false);

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

	const mescrollTop = "20rpx"

	const productList = ref<Array<any>>([]),
		loading = ref<boolean>(false),
		listLoading = ref<boolean>(false),
		mescrollRef = ref(null);
	const productClassifyTreeList = ref([])
	const treePicker = ref<any>(null)
	const productQuery = ref<any>({
		type_name: '',
		type_id: '',
	})
	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,
			product_type_id: productQuery.value.type_id
		};
		getProductList(data).then((res : any) => {
			let newArr = res.data.data;
			mescroll.endSuccess(newArr.length);
			//设置列表数据
			if (mescroll.num == 1) {
				productList.value = []; //如果是第一页需手动制空列表
			}
			productList.value = productList.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(); // 请求失败, 结束加载
		})
	}
	// 获取食材分类
	const getProductClassifyTree = () => {
		getProductClassifyTreeList({}).then((res : any) => {
			productClassifyTreeList.value = res.data
		}).catch(err => {
			// 如果是4001，没有绑定企业账号，强制跳转绑定
			if (err.code == 4001) {
				redirect({ url: '/addon/erp/pages/member/bind' })
			}
		})
	}
	// 显示选择器
	const showPicker = () => {
		treePicker.value._show();
	}
	//监听选择（ids为数组）
	const selectChange = (ids : any, names : any) => {
		productQuery.value.type_id = ids.length > 0 ? ids[0] : ''
		productQuery.value.type_name = names
		getMescroll().resetUpScroll()
	}
	// 删除
	const del_id = ref<number>(0);
	const hanldeDelete = (id : number) => {
		show.value = true;
		del_id.value = id;
	};
	// 确认删除
	const confirm = () => {
		if (del_id.value == 0) {
			uni.showToast({ icon: 'none', title: t("Invalid ID") });
			return false;
		}
		let index = productList.value.findIndex(item => item.id === del_id.value);
		deleteProduct(del_id.value)
			.then(() => {
				productList.value.splice(index, 1);
				del_id.value = 0;
				show.value = false;
			}).catch(() => { });
	}
	getProductClassifyTree()
</script>

<style scoped>
	.classify-box {
		padding: 20rpx 40rpx;
		box-sizing: border-box;
		background: #fff;
	}
</style>