<template>
	<view class="bg-[var(--page-bg-color)] min-h-[100vh] overflow-hidden form-edit" :style="themeColor()">
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<u-form labelPosition="left" :model="formData" errorType='toast' :rules="rules" ref="formRef"
			labelWidth="160rpx">
			<view class="sidebar-margin card-template mt-[var(--top-m)] py-[20rpx]">
			<!-- 	<view>
					<u-form-item :label="t('code')" prop="code" borderBottom required>
						<u-input fontSize="28rpx" v-model="formData.code" :placeholder="t('codePlaceholderNew')" disabled ></u-input>
					</u-form-item>
				</view> -->
				<view class="mt-[16rpx]">
					<u-form-item :label="t('name')" prop="name" borderBottom required>
						<u-input fontSize="28rpx" v-model="formData.name" :placeholder="t('namePlaceholder')" ></u-input>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('contact')" prop="contact" borderBottom required>
						<u-input fontSize="28rpx" v-model="formData.contact" :placeholder="t('contactPlaceholder')"
							></u-input>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('phone')" prop="phone" borderBottom required>
						<u-input fontSize="28rpx" v-model="formData.phone" type="number" maxlength="11" :placeholder="t('phonePlaceholder')" ></u-input>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('productType')" prop="product_type" borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="productTypes" multiple dataKey="name" dataValue="id" :localdata="productTypeData" :placeholder="t('productTypePlaceholder')"
										@change="productTypeChange"></zxz-uni-data-select>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.product_type_id" :options="productTypeData" dataKey="name" dataValue="id"  :placeholder="t('productTypePlaceholder')"  :height="38"/>
						<!-- #endif -->				
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('merchantMobile')" prop="mobile" borderBottom>
						<u-input fontSize="28rpx" v-model="formData.mobile" type="number" maxlength="11" :placeholder="t('merchantMobilePlaceholder')" ></u-input>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('term')" prop="term" borderBottom>
						<u-input fontSize="28rpx" v-model="formData.term" type="number" :placeholder="t('termPlaceholder')" ></u-input>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('address')" prop="address" borderBottom>
						<u-input fontSize="28rpx" v-model="formData.address" :placeholder="t('addressPlaceholder')"
							></u-input>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('description')" prop="description" borderBottom>
						<u-textarea fontSize="28rpx" v-model="formData.description" :placeholder="t('descriptionPlaceholder')"
							></u-textarea>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('credentialImage')" prop="credential_image" borderBottom>
							<up-upload
								:fileList="credentialImageFileList"
								@afterRead="afterRead"
								@delete="imageDelete"
								multiple
								:maxCount="5"
							></up-upload>
					</u-form-item>
				</view>
			</view>

		</u-form>
		<view v-if="hasPermission('erp_base_supplier_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>
		<!-- <area-select ref="areaRef" @complete="areaSelectComplete" :area-id="0" /> -->
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, computed } from 'vue'
	import { t } from '@/locale'
	import { onLoad } from '@dcloudio/uni-app';
	import { addSupplier } from '@/addon/erp/api/base';
	import { generatedCode } from '@/addon/erp/utils/common';
	import { getProductTypeSelect} from '@/addon/erp/api/product';
	import {uploadImage } from '@/app/api/system'
	import { redirect } from '@/utils/common';
	import useMemberStore from '@/stores/member'
	import { img } from '@/utils/common'
	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 productTypeData=ref([])

	const rules = computed(() => {
		return {
			// 'code': {
			// 	type: 'string',
			// 	required: true,
			// 	message: t('codePlaceholdernew'),
			// 	trigger: ['blur', 'change'],
			// },
			'name': {
				type: 'string',
				required: true,
				message: t('namePlaceholder'),
				trigger: ['blur', 'change'],
			},
			'contact': {
				type: 'string',
				required: true,
				message: t('contactPlaceholder'),
				trigger: ['blur', 'change'],
			},
			'phone': [
				{
					type: 'string',
					required: true,
					message: t('phonePlaceholder'),
					trigger: ['blur', 'change'],
				},
				{
					validator(rule : any, value : any, callback : any) {
						let mobile = /^1[3-9]\d{9}$/;
						if (!mobile.test(value)) {
							callback(new Error(t('mobileError')))
						} else {
							callback()
						}
					}
				}
			]
		}
	})

	const formData = reactive({
		code: generatedCode("S"),
		name: '',
		contact: '',
		phone: '',
		term: '',
		city: '',
		cityName: '',
		address: '',
		description: '',
		mobile:'',
		product_type_id:'',
		credential_image:'',
	})
	const productTypes=ref([])
	const credentialImageFileList=ref<FileItem[]>([])
	
	// 页面加载
	onLoad((option : any) => {
		getProductTypeDataList();
	})
	
	
	// const selectArea = () => {
	// 	isSelectAddress.value = true
	// 	areaRef.value.open()
	// }

	// const areaSelectComplete = (event : any) => {
	// 	let cityArr = [] as any[];
	// 	cityArr = [event.province.id || 0, event.city.id || 0, event.district.id || 0];

	// 	formData.city = cityArr.join(',');
	// 	formData.cityName = `${event.province.name || ''}${event.city.name || ''}${event.district.name || ''}`
	// 	isSelectAddress.value = false;
	// }
	
	const productTypeChange=(e: any) =>{
		console.log('e:', e,productTypes.value);
	}
	
	const getProductTypeDataList = () => {
		getProductTypeSelect().then((res : any) => {
			productTypeData.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 = credentialImageFileList.value.length;
	  lists = lists.filter((item:FileItem) => item.url);
	  lists.map((item: any) => {
	    credentialImageFileList.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 = credentialImageFileList.value[fileListLen];
	    credentialImageFileList.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 = credentialImageFileList.value;
			currentFileList.splice(imageIndex, 1);
			credentialImageFileList.value = [...credentialImageFileList.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(credentialImageFileList.value.length > 0){
				const imgUrls=credentialImageFileList.value.map((item:any)=>item.url)
				formData.credential_image=imgUrls.join(',')
			}
			// #ifdef H5
			if(productTypes.value.length > 0){
				formData.product_type_id=productTypes.value.join(',')
			}
			// #endif
			addSupplier(formData).then((res : any) => {
				if (res.code == 1) {
					redirect({ url: '/addon/erp/pages/base/supplier/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>