<template>
	<view class="w-user-angent">
		<uni-forms ref="wflowForm" :rules="rules" :modelValue="userAgent" label-position="top" label-width="200">
			<uni-forms-item name="timeRange" :required="true" label="代理时间段">
				<uni-datetime-picker v-model="userAgent.timeRange" type="datetimerange" rangeSeparator="至" />
			</uni-forms-item>
			<uni-forms-item name="user" :required="true" label="代理人">
				<user-picker class="w-user" v-model="userAgent.user" :formProps="{multiple: false, placeholder: '请选择代理人'}"
					position="right" />
			</uni-forms-item>
		</uni-forms>
		<button type="warn" plain size="mini" @click="cancelAgent" v-if="showCancel">
			<uni-icons type="refreshempty" color="#E64340" size="13"></uni-icons>
			取消代理人
		</button>
		<button type="primary" size="mini" class="w-button" @click="doSubmit">提交</button>
	</view>
</template>

<script setup>
	import UserPicker from '@/components/form/UserPicker.vue'
	import { getUserAgent, setUserAgent, cancelUserAgent } from '@/api/org.js'
	import { computed, onBeforeMount, ref } from "vue";

	const userAgent = ref({
		timeRange: [],
		effective: false,
		user: []
	})
	
	const showCancel = ref(false)
	
	const wflowForm = ref()

	const userTemp = computed({
		get() {
			return userAgent.value.user ? [userAgent.value.user] : []
		},
		set(val) {
			userAgent.value.user = val[0]
		}
	})
	
	const rules = {
		timeRange: {
			rules: [{
				errorMessage:"请选择代理时间段",
				required:true
			}]
		},
		user: {
			rules: [{
				errorMessage:"请选择代理人",
				required:true
			}]
		}
	}

	onBeforeMount(() => {
		getUserAgent().then(rsp => {
			if (rsp.data) {
				userAgent.value = {
					...rsp.data,
					user: rsp.data.user ? [rsp.data.user] : []
				}
				showCancel.value = true
			}
		})
	})
	
	function cancelAgent(){
		uni.showModal({
			title: '提示',
			content: '您是否要取消该代理人设置',
			success: function(res) {
				if (res.confirm) {
					cancelUserAgent().then(res => {
						uni.showToast({
							icon: 'none',
							title: '取消成功'
						})
						uni.navigateBack()
					})
				}
			}
		});
	}
	
	function doSubmit(){
		wflowForm.value.validate().then(res => {
			setUserAgent({
				timeRange: userAgent.value.timeRange, 
				user: userAgent.value.user[0]
			}).then(res => {
				uni.showToast({
					icon: 'none',
					title: '设置代理人成功'
				})
				uni.navigateBack()
			}).catch(err => {
				uni.showToast({
					icon: 'none',
					title: '设置失败：' + err.msg
				})
			})
		}).catch(err => {
			uni.showToast({
				icon: 'none',
				title: '请完成设置'
			})
		})
	}
</script>

<style lang="less" scoped>
	page {
		background-color: white !important;
	}

	.w-user-angent {
		padding: 32rpx 16rpx;

		.w-button {
			width: 100%;
		}
		
		button {
			margin-bottom: 32rpx;
		}
	}
</style>