<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="t('warehouseName')" prop="type" required borderBottom>
						<view class="flex w-full items-center h-[52rpx]" @click="warehouseSheetShow = true">
							<view v-if="!formData.warehouse_id" class="text-[#888] text-[28rpx] flex-1">
								{{ t('warehouseNamePlaceholder') }}
							</view>
							<view v-else class="text-[28rpx] flex-1 leading-[1.4]">{{ formData.warehouse_name }}</view>
						</view>
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('productName')" prop="product_id" required borderBottom>
						<view class="flex w-full items-center h-[52rpx]" @click="productSheetShow = true">
							<view v-if="!formData.product_id" class="text-[#888] text-[28rpx] flex-1">
								{{ t('productName') }}
							</view>
							<view v-else class="text-[28rpx] flex-1 leading-[1.4]">{{ formData.product_name }}</view>
						</view>
					</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 border="none"
							clearable placeholderStyle="color: #888" :placeholder="t('surfaceNumPlaceholder')" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('number')" prop="number" required borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.number" border="none" clearable
							placeholderStyle="color: #888" :placeholder="t('numberPlaceholder')" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('type')" prop="type" required borderBottom>
						<up-radio-group v-model="formData.type" placement="row">
							<up-radio :customStyle="{marginBottom: '8px'}" v-for="(item, index) in typeList"
								:key="index" :label="item" :name="index">
							</up-radio>
						</up-radio-group>
					</up-form-item>
				</view>
			</view>



		</up-form>
		<!-- 仓库 -->
		<u-action-sheet class="" :actions="warehouseList" :show="warehouseSheetShow" :closeOnClickOverlay="true"
			:safeAreaInsetBottom="true" @close="warehouseSheetShow = false"
			@select="updateSexWarehouse"></u-action-sheet>

		<!-- 产品 -->
		<u-action-sheet class="" :actions="productList" :show="productSheetShow" :closeOnClickOverlay="true"
			:safeAreaInsetBottom="true" @close="productSheetShow = false" @select="updateSexProduct"></u-action-sheet>

		<view 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 { addInventory, getInventoryTypeList, getInventoryProduct } from '@/addon/erp/api/inventory';
	import { redirect } from '@/utils/common';

	const formRef : any = ref(null)
	const loading = ref(false)
	const typeList = 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: "",
		warehouse_id: "",
		warehouse_name: "",
		product_id: "",
		product_name: "",
		surface_num: "",
		number: "",
		real_num: "",
		type: "",

	})

	onReady(() => {
		formRef.value.setRules(rules);
	})

	// 页面加载
	onLoad((option : any) => {
		getTypeAllFn();
		getWarehouseList();
	})

	// 获取状态
	const getTypeAllFn = () => {
		getInventoryTypeList().then((res) => {
			typeList.value = res.data;
		});
	};


	/**
	 * 仓库
	 */
	const warehouseSheetShow = ref(false)
	const warehouseList = ref<any[]>([]);
	const updateSexWarehouse = (e : any) => {
		formData.value.warehouse_id = e.id;
		formData.value.warehouse_name = e.name;
		getInventoryProduct({
			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 productSheetShow = ref(false);
	const productList = ref<any[]>([]);
	const updateSexProduct = (e : any) => {
		formData.value.product_id = e.id;
		formData.value.product_name = e.name;

		handleProductIdChange(e.id);
	}

	// 产品选择事件
	const handleProductIdChange = (val : number) => {
		const product = productList.value.find((item) => item.id === val);
		if (product) {
			formData.value.surface_num = product.surface_num;
		}
	};


	// 保存
	const handSave = () => {
		if (loading.value) return

		if (!formData.value.warehouse_id) {
			uni.showToast({ icon: 'none', title: t('warehouseNamePlaceholder') })
			return false;
		}
		if (!formData.value.product_id) {
			uni.showToast({ icon: 'none', title: t('productNamePlaceholder') })
			return false;
		}
		if (!formData.value.number) {
			uni.showToast({ icon: 'none', title: t('numberPlaceholder') })
			return false;
		}
		if (!formData.value.type) {
			uni.showToast({ icon: 'none', title: t('typePlaceholder') })
			return false;
		}

		loading.value = true

		addInventory(formData.value).then((res : any) => {
			loading.value = false
			if (res.code == 1) {
				redirect({ url: '/addon/erp/pages/inventory/inventory/list' })
			}
		}).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>