<template>
	<view class="bg-[var(--page-bg-color)] min-h-[100vh] overflow-hidden form-edit" :style="themeColor()">
		<u-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>
					<u-form-item :label="t('productTypeId')" prop="product_type_id" required borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.product_type_id" :localdata="pidList" dataKey="name" dataValue="id"
						:clear="false"  placeholder="请选择食材类型" @change="updateSex"/>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.product_type_id" :options="pidList" dataKey="name" dataValue="id" :defaultVal="formData.product_type_id" placeholder="请选择食材类型"  :height="38" @change="updateSex"/>
						<!-- #endif -->
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('code')" prop="code" required borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.code" disabled  clearable
							placeholderStyle="color: #888" :placeholder="t('codePlaceholderNew')" />
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('name')" prop="name" required borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.name"  clearable
							placeholderStyle="color: #888" :placeholder="t('namePlaceholder')" />
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('productUnitId')" required prop="product_unit_id" borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.product_unit_id" :localdata="unitList" dataKey="name" dataValue="id"
						:clear="false"  placeholder="请选择单位" @change="updateSexUnit"/>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.product_unit_id" :options="unitList" dataKey="name" dataValue="id" :defaultVal="formData.product_type_id" placeholder="请选择单位"  :height="38" @change="updateSexUnit"/>
						<!-- #endif -->
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('spec')" prop="spec" borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.spec"  clearable
							placeholderStyle="color: #888" :placeholder="t('specPlaceholder')" />
					</u-form-item>
				</view>

				<view class="mt-[16rpx]">
					<u-form-item :label="t('minWarning')" prop="min_warning" borderBottom>
						<u-input fontSize="28rpx" type="number" v-model="formData.min_warning"
							:placeholder="t('minWarningPlaceholder')" ></u-input>
					</u-form-item>
				</view>

				<view class="mt-[16rpx]">
					<u-form-item :label="t('maxWarning')" prop="max_warning" borderBottom>
						<u-input fontSize="28rpx" type="number" v-model="formData.max_warning"  clearable
							maxlength="120" :placeholder="t('maxWarningPlaceholder')" placeholderStyle="color: #888" />
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('expiryTerm')" prop="expiry_term" borderBottom>
						<u-input fontSize="28rpx" type="number" v-model="formData.expiry_term"  clearable
							maxlength="120" :placeholder="t('expiryTermPlaceholder')" placeholderStyle="color: #888" />
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('expiryAlertTerm')" prop="expiry_alert_term" borderBottom>
						<u-input fontSize="28rpx" type="number" v-model="formData.expiry_alert_term"  clearable
							maxlength="120" :placeholder="t('expiryAlertTermPlaceholder')" placeholderStyle="color: #888" />
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('remark')" prop="remark">
						<u-textarea fontSize="28rpx" v-model="formData.remark" :placeholder="t('remarkPlaceholder')"
							></u-textarea>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('image')" 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>

		</u-form>
		<view v-if="hasPermission('erp_product_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 } from '@dcloudio/uni-app';
	import { getProductTypeSelect, getProductUnitSelect, addProduct } from '@/addon/erp/api/product';
	import { generatedCode } from '@/addon/erp/utils/common';
	import {uploadImage } from '@/app/api/system'
	import { redirect } from '@/utils/common';
	import useMemberStore from '@/stores/member'
	import usePermission from '@/utils/usePermission'
	const { hasPermission } = usePermission()
	const memberStore = useMemberStore()
	interface FileItem {
	  url: string;
	  status?: string;
	  message?: string;
	}
	const formRef : any = ref(null)
	const loading = ref(false)

	const areaRef = ref()
	const isSelectAddress = ref(false)

	const rules = computed(() => {
		return {
			'product_type_id': {
				type: 'number',
				required: true,
				message: t('productTypeIdPlaceholder'),
				trigger: ['change'],
			},
			'name': {
				type: 'string',
				required: true,
				message: t('namePlaceholder'),
				trigger: ['blur', 'change'],
			},
			'product_unit_id': {
				type: 'number',
				required: true,
				message: t('productUnitIdPlaceholder'),
				trigger: ['blur', 'change'],
			},
		}
	})

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

	const formData = ref({
		id: "",
		code:generatedCode("P"),
		name: "",
		product_type_id: 0,
		product_type_name: "",
		spec: "",
		inventory: "",
		min_warning: "",
		max_warning: "",
		remark: "",
		product_unit_id: "",
		product_unit_name: "",
		expiry_term :"",
		expiry_alert_term:"",
		image: "",
	})

	const imageFileList=ref<FileItem[]>([])
	/**
	 * 分类
	 */
	const pidList = ref<any[]>([]);
	const updateSex = (e : any) => {
		formData.value.product_type_id = e.id;
		formData.value.product_type_name = e.name;
	}
	// 获取分类
	const getCateList = () => {
		getProductTypeSelect().then((res : any) => {
			pidList.value = res.data;
		}).catch(err => {
			// 如果是4001，没有绑定企业账号，强制跳转绑定
			if (err.code == 4001) {
				redirect({ url: '/addon/erp/pages/member/bind' })
			}
		})
	}

	/**
	 * 单位
	 */
	const unitList = ref<any[]>([]);
	const updateSexUnit = (e : any) => {
		formData.value.product_unit_id = e.id;
		formData.value.product_unit_name = e.name;
	}
	// 获取单位
	const getUnitList = () => {
		getProductUnitSelect({}).then((res : any) => {
			unitList.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: 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 handSave = async() => {
		formRef.value.validate().then(() => {
			if (loading.value) return
			loading.value = true
			if(imageFileList.value.length > 0){
				const imgUrls=imageFileList.value.map((item:any)=>item.url)
				formData.value.image=imgUrls.join(',')
			}
			addProduct(formData.value).then((res : any) => {
				loading.value = false
				if (res.code == 1) {
					redirect({ url: '/addon/erp/pages/product/product/list' })
				}
			}).catch((err) => {
				// 如果是4001，没有绑定企业账号，强制跳转绑定
				if (err.code == 4001) {
					redirect({ url: '/addon/erp/pages/member/bind' })
				}
				loading.value = false
			})
		})
	}
</script>

<style lang="scss" scoped>
	.form-edit :deep(.u-form-item__body__left__content__label) {
		font-size: 28rpx !important;
	}

	.form-edit :deep(.u-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>