<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('sellList')" 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('sellList') }}
							</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="customer.contact" required borderBottom>
						<u-input fontSize="28rpx" v-model="formData.customer.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="customer.phone" required borderBottom>
						<u-input fontSize="28rpx" v-model="formData.customer.phone" border="none" clearable
							placeholderStyle="color: #888" :placeholder="t('phonePlaceholder')" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<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('warehousePlaceholder') }}
							</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('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]">
										{{ t('sellQuantity') }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{item.num}}</text>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										<view class="content-center">
											{{ t('returnQuantity') }}:
										</view>
										<view class="ml-[20rpx]">
											<u-number-box min="0" v-model="item.return_num" :max="item.num"
												: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.subtotal }}</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>

		<u-action-sheet class="" :actions="warehouseList" :show="warehouseSheetShow" :closeOnClickOverlay="true"
			:safeAreaInsetBottom="true" @close="warehouseSheetShow = false"
			@select="updateSexWarehouse"></u-action-sheet>
	</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 { addSellReturn, getSellInfo } from '@/addon/erp/api/sell';
	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({
		sell_id: "",
		sell_code: "",
		code: generatedCode("TH"),
		customer: {
			name: "",
			contact: "",
			phone: "",
		},
		city: "",
		address: "",
		type: "",
		rate: "16",
		billing_time: dayjs().format('YYYY-MM-DD'),
		warehouse_id: '',
		warehouse_name: '',
		remark: "",
		productList: [] as any[],
		total_num: 0,
		money: 0,
		total_money: 0
	})

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

	// 页面加载
	onLoad((option : any) => {
		getWarehouseList();
		// 接收子页面传值
		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.return_num) * Number(item.price);
			data.money += amount;
			data.nums += Number(item.return_num);
		}
		return 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;
		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 getSellInfoFn = async (id : number) => {
		const data = await (await getSellInfo(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;
	};

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

	/**
	 * 制单日期
	 */
	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.sell_id) {
			uni.showToast({ icon: 'none', title: t('sellCodePlaceholder') })
			return false;
		}
		if (!formData.value.customer.contact) {
			uni.showToast({ icon: 'none', title: t('contactPlaceholder') })
			return false;
		}
		if (!formData.value.customer.phone) {
			uni.showToast({ icon: 'none', title: t('phonePlaceholder') })
			return false;
		}
		if (!formData.value.warehouse_id) {
			uni.showToast({ icon: 'none', title: t('warehousePlaceholder') })
			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;
		formData.value.money = totalData.value.money;

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