<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('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]">
					<up-form-item :label="'仓库'" prop="warehouse_id" required borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.warehouse_id" :localdata="warehouseList" dataKey="name"
							dataValue="id" clear placeholder="请选择仓库" @change="warehouseIdChange" />
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.warehouse_id" :options="warehouseList" dataKey="name"
							dataValue="id" clearable placeholder="请选择仓库" :height="38" @change="warehouseIdChange" />
						<!-- #endif -->
					</up-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')"></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" 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')"></u-input>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<up-form-item :label="'食堂审领人'" prop="salesman_id" borderBottom>
						<!-- #ifdef H5 -->
						<zxz-uni-data-select v-model="formData.salesman_id" :localdata="siteUser" dataKey="username"
							dataValue="uid" clear placeholder="请选择食堂审领人" @change="salesmanIdChange" />
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<wht-select v-model="formData.salesman_id" :options="siteUser" dataKey="username"
							dataValue="uid" clearable placeholder="请选择食堂审领人" :height="38" @change="salesmanIdChange" />
						<!-- #endif -->
					</up-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="t('address')" prop="address" borderBottom>
						<u-input fontSize="28rpx" v-model="formData.address" 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')"></u-textarea>
					</u-form-item>
				</view>
			</view>

		</u-form>
		<view class="w-full footer" v-if="hasPermission('erp_base_customer_add')">
			<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 { onLoad, onReady, onShow } from '@dcloudio/uni-app';
	import { t } from '@/locale'
	import { addCustomer, getusersList, getWarehouseSelect } from '@/addon/erp/api/base';
	import { generatedCode } from '@/addon/erp/utils/common';
	import { redirect } from '@/utils/common';
	import useMemberStore from '@/stores/member'
	import usePermission from '@/utils/usePermission'
	const { hasPermission } = usePermission()
	interface Warehouse {
		id : number;
		name : string;
	}
	const memberStore = useMemberStore()

	const formRef : any = ref(null)
	const loading = ref(false)

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

	const warehouseList = ref<Warehouse[]>([]);

	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'],
			},
			'warehouse_id': {
				type: 'number',
				required: true,
				message: '请选择仓库',
				trigger: ['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 = new RegExp('^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: '',
		salesman_id: '',
		warehouse_id: '',
		address: '',
		description: ''
	})

	onLoad((option : any) => {
		getAllUserList()
		getWarehouseSelectList()
	})
	const getWarehouseSelectList = () => {
		getWarehouseSelect().then(res => {
			warehouseList.value = res.data || []
		})
	}
	const warehouseIdChange = (e : any) => {
		formData.warehouse_id = e?.id || ''
		if (formRef.value) {
			formRef.value.validateField('warehouse_id');
		}
	}
	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 siteUser = ref<any[]>([]);
	const salesmanIdChange = (e : any) => {
		formData.salesman_id = e?.uid || ''
		if (formRef.value) {
			formRef.value.validateField('salesman_id');
		}
	}
	// 获取食堂审领人
	const getAllUserList = () => {
		getusersList({ page: 1, limit: 120 }).then((res : any) => {
			siteUser.value = res.data.data || [];
		}).catch(err => {
			// 如果是4001，没有绑定企业账号，强制跳转绑定
			if (err.code == 4001) {
				redirect({ url: '/addon/erp/pages/member/bind' })
			}
		})
	}
	// 保存
	const handSave = async () => {
		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>