<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="180rpx">
			<view class="sidebar-margin card-template mt-[var(--top-m)] py-[20rpx]">
				<view>
					<up-form-item :label="t('supplierId')" prop="supplier_id" required borderBottom>
						<view class="flex w-full items-center h-[52rpx]" @click="supplierSheetShow = true">
							<view v-if="!formData.supplier_id" class="text-[#888] text-[28rpx] flex-1">
								{{ t('supplierIdPlaceholder') }}
							</view>
							<view v-else class="text-[28rpx] flex-1 leading-[1.4]">{{ formData.supplier_name }}</view>
						</view>
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('warehouseId')" prop="warehouse_id" 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('warehouseIdPlaceholder') }}
							</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('type')" prop="type" borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.type" border="none" clearable
							placeholderStyle="color: #888" :placeholder="t('typePlaceholder')" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('deliveryTime')" prop="delivery_time" borderBottom>
						<view class="flex w-full items-center h-[52rpx]" @click="deliveryTimeShow = true">
							<view v-if="!formData.delivery_time" class="text-[#888] text-[28rpx] flex-1">
								{{ t('deliveryTimePlaceholder') }}
							</view>
							<view v-else class="text-[28rpx] flex-1 leading-[1.4]">{{ formData.delivery_time }}</view>
						</view>
						<u-datetime-picker @cancel="deliveryTimeShow = false" @confirm="deliveryTimeConfirm"
							:show="deliveryTimeShow" v-model="formData.delivery_time"
							:placeholder="t('deliveryTimePlaceholder')" mode="date"></u-datetime-picker>
					</up-form-item>
				</view>

				<view class="mt-[16rpx]">
					<up-form-item :label="t('billingTime')" prop="billing_time" borderBottom>
						<view class="flex w-full items-center h-[52rpx]" @click="billingTimeShow = true">
							<view v-if="!formData.billing_time" class="text-[#888] text-[28rpx] flex-1">
								{{ t('billingTimePlaceholder') }}
							</view>
							<view v-else class="text-[28rpx] flex-1 leading-[1.4]">{{ formData.billing_time }}</view>
						</view>
						<u-datetime-picker @cancel="billingTimeShow = false" @confirm="billingTimeConfirm"
							:show="billingTimeShow" v-model="formData.billing_time"
							:placeholder="t('billingTimePlaceholder')" mode="date"></u-datetime-picker>
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('rate')" prop="rate" borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.rate" border="none" clearable
							placeholderStyle="color: #888" :placeholder="t('ratePlaceholder')" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('remark')" prop="remark">
						<u-textarea fontSize="28rpx" v-model="formData.remark" :placeholder="t('remarkPlaceholder')"
							border="none"></u-textarea>
					</up-form-item>
				</view>
			</view>

			<view class="mx-[var(--sidebar-m)] bg-[#ffffff] rounded mt-[20rpx]">
				<view class="flex justify-between py-[10rpx] px-[20rpx] box-border border-0 border-b-1 border-color-[#dadbde] border-solid
				">
					<view class="text-base font-bold">{{t('Enter product')}}</view>
					<view><u-button @click="goProductSelect" icon="plus" type="primary" :plain="true" size="mini"
							:text="t('Add product')"></u-button>
					</view>
				</view>

				<view v-if="formData.product.length > 0" class="sidebar-margin mt-[20rpx] pb-[20rpx] body-bottom">
					<view class="mb-[15rpx]" v-for="(item, index) in formData.product" :key="index">

						<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><u-button :plain="true" type="error" @click="hanldeDelete(index)"
											:text="t('delete')" size="mini"></u-button></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('productCode') }}:<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('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]">
										<view class="content-center">
											{{ t('purchasePrice') }}:
										</view>
										<view class="ml-[20rpx]">
											<u-number-box min="0" v-model="item.purchase_price" :integer="true"
												inputWidth="80"></u-number-box>
										</view>

									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										<view class="content-center">
											{{ t('purchaseQuantity') }}:
										</view>
										<view class="ml-[20rpx]">
											<u-number-box min="1" v-model="item.purchase_quantity" :integer="true"
												inputWidth="80"></u-number-box>
										</view>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										{{ t('totalPrice') }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{ item.purchase_quantity * item.purchase_price }}</text>
									</view>

								</view>
							</view>
						</view>
					</view>
				</view>
				<view v-else class="sidebar-margin mt-[20rpx] body-bottom text-center">
					<text class="text-sm text-color-[#848484]">暂未选择产品</text>
				</view>
			</view>



		</up-form>
		<!-- 产品分类 -->
		<u-action-sheet class="" :actions="supplierList" :show="supplierSheetShow" :closeOnClickOverlay="true"
			:safeAreaInsetBottom="true" @close="supplierSheetShow = false" @select="updateSex"></u-action-sheet>

		<!-- 产品单位 -->
		<u-action-sheet class="" :actions="warehouseList" :show="warehouseSheetShow" :closeOnClickOverlay="true"
			:safeAreaInsetBottom="true" @close="warehouseSheetShow = false"
			@select="updateSexWarehouse"></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 { getSupplierSelect, getWarehouseSelect } from '@/addon/erp/api/base';
	import { addOrder } from '@/addon/erp/api/purchase';
	import { generatedCode } from '@/addon/erp/utils/common';
	import { redirect } from '@/utils/common';
	import dayjs from 'dayjs'

	const formRef : any = ref(null)
	const loading = ref(false)


	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("CG"),
		supplier_id: "",
		supplier_name: "",
		delivery_time: dayjs().format('YYYY-MM-DD'),
		type: "",
		warehouse_id: "",
		warehouse_name: "",
		billing_time: dayjs().format('YYYY-MM-DD'),
		remark: "",
		rate: 16,
		product: [] as any[],
		total_num: 0,
		money: 0,
		total_money: 0
	})

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

	// 页面加载
	onLoad((option : any) => {


		getSupplierList();
		getWarehouseList();

		// 接收子页面传值
		uni.$on('choose_product', res => {
			const uniqueItems : any = {};
			formData.value.product.forEach(item => {
				uniqueItems[item.code] = item;
			});

			res.forEach(item => {
				if (!uniqueItems[item.code]) {
					uniqueItems[item.code] = item;
				}
			});
			const uniqueArray = Object.values(uniqueItems);
			formData.value.product = uniqueArray.map(item => {
				item.purchase_price = 0;
				item.purchase_quantity = 1;
				item.unit = item.productUnit?.name
				return item;
			});

		})
	})

	/**
	 * 供应商
	 */
	const supplierSheetShow = ref(false)
	const supplierList = ref<any[]>([]);
	const updateSex = (e : any) => {
		formData.value.supplier_id = e.id;
		formData.value.supplier_name = e.name;
		if (formRef.value) {
			formRef.value.validateField('supplier_id');
		}
	}
	// 获取供应商
	const getSupplierList = () => {
		getSupplierSelect({}).then((res : any) => {
			supplierList.value = res.data;
		}).catch(err => {
			// 如果是4001，没有绑定企业账号，强制跳转绑定
			if (err.code == 4001) {
				redirect({ url: '/addon/erp/pages/member/bind' })
			}
		})
	}

	/**
	 * 仓库
	 */
	const warehouseSheetShow = ref(false)
	const warehouseList = ref<any[]>([]);
	const updateSexWarehouse = (e : any) => {
		formData.value.warehouse_id = e.id;
		formData.value.warehouse_name = e.name;
		if (formRef.value) {
			formRef.value.validateField('warehouse_id');
		}
	}
	// 获取仓库
	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 goProductSelect = () => {
		if (!formData.value.warehouse_id) {
			uni.showToast({ icon: 'none', title: t('warehouseIdPlaceholder') })
			return false;
		}

		return redirect({
			url: '/addon/erp/pages/product/product/product-select',
			param: {
				type: 'all'
			},
		})
	}

	/**
	 * 交货日期
	 */
	const deliveryTimeShow = ref(false);
	const deliveryTimeConfirm = (e : any) => {
		formData.value.delivery_time = uni.$u.date(e.value, 'yyyy-mm-dd');
		deliveryTimeShow.value = false;
	}

	/**
	 * 制单日期
	 */
	const billingTimeShow = ref(false);
	const billingTimeConfirm = (e : any) => {
		formData.value.billing_time = uni.$u.date(e.value, 'yyyy-mm-dd');
		billingTimeShow.value = false;
	}

	// 删除
	const hanldeDelete = (index : number) => {
		formData.value.product.splice(index, 1);
	}

	// 总金额
	const totalData = computed(() => {
		let data = {
			money: 0,
			total_money: 0,
			nums: 0,
		};
		for (let item of formData.value.product) {
			let amount = Number(item.purchase_quantity) * Number(item.purchase_price);
			data.money += amount;
			data.nums += Number(item.purchase_quantity);
		}
		// 税后金额
		data.total_money = data.money + data.money * (formData.value.rate / 100);
		return data;
	});

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

		if (!formData.value.supplier_id) {
			uni.showToast({ icon: 'none', title: t('supplierIdPlaceholder') })
			return false;
		}
		if (!formData.value.warehouse_id) {
			uni.showToast({ icon: 'none', title: t('warehouseIdPlaceholder') })
			return false;
		}

		loading.value = true

		formData.value.total_num = totalData.value.nums;
		formData.value.money = totalData.value.money;
		formData.value.total_money = totalData.value.total_money;

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