<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('name')" prop="name" required borderBottom>
						<u-input  fontSize="28rpx" v-model.trim="formData.name" border="none" clearable placeholderStyle="color: #888" :placeholder="t('namePlaceholder')"/>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('contact')" prop="contact" required borderBottom>
						<u-input fontSize="28rpx" v-model="formData.contact" :placeholder="t('contactPlaceholder')" border="none"></u-input>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('phone')" prop="phone" required borderBottom>
						<u-input fontSize="28rpx" v-model.trim="formData.phone" type="number" maxlength="11" border="none" clearable :placeholder="t('phonePlaceholder')" placeholderStyle="color: #888"/>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('telephone')" prop="telephone" borderBottom>
						<u-input fontSize="28rpx" v-model="formData.telephone" :placeholder="t('telephonePlaceholder')" border="none"></u-input>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('city')" prop="cityName" borderBottom>
						<view class="flex w-full items-center h-[52rpx]" @click="selectArea">
							<view v-if="!formData.cityName" class="text-[#888] text-[28rpx] flex-1">{{ t('cityPlaceholder') }}</view>
							<view v-else class="text-[28rpx] flex-1 leading-[1.4]">{{ formData.cityName }}</view>
						</view>
					</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" border="none" clearable maxlength="120" :placeholder="t('addressPlaceholder')" placeholderStyle="color: #888"/>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('description')" prop="description">
						<u-textarea fontSize="28rpx" v-model="formData.description" :placeholder="t('descriptionPlaceholder')" border="none"></u-textarea>
					</u-form-item>
				</view>
			</view>
			
		</u-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>
	    <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 { addCustomer } from '@/addon/erp/api/base';
	import { generatedCode } from '@/addon/erp/utils/common';
	import { redirect } from '@/utils/common';
	
	const formRef: any = ref(null)
	const loading = ref(false)
	
	const areaRef = ref()
	const isSelectAddress = ref(false)
	
	const rules = computed(() => {
	    return {
	        '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("CT"),
		name: '',
		contact: '',
		phone: '',
		telephone: '',
		city: '',
		cityName: '',
		address: '',
		description: ''
	})
	

	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 handSave = () => {
		formRef.value.validate().then(() => {
		    if (loading.value) return
		    loading.value = true
			
		    addCustomer(formData).then((res: any) => {
				loading.value = false
				if(res.code == 1){
					redirect({ url: '/addon/erp/pages/base/customer/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>