<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('customerName')" prop="customer_id" required borderBottom>
					<!-- 	<zxz-uni-data-select v-model="formData.customer_id" :localdata="[]" dataKey="name" dataValue="id" 
						:clear="false" placeholder="请选择食堂" @change="customeChange" /> -->
						<!-- 	<uni-data-select v-model="formData.customer_id" :localdata="canteenList" placeholder="请选择食堂" @change="customeChange"></uni-data-select> -->
						<!-- #ifdef H5 -->
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<!-- <wht-select v-model="formData.customer_id" :options="canteenList" dataKey="name" dataValue="id"   placeholder="请选择食堂" :height="38" @change="customeChange"/> -->
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="'出库单'" prop="manual_id" required borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.manual_id" :localdata="manualSelectList" dataKey="code" dataValue="id"
						:clear="false" :disabled="formData.customer_id == ''" :placeholder="formData.customer_id == ''?'请先选择食堂':'请选择出库单'" @change="manualIdChange" />
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.manual_id" :options="manualSelectList" dataKey="code" dataValue="id"  :disabled="formData.customer_id == ''" :placeholder="formData.customer_id == ''?'请先选择食堂':'请选择出库单'" :backgroundColor="formData.customer_id == ''?'#f5f7fa':'#ffffff'" :height="38" @change="manualIdChange"/>
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('contact')" prop="contact"  borderBottom>
						<u-input fontSize="28rpx" v-model="formData.contact"  clearable
							placeholderStyle="color: #888" :placeholder="t('contactPlaceholder')" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('phone')" prop="phone"  borderBottom>
						<u-input fontSize="28rpx" v-model="formData.phone"  clearable
							placeholderStyle="color: #888" :placeholder="t('phonePlaceholder')" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="'详细地址'" prop="address"  borderBottom>
						<u-input fontSize="28rpx" v-model="formData.address"  clearable
							placeholderStyle="color: #888" :placeholder="'请输入详细地址'" />
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('warehouseName')" prop="type" required borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.warehouse_id" :localdata="warehouseList" dataKey="name" dataValue="id" 
						:clear="false" disabled placeholder="请选择仓库"/>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.warehouse_id" :options="warehouseList" dataKey="name" dataValue="id"  disabled  placeholder="请选择仓库" backgroundColor="#f5f7fa" :height="38"/>
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('billingTime')" prop="billing_time" required borderBottom>
						 <up-datetime-picker hasInput :show="billingTimeShow" v-model="formData.billing_time" mode="date" :placeholder="t('billingTimePlaceholder')" ></up-datetime-picker>
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="t('reason')" prop="reason">
						<u-textarea fontSize="28rpx" v-model="formData.reason" :placeholder="t('reasonPlaceholder')">
						</u-textarea>
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('inboundImage')" prop="inbound_image" borderBottom>
						<up-upload
							:fileList="imageFileList"
							@afterRead="afterRead"
							multiple
							:maxCount="5"
							: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('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.product?.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.product?.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.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.unit}}</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.num}}</text>
									</view>
									<view class="flex justify-start mb-[18rpx] text-[12px] text-[#6a6a6a]">
										{{ '已退数量' }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{item.returned_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]">
										<view class="content-center">
											单价:
										</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]">
										{{ t('totalPrice') }}:<text
											class="ml-[20rpx] text-[var(--primary-color)]">{{ item.return_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]">{{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 { getWarehouseSelect,getCustomerSelect} from '@/addon/erp/api/base';
	import { addManualReturn, getOutboundManualSelect,getOutboundManualInfo} from '@/addon/erp/api/sell';
	import { generatedCode } from '@/addon/erp/utils/common';
	import {uploadImage } from '@/app/api/system'
	import { redirect } from '@/utils/common';
	import { checkBtnPermission } from '@/utils/auth';
	import useMemberStore from '@/stores/member'
	import dayjs from 'dayjs'
	
	const memberStore = useMemberStore()
	
	interface FileItem {
	  url: string;
	  status?: string;
	  message?: string;
	}
	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 canteenList = ref<any[]>([]);
	const imageFileList=ref<FileItem[]>([])
	const formData = ref({
		code: generatedCode("ST"),
		customer_id: '',
		warehouse_id: '',
		manual_id: '',
		billing_time: dayjs().format('YYYY-MM-DD'),
		reason: '',
		contact: '',
		phone: '',
		address: '',
		inbound_image:"",
		productList: [] as any[],
		total_num:0,
		total_amount:0,
	})

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

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


	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: result as string,
	    });
	    fileListLen++;
	  }
	}
	
	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 manualSelectList = ref<any>([])
	const getOutboundManualAllFn = (id: number) => {
		getOutboundManualSelect(id)
			.then(({ data }) => {
				manualSelectList.value = data
			})
			.catch()
	}
	const manualIdChange=(e: any) =>{
		getOutboundManualInfoFn(e.id)
	}
	const getOutboundManualInfoFn = async (id: any) => {
	    const data = await (await getOutboundManualInfo(id)).data
	    if (data) {
	        Object.keys(formData.value ).forEach((key: string) => {
	            if (data[key] != undefined && key != 'code') {
					(formData.value as any)[key] = data[key];
	            }
	        })
			formData.value.productList=formData.value.productList.map((item:any)=>{
				item.return_num = item.return_num ? Number(item.return_num) : 0
				return item 
			})
	    }
	    formData.value.manual_id = id
	}
	/**
	 * 仓库
	 */
	const warehouseList = ref<any[]>([]);
	// 获取仓库
	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 customeChange=(e: any) =>{
		 formData.value.customer_id = e.id
		 formData.value.contact = e.contact
		 formData.value.phone = e.phone
		 formData.value.address = e.address
		 getOutboundManualAllFn(e.id)
		if (formRef.value) {
			formRef.value.validateField('customer_id');
		}
	}
	// 获取食堂
	const getCanteenList = () => {
		getCustomerSelect({}).then((res : any) => {
			canteenList.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 totalData = computed(() => {
	    const data = {
	        total_amount: 0,
	        total_num: 0
	    }
	    for (const item of formData.value.productList) {
	        const amount = Number(item.return_num) * Number(item.price)
	        data.total_amount += amount
	        data.total_num += Number(item.return_num)
	    }
	    return data
	})


	// 保存
	const handSave = () => {
		const hasPermission = checkBtnPermission(memberStore.btnPermission, 'erp_inbound_return_add')
		if (!hasPermission) return
		if (loading.value) return
		if (!formData.value.manual_id) {
			uni.showToast({ icon: 'none', title: '请选择出库单' })
			return false;
		}
		if (!formData.value.warehouse_id) {
			uni.showToast({ icon: 'none', title: '请选择仓库' })
			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.total_num;
		formData.value.total_amount = totalData.value.total_amount;
		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)=>item.url)
			formData.value.inbound_image=imgUrls.join(',')
		}
		addManualReturn(formData.value).then((res : any) => {
			loading.value = false
			if (res.code == 1) {
				redirect({ url: '/addon/erp/pages/canteen/return/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>