<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('code')" prop="code" required borderBottom>
						<u-input fontSize="28rpx" v-model="formData.code" disabled  clearable
							placeholderStyle="color: #888" :placeholder="t('codePlaceholderNew')" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('supplierName')" prop="supplier_id" required borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.supplier_id" :localdata="supplierList" dataKey="name" dataValue="id"
						:clear="false"  placeholder="请选择供应商" @change="supplierIdChange"/>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.supplier_id" :options="supplierList" dataKey="name" dataValue="id" placeholder="请选择供应商"  :height="38" @change="supplierIdChange"/>
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('warehouseName')" 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="warehouseIdChange"/>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.warehouse_id" :options="warehouseList" dataKey="name" dataValue="id" placeholder="请选择仓库"  :height="38" @change="warehouseIdChange"/>
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('billingTime')" prop="billing_time" required borderBottom @click="billingTimeShow = true">
						<!-- #ifdef H5 -->
						<up-datetime-picker hasInput :show="billingTimeShow" v-model="formData.billing_time" mode="date" :placeholder="t('billingTimePlaceholder')" @confirm="billingTimeConfirm" @cancel="billingTimeShow = false"></up-datetime-picker>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<u-input fontSize="28rpx" v-model="formData.billing_time"  readonly
							placeholderStyle="color: #888" :placeholder="t('billingTimePlaceholder')" />
						<up-datetime-picker :show="billingTimeShow" v-model="billing_time_new" mode="date" :placeholder="t('billingTimePlaceholder')" @confirm="billingTimeConfirm" @cancel="billingTimeShow = false"></up-datetime-picker>
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('remark')" prop="remark">
						<u-textarea fontSize="28rpx" v-model="formData.reason" :placeholder="t('remarkPlaceholder')"
							></u-textarea>
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('image')" required prop="image" borderBottom>
						<up-upload
							:fileList="imageFileList"
							@afterRead="afterRead"
							@delete="imageDelete"
							multiple
							:maxCount="5"
							accept="image"
							:capture="['camera']"
						></up-upload>
					</u-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.product?.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.product?.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.product?.productType?.name}}</text>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										{{ t('productSpec') }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{item.product?.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.product?.productUnit?.name}}</text>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										{{ '批次号' }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{item.batch_number}}</text>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										{{ '库存数量' }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{item.inventory}}</text>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										<view class="content-center">
											{{ t('retirePrice') }}:
										</view>
										<view class="ml-[20rpx]">
											<u-number-box min="0" v-model="item.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('retireQuantity') }}:
										</view>
										<view class="ml-[20rpx]">
											<u-number-box min="1" v-model="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.num * item.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>

		<view v-if="hasPermission('erp_outbound_return_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 { getSupplierSelect, getWarehouseSelect } from '@/addon/erp/api/base';
	import { addReturn } from '@/addon/erp/api/purchase';
	import { generatedCode } from '@/addon/erp/utils/common';
	import {uploadImage } from '@/app/api/system'
	import { redirect } from '@/utils/common';
	import dayjs from 'dayjs'
	import useMemberStore from '@/stores/member'
	import { img } from '@/utils/common'
	import usePermission from '@/utils/usePermission'
	const { hasPermission } = usePermission()
	interface FileItem {
	  url: string;
	  status?: string;
	  message?: string;
	}
	const memberStore = useMemberStore()
	
	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 imageFileList=ref<FileItem[]>([])
	const formData = ref({
		id: "",
		code: generatedCode("CT"),
		supplier_id: '',
		warehouse_id: '',
		billing_time: dayjs().format('YYYY-MM-DD'),
		product: [] as any[],
		outbound_image: '',
		reason: '',
		total_num:0,
		total_amount:0,
	})
	const billing_time_new=ref(dayjs().format('YYYY-MM-DD'))
	
	onReady(() => {
		formRef.value.setRules(rules);
	})

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

		getSupplierList();
		getWarehouseList();

		// 接收子页面传值
		uni.$on('choose_product-out', res => {
			const uniqueItems : any = {};
			formData.value.product.forEach(item => {
				uniqueItems[item.product.code] = item;
			});
		
			res.forEach((item:any) => {
				if (!uniqueItems[item.product.code]) {
					uniqueItems[item.product.code] = item;
				}
			});
			const uniqueArray = Object.values(uniqueItems);
			formData.value.product = uniqueArray.map((item:any) => {
				item.num = 1;
				item.unit=item!.product.productUnit ? item!.product.productUnit!.name : ''
				item.price= item.price || 0
				return item;
			});
		
		})
	})

	/**
	 * 供应商
	 */
	const supplierList = ref<any[]>([]);
	const supplierIdChange = (e : any) => {
		formData.value.supplier_id = e.id;
		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 afterRead = async (event: any) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists:FileItem[] = [].concat(event.file) ;
	  let fileListLen = imageFileList.value.length;
	  lists = lists.filter((item:FileItem) => item.url);
	  lists.map((item: any) => {
	    imageFileList.value.push({
		  url: item.url,
	      status: 'uploading',
	      message: '上传中',
	    });
	  })
	  for (let i = 0; i < lists.length; i++) {
	    const result = await uploadFilePromise(lists[i].url);
	    let item = imageFileList.value[fileListLen];
	    imageFileList.value.splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: img(result as string),
	    });
	    fileListLen++;
	  }
	}
	const imageDelete = (event:any) => {
		if (event.index !== undefined && event.file !== undefined) {
			const imageIndex = event.index;
			const currentFileList = imageFileList.value;
			currentFileList.splice(imageIndex, 1);
			imageFileList.value = [...imageFileList.value];
		}
	}
	const uploadFilePromise = (url: any) => {
	  return new Promise((resolve, reject) => {
	    let a = uploadImage({
			filePath:url,
			name: 'file'
	    }).then((res:any)=>{
			setTimeout(() => {
			  resolve(res.data.url as string);
			}, 1000);
		})
	  });
	}
	
	// 跳转到食材选择页
	const goProductSelect = () => {
		if (!formData.value.supplier_id) {
			uni.showToast({ icon: 'none', title: '请选择供应商' })
			return false;
		}
		if (!formData.value.warehouse_id) {
			uni.showToast({ icon: 'none', title: t('warehouseIdPlaceholder') })
			return false;
		}

		return redirect({
			url: '/addon/erp/pages/product/product/out-product-select',
			param: {
				warehouse_id: formData.value.warehouse_id,
				supplier_id: formData.value.supplier_id,
			},
		})
	}

	/**
	 * 仓库
	 */
	const warehouseList = ref<any[]>([]);
	const warehouseIdChange = (e : any) => {
		formData.value.warehouse_id = e?.id ?? '';
		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 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,
			nums: 0,
		};
		for (let item of formData.value.product) {
			let amount = Number(item.num) * Number(item.price);
			data.money += amount;
			data.nums += Number(item.num);
		}
		return data;
	});

	// 保存
	const handSave = async() => {
		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;
		}
		if (!formData.value.billing_time) {
			uni.showToast({ icon: 'none', title: t('billingTimePlaceholder') })
			return false;
		}
		if (imageFileList.value.length === 0) {
			uni.showToast({ icon: 'none', title: '请上传图片' })
			return false;
		}
		loading.value = true
		formData.value.total_num = totalData.value.nums;
		formData.value.total_amount = totalData.value.money;
		formData.value.billing_time = uni.$u.date(formData.value.billing_time, 'yyyy-mm-dd');
		if(imageFileList.value.length > 0){
			const imgUrls=imageFileList.value.map((item:any)=>{
				return `upload${item.url.split('upload')[1]}`
			})|| []
			formData.value.outbound_image=imgUrls.join(',')
		}

		addReturn(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>