<template>
	<view class="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">
				<u-checkbox-group class="w-full" v-model="checkProductList" placement="column">
					<view class="mb-[15rpx]" v-for="(item,index) in productList" :key="index">
						<up-collapse class="bg-[#ffffff] rounded-10rpx">
							<up-collapse-item>
								<template #title>
									<view class="flex" style="display: flex;align-items: center;">
										<u-checkbox :name="item"></u-checkbox>
										<view>{{item.name}}</view>
									</view>
								</template>
								<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>
							</up-collapse-item>
						</up-collapse>
					</view>
				</u-checkbox-group>
			</view>
			<mescroll-empty v-if="!productList.length && !loading &&!listLoading"></mescroll-empty>

		</mescroll-body>
		<loading-page :loading="loading"></loading-page>
		<view class="sidebar-margin mt-[20rpx] body-bottom">
			<u-button @click="onConfirm" type="primary" shape="circle" :text="t('confirmChoose')"></u-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 { getProductListByWarehouse, getProductClassifyTreeList } from '@/addon/erp/api/product';
	import { onLoad, onPageScroll, onReachBottom } from '@dcloudio/uni-app';

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

	const productClassifyTreeList = ref<any[]>([]);
	const checkProductList = ref<any[]>([]);
	const queryType = ref<any>('all');	// 查询方式 all 获取全部食材，  warehouse 根据仓库ID ，获取对应的食材
	const warehouse_id = ref<any>(undefined);	// 仓库Id
	const treePicker = ref<any>(null)
	const productQuery = ref<any>({
		type_name:'',
		type_id:'',
	})
	// 页面加载
	onLoad((option : any) => {
		queryType.value = option.type ? option.type : '';
		warehouse_id.value = option.warehouse_id ? option.warehouse_id : undefined
	})
	const mescrollTop = "20rpx"

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

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

	// 获取食材分类
	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 getListFn = (mescroll : mescrollStructure) => {
		listLoading.value = true;
		loading.value = true;
		let data : Object = {
			page: mescroll.num,
			limit: mescroll.size,
			warehouse_id: warehouse_id.value,
			product_type_id: productQuery.value.type_id
		};
		getProductListByWarehouse(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 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 onConfirm = () => {
		uni.$emit('choose_product', checkProductList.value);
		// 返回上一页
		uni.navigateBack({
			delta: 1
		});
	}
	getProductClassifyTree()
</script>

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