<template>
	<view class="page">
		<up-form ref="formRef" :model="form" :rules="rules" labelPosition="left" labelWidth="150rpx">
			<view class="info">
				<view class="info-header">地址信息</view>
				<view class="info-content">
					<up-form-item label="接单地址" prop="area">
						<view plain class="flex-rowr" @click="selectAddr">
							<text v-if="form.area">{{ form.area }}</text>
							<text v-else class="placeholder">请定位选择小区或商城等</text>
							<up-icon style="margin-left: 22rpx;" name="arrow-down" color="#7F7F7F"
								size="21rpx"></up-icon>
						</view>
					</up-form-item>
					<up-form-item label="接单地址" prop="address" labelPosition="top">
						<view class="textarea">
							<textarea v-model="form.address" placeholder="如街道、门牌号、小区、乡镇、村等" :row="2"></textarea>
						</view>
					</up-form-item>
				</view>
			</view>

			<view class="info">
				<view class="info-header">接单信息</view>
				<view class="info-content">
					<up-form-item label="接单状态" prop="status">
						<view class="flex-rowr">
							<switch :checked="!!form.status" @change="onSwitch" color="#FFBF60"
								style="transform: scale(0.6);" />
							<text>{{ !!form.status ? '开启' : '关闭' }}</text>
						</view>
					</up-form-item>
					<up-form-item label="接单范围" prop="rangeNo">
						<up-input v-model="form.rangeNo" type="number" placeholder="请输入内容" inputAlign="right" border="none">
							<template #suffix>
								<text>Km</text>
							</template>
						</up-input>
					</up-form-item>
					<up-form-item @click="toNoOrderDate" 
					v-if="eidtItem"
					label="不接单日期(选填)" prop="disabledDate" labelWidth="300rpx">
						<view class="" style="display: flex;width: 380rpx;">
							<view class="text-ellipsis"
							style="margin-left: auto;"
							v-if="eidtItem && eidtItem.appletOutDate && eidtItem.appletOutDate.length">
								{{ getDisabledDateDesc(eidtItem.appletOutDate) }}
							</view>
							
							<view class="text-ellipsis"
							style="margin-left: auto;" v-else>
								暂无不可接单日期
							</view>
							>
						</view>
					</up-form-item>
				</view>
			</view>

		</up-form>

		<view style="margin-top: 40rpx;">
			<up-parse class="size-28" :content="configList.adress_statement.paramValueArea" containerStyle="{
          color: '#707070',
          fontSize: '22rpx',
          lineHeight: '35rpx',
        }"></up-parse>
		</view>

		<view class="footer-btn">
			<view class="btn" @click="onSave">
				{{ eidtItem ? '修改地址' : '新增地址'}}
			</view>
		</view>
	</view>
    <!-- 客服组件 -->
    <CustomerService />
</template>

<script setup>
	import {
		ref,
		getCurrentInstance,
		computed,
	} from 'vue'
	import dayjs from 'dayjs'
	import {
		store
	} from '@/store'
	import {
		insertAddress,
		udpateAddress,
		addressDetail,
	} from "@/api/address/address.js"
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'

	const instance = getCurrentInstance();
	const configList = store.state.system.configList

	const formRef = ref()
	const form = ref({
		area: null,
		latitude: null,
		longitude: null,
		address: null,
		status: true,
		rangeNo: null,
		disabledDate: [],
	})
	
	const userInfo = computed(() => {
		return store.getters.userInfo;
	})
	
	const rules = ref({})
	const eidtItem = ref(null);
	const addressId = ref(0)

	onLoad((options) => {
		addressId.value = options.addressId
		
		// eidtItem.value = options?.item ? JSON.parse(options.item) : null;
		// form.value = {
		// 	id: eidtItem?.value?.id || null,
		// 	area: eidtItem?.value?.area || null,
		// 	address: eidtItem?.value?.address || null,
		// 	status: eidtItem?.value?.status == 'true' || null,
		// 	latitude: eidtItem?.value?.latitude || null,
		// 	longitude: eidtItem?.value?.longitude || null
		// }
		getDetail()
	});

	const setAddress = (res) => {
		form.value.latitude = res.latitude
		form.value.longitude = res.longitude

		if (!res.address && res.name) { //用户直接选择城市的逻辑
			return form.value.area = res.name
		}
		if (res.address || res.name) {
			return form.value.area = res.address + res.name
		}
		form.value.area = '' //用户啥都没选就点击勾选
	}

	const selectAddr = () => {
		uni.chooseLocation({
			success: function(res) {
				setAddress(res)
			},
			fail(e) {
				console.log("获取位置信息失败!", e)
			}
		})
	}

	const onSwitch = (e) => {
		form.value.status = e.detail.value
	}

	const onSave = async () => {
		// 验证接单范围是否在3-15公里之间
		if (isNaN(form.value.rangeNo - 1) || form.value.rangeNo < 3 || form.value.rangeNo > 15) {
			uni.showToast({
				title: '接单范围必须是3-15公里之间的数字',
				icon: 'none'
			})
			return
		}

        //必须选择地区
        if (!form.value.area) {
            uni.showToast({
                title: '请选择地区',
                icon: 'none'
            })
            return
        }

		let code = null;
		if (eidtItem?.value?.id) {
			let result = await udpateAddress({
				...form.value,
				userId : userInfo.value.userId,
			})
			code = result.code
		} else {
			// 新增地址
			let result = await insertAddress({
				...form.value,
				userId : userInfo.value.userId,
			})
			code = result.code
		}
		if (code == 200) {
			uni.navigateBack()
		}
	}
	
	function getDetail(){
		
		if(!addressId.value){
			return
		}
		
		addressDetail(addressId.value).
		then(res => {
			console.log(res.data);
			eidtItem.value = res.data
			form.value = {
				id: eidtItem?.value?.id || null,
				area: eidtItem?.value?.area || null,
				address: eidtItem?.value?.address || null,
				status: eidtItem?.value?.status == 'true' || null,
				latitude: form.value.latitude || eidtItem?.value?.latitude || null,
				longitude: form.value.latitude || eidtItem?.value?.longitude || null,
				rangeNo: form.value.rangeNo || eidtItem?.value?.rangeNo || null
			}
		})
	}
	
	const getDisabledDateDesc = (dateArr) => {
		if (!dateArr?.length) {
			return '暂无不可接单日期'
		}
	
		return dateArr.map(date => dayjs(date.date).format('MM-DD')).join('、')
	}

	const toNoOrderDate = () => {
		if (eidtItem?.value?.id) {
			uni.navigateTo({
				url: `/otherPages/myOrdersManage/date/detail?addressId=${eidtItem.value.id}`
			});
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		padding: 35rpx 37rpx 144rpx 37rpx;
		min-height: calc(100vh - 200rpx);
		background-color: #fff;
	}

	.info {
		color: #707070;
		font-size: 30rpx;
		line-height: 40rpx;

		&-header {
			color: #000000;
		}

		.placeholder {
			color: #707070;
		}

		.textarea {
			margin-top: 16rpx;
			background-color: #F3F3F3;
			padding: 26rpx 8rpx;
			border-radius: 15rpx;
			height: 200rpx;
			overflow: scroll;
			textarea{
				height: 200rpx;
			}
		}

		:deep(.u-form-item__body__left__content__label) {
			color: #707070;
		}
	}
	.text-ellipsis {
		text-align: right;
		overflow: hidden; //超出的文本隐藏
		text-overflow: ellipsis; //溢出用省略号显示
		white-space: nowrap; //溢出不换行
		width: 330rpx;
	}
</style>