<template>
	<view class="bg-[var(--page-bg-color)] min-h-[100vh] overflow-hidden form-edit" :style="themeColor()">

		<up-form labelPosition="left" :model="formData" errorType='toast' :rules="rules" ref="formRef"
			labelWidth="150rpx">
			<view class="sidebar-margin card-template mt-[var(--top-m)] py-[20rpx]">
				<view>
					<up-form-item :label="'单据编号'" prop="code" required borderBottom>
						<u-input fontSize="28rpx" v-model="formData.code" disabled  clearable
							placeholderStyle="color: #888" :placeholder="'请输入单据编号'" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					 <up-form-item :label="'制单日期'" prop="billing_time" required borderBottom>
						 <u-input fontSize="28rpx" v-model="formData.billing_time" disabled  clearable
						 	placeholderStyle="color: #888" :placeholder="'请选择制单日期'" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="'盘点日期'" prop="check_time" required borderBottom @click="checkTimeShow = true">
						 <!-- #ifdef H5 -->
						<up-datetime-picker hasInput :show="checkTimeShow" v-model="formData.check_time" mode="date" :placeholder="'请选择盘点日期'" @confirm="checkTimeConfirm" @cancel="checkTimeShow = false"></up-datetime-picker>
						 <!-- #endif -->
						 <!-- #ifdef MP-WEIXIN -->
						 <u-input fontSize="28rpx" v-model="formData.check_time"  readonly
						 	placeholderStyle="color: #888" placeholder="请选择盘点日期" />
						 <up-datetime-picker :show="checkTimeShow" v-model="check_time_new" mode="date" :placeholder="'请选择盘点日期'" @confirm="checkTimeConfirm" @cancel="checkTimeShow = false"></up-datetime-picker>
						 <!-- #endif -->
					</up-form-item>
				</view>
				<view  class="mt-[16rpx]">
					<up-form-item :label="'仓库名称'" prop="warehouse_id" required borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.warehouse_id" :localdata="warehouseList" dataKey="name" dataValue="id"
						:clear="false"  placeholder="请选择仓库" @change="updateSexWarehouse"/>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.warehouse_id" :options="warehouseList" dataKey="name" dataValue="id" placeholder="请选择仓库"  :height="38" @change="updateSexWarehouse"/>
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('productName')" prop="product_id" required borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.product_id" :localdata="productList" dataKey="name" dataValue="product_id"
						:clear="false" :disabled="productList.length === 0" placeholder="请选择食材" @change="productIdChange"/>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.product_id" :options="productList" dataKey="name" dataValue="product_id" placeholder="请选择食材"  :height="38" :disabled="productList.length === 0" @change="productIdChange"/>
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="'批次号'" prop="inventory_id"  borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.inventory_id" :localdata="batchNumberList" dataKey="batch_number" dataValue="inventory_id"
						:clear="false" :disabled="batchNumberList.length === 0" placeholder="请选择批次号" @change="inventoryIdChange"/>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.inventory_id" :options="batchNumberList" dataKey="batch_number" dataValue="inventory_id" placeholder="请选择批次号"  :height="38" :disabled="batchNumberList.length === 0" @change="inventoryIdChange"/>
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('surfaceNum')" prop="surface_num" borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.surface_num" readOnly disabled 
							clearable placeholderStyle="color: #888" :placeholder="t('surfaceNumPlaceholder')" />
						<view v-show="formData.freeze">(其中因未完成出库单占用的冻结数量：{{ formData.freeze }})</view>
					</up-form-item>
				</view>
				<view  class="mt-[16rpx]">
					<up-form-item :label="'盘点结果'" prop="type" required borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.type" :localdata="typeList" dataKey="name" dataValue="name"
						:clear="false"  placeholder="请选择盘点结果"/>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.type" :options="typeList" dataKey="name" dataValue="name" placeholder="请选择盘点结果"  :height="38" @change="typeChange"/>
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="'操作数量'" prop="number" required borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.number"  clearable
							placeholderStyle="color: #888" :placeholder="'请输入操作数量'" />
					</up-form-item>
				</view>
			</view>

		</up-form>


		<view v-if="hasPermission('erp_inventory_check_add')" class="w-full footer">
			<view
				class="py-[var(--top-m)] px-[var(--sidebar-m)] footer w-full fixed bottom-0 left-0 right-0 box-border">
				<button hover-class="none"
					class="!bg-[var(--primary-color)] text-[#fff] h-[80rpx] leading-[80rpx] rounded-[100rpx] text-[26rpx] font-500"
					@click="handSave" :disabled="loading" :class="{'opacity-50': loading}">{{t('save')}}</button>
			</view>
		</view>
	</view>

</template>

<script setup lang="ts">
	import { ref, reactive, computed } from 'vue'
	import { t } from '@/locale'
	import { onLoad, onReady } from '@dcloudio/uni-app';
	import { getWarehouseSelect } from '@/addon/erp/api/base';
	import { getMemberInfo } from '@/addon/erp/api/member';
	import { generatedCode } from '@/addon/erp/utils/common';
	import { addCheck, getCheckTypeList, getCheckProduct } from '@/addon/erp/api/inventory';
	import { redirect } from '@/utils/common';
	import dayjs from 'dayjs'
	import useMemberStore from '@/stores/member'
	import usePermission from '@/utils/usePermission'
	const { hasPermission } = usePermission()	
	const memberStore = useMemberStore()
	
	const formRef : any = ref(null)
	const loading = ref(false)
	const billingTimeShow = ref(false)
	const checkTimeShow = ref(false)
	const typeList = ref<any[]>([]);
	const batchNumberList = ref<any[]>([]);

	const rules = reactive({
		// 'supplier_id': {
		// 	required: true,
		// 	message: t('supplierIdPlaceholder'),
		// 	trigger: ['blur', 'change'],
		// },
		// 'warehouse_id': {
		// 	required: true,
		// 	message: t('warehouseIdPlaceholder'),
		// 	trigger: ['blur', 'change'],
		// }
	})


	const formData = ref({
		 id: '',
		 code: generatedCode('PD'),
		 billing_time: dayjs().format('YYYY-MM-DD'),
		 check_time: dayjs().format('YYYY-MM-DD'),
		 operator_id:'',
		 warehouse_id: '',
		 inventory_id: '',
		 product_id: '',
		 surface_num: '',
		 freeze: '',
		 number: '',
		 real_num: '',
		 type: ''
	})
	const check_time_new=ref(dayjs().format('YYYY-MM-DD'))
	onReady(() => {
		formRef.value.setRules(rules);
	})
	const getOperator = async () => {
	    const res = await getMemberInfo();
	    return res.data?.adminInfo?.uid || '';
	}
	// 页面加载
	onLoad(async (option : any) => {
		getTypeAllFn();
		getWarehouseList();
		formData.value.operator_id = await getOperator();
	})
	// 获取状态
	const getTypeAllFn = () => {
		getCheckTypeList().then((res) => {
			const data = Object.values(res.data);
			typeList.value = data.map((item:any)=>{
				return {name:item}
			})
		});
	};


	/**
	 * 仓库
	 */
	const warehouseList = ref<any[]>([]);
	const updateSexWarehouse = (e : any) => {
		formData.value.warehouse_id = e?.id ?? '';
		formData.value.inventory_id = ''
		formData.value.product_id = ''
		formData.value.surface_num = ''
		formData.value.freeze = ''
		batchNumberList.value = []
		getCheckProduct({
			warehouse_id: e.id,
		}).then((res) => {
			productList.value = res.data;
		});
	}
	// 获取仓库
	const getWarehouseList = () => {
		getWarehouseSelect({}).then((res : any) => {
			warehouseList.value = res.data;
		}).catch(err => {
			// 如果是4001，没有绑定企业账号，强制跳转绑定
			if (err.code == 4001) {
				redirect({ url: '/addon/erp/pages/member/bind' })
			}
		})
	}
	const checkTimeConfirm = (e : any) => {
		formData.value.check_time = uni.$u.date(e.value, 'yyyy-mm-dd');
		checkTimeShow.value = false;
	}
	// 食材
	const productList = ref<any[]>([]);
	const productIdChange = (e : any) => {
		formData.value.product_id = e?.product_id ?? '';

		handleProductIdChange(e.product_id);
	}
	// 批次号
	const inventoryIdChange = (e : any) => {
		formData.value.inventory_id = e?.inventory_id ?? '';
	}
	// 盘点结果
	const typeChange = (e : any) => {
		formData.value.type = e?.name ?? '';
	}

	// 食材选择事件
	const handleProductIdChange = (val : number) => {
		const product = productList.value.find((item) => item.product_id === val);
		batchNumberList.value = productList.value.filter((item) => item.product_id === val)
		if (product) {
			formData.value.surface_num = product?.surface_num ?? '';
			formData.value.freeze = product?.freeze ?? ''
		}
	};


	// 保存
	const handSave = async() => {
		if (loading.value) return
		if (!formData.value.warehouse_id) {
			uni.showToast({ icon: 'none', title: '请选择仓库' })
			return false;
		}
		if (!formData.value.product_id) {
			uni.showToast({ icon: 'none', title: '请选择食材' })
			return false;
		}
		if (!formData.value.number) {
			uni.showToast({ icon: 'none', title: '请输入操作数量' })
			return false;
		}
		if (!formData.value.type) {
			uni.showToast({ icon: 'none', title: '请选择盘点结果' })
			return false;
		}

		loading.value = true
		formData.value.check_time = uni.$u.date(formData.value.check_time, 'yyyy-mm-dd');
		addCheck(formData.value).then((res : any) => {
			loading.value = false
			if (res.code == 1) {
				redirect({ url: '/addon/erp/pages/index' })
			}
		}).catch((err) => {
			// 如果是4001，没有绑定企业账号，强制跳转绑定
			if (err.code == 4001) {
				redirect({ url: '/addon/erp/pages/member/bind' })
			}
			loading.value = false
		})

		// console.log("formRef.value", formRef.value);
		// console.log("formData.value", formData.value);
		// return;
		// formRef.value.validate().then(() => {

		// }).catch(err => {
		// 	console.log("err", err);
		// })
	}
</script>

<style lang="scss" scoped>
	.form-edit :deep(.up-form-item__body__left__content__label) {
		font-size: 28rpx !important;
	}

	.form-edit :deep(.up-form-item__body__right) {
		display: flex;
		align-items: center;
	}

	.footer {
		height: calc(100rpx + var(--top-m) + var(--top-m) + constant(safe-area-inset-bottom)) !important;
		height: calc(100rpx + var(--top-m) + var(--top-m) + env(safe-area-inset-bottom)) !important;
	}
</style>