<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('sellDelivery')" prop="sell_id" required borderBottom>
						<view class="flex w-full items-center h-[52rpx]" @click="goSellSelect">
							<view v-if="!formData.sell_id" class="text-[#888] text-[28rpx] flex-1">
								{{ t('sellDeliveryPlaceholder') }}
							</view>
							<view v-else class="text-[28rpx] flex-1 leading-[1.4]">{{ formData.sell_code }}</view>
						</view>
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('contact')" prop="contact" required borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.contact" border="none" clearable
							placeholderStyle="color: #888" :placeholder="t('contactPlaceholder')" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('phone')" prop="phone" required borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.phone" border="none" clearable
							placeholderStyle="color: #888" :placeholder="t('phonePlaceholder')" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('type')" prop="type" required 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" required 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.billing_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" required 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('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('productList')}}</view>
				</view>

				<view v-if="formData.productList.length > 0" class="sidebar-margin mt-[20rpx] pb-[20rpx] body-bottom">
					<view class="mb-[15rpx]" v-for="(item, index) in formData.productList" :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.products?.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('productCode') }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{item.products?.code}}</text>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										{{ t('productSpec') }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{item.products?.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.unit}}</text>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										{{ t('sellPrice') }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{item.price}}</text>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										<view class="content-center">
											{{ t('sellQuantity') }}:
										</view>
										<view class="ml-[20rpx]">
											<u-number-box min="0" v-model="item.num" :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('warehouseName') }}:
										</view>
										<view class="ml-[20rpx] flex-1">
											<!-- 仓库 -->
											<my-select :disabled="false" v-model="item.wp_id" label_key="warehouse_name"
												value_key="id" :options="item.warehouseList"
												@change="onWarehouseChange" />
										</view>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										{{ t('canUseInventory') }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{item.inventory}}</text>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										{{ t('totalPrice') }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{ totalData.money }}</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]">{{t('sellDeliveryPlaceholder')}}</text>
				</view>
			</view>



		</up-form>


		<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 { getCustomerSelect } from '@/addon/erp/api/base';
	import { addDelivery, getDeliverySellInfo } from '@/addon/erp/api/sell';
	import { generatedCode } from '@/addon/erp/utils/common';
	import { redirect } from '@/utils/common';
	import MySelect from '@/addon/erp/components/u-select/index.vue';
	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({
		sell_id: "",
		sell_code: "",
		code: generatedCode("CK"),
		customer_id: "",
		customer_name: "",
		contact: "",
		phone: "",
		city: "",
		address: "",
		type: "",
		rate: "16",
		billing_time: dayjs().format('YYYY-MM-DD'),
		delivery_time: dayjs().format('YYYY-MM-DD'),
		remark: "",
		productList: [] as any[],
		total_num: 0,
		money: 0,
		total_money: 0
	})

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

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

		// 接收子页面传值
		uni.$on('choose_sell', res => {
			getSellInfoFn(res.id);
		})
	})

	// 总金额
	const totalData = computed(() => {
		let data = {
			money: 0,
			nums: 0,
		};
		for (let item of formData.value.productList) {
			let amount = Number(item.num) * Number(item.price);
			data.money += amount;
			data.nums += Number(item.num);
		}
		return data;
	});


	// 获取销售单明细
	const getSellInfoFn = async (id : number) => {
		const data = await (await getDeliverySellInfo(id)).data;
		if (data)
			Object.keys(formData.value).forEach((key : string) => {
				if (data[key] != undefined && key != "code") formData.value[key] = data[key];
			});
		let cityArray = formData.value.city.split(",");
		formData.value.city = cityArray.map((item : any) => parseInt(item));
		formData.value.sell_id = id;
		formData.value.sell_code = data.code;
	};

	/**
	 * 仓库选择事件
	 * @param id
	 */
	const onWarehouseChange = (id : string | number) => {
		formData.value.productList.forEach((item : any) => {
			item.warehouseList.forEach((ware : any) => {
				if (id == ware.id) {
					item.inventory = ware.inventory;
				}
			});
		});
	};

	// 跳转到销售单选择页
	const goSellSelect = () => {
		return redirect({
			url: '/addon/erp/pages/sell/sell/sell-select',
			param: {
				status: 5
			}
		})
	}

	/**
	 * 交货日期
	 */
	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 handSave = () => {
		if (loading.value) return

		if (!formData.value.customer_id) {
			uni.showToast({ icon: 'none', title: t('customerIdPlaceholder') })
			return false;
		}
		if (!formData.value.type) {
			uni.showToast({ icon: 'none', title: t('typePlaceholder') })
			return false;
		}
		if (!formData.value.delivery_time) {
			uni.showToast({ icon: 'none', title: t('deliveryTimePlaceholder') })
			return false;
		}
		if (!formData.value.billing_time) {
			uni.showToast({ icon: 'none', title: t('billingTimePlaceholder') })
			return false;
		}

		loading.value = true

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

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