<template>
	<view class="teacher">
		<view class="one">
			<up-form :model="form" ref="uFormRef" :rules="rules" labelPosition="top">
				<up-form-item label="课程名称" labelWidth="80" prop="name" :required="true">
					<up-input v-model="form.name" placeholder="请输入课程名称" />
				</up-form-item>
				<up-form-item label="学科" prop="subject" :required="true">
					<picker @change="subjectChange" :range="subjectList" range-key='label'>
						<view class="picker">{{form.subject_name||'请选择学科'}}</view>
					</picker>
				</up-form-item>
				<up-form-item label="年级" prop="grade" :required="true">
					<picker @change="gradeChange" :range="gradeList" range-key='label'>
						<view class="picker">{{form.grade_name||'请选择年级'}}</view>
					</picker>
				</up-form-item>
				<up-form-item label="类型" prop="type" :required="true">
					<picker @change="typeChange" :range="typeList" range-key='label'>
						<view class="picker">{{form.type_name||'请选择年级'}}</view>
					</picker>
				</up-form-item>
				<up-form-item label="金额(元)" prop="money" labelWidth="80" :required="true">
					<up-input v-model="form.money" placeholder="请输入金额(元)" />
				</up-form-item>
				<up-form-item label="开始时间" labelWidth="80" prop="start_time" :required="true"
					@click="showStart = true; hideKeyboard()">
					<up-input v-model="form.start_time" disabled disabledColor="#ffffff"
						placeholder="请选择开始时间"></up-input>
					<up-icon slot="right" name="arrow-right"></up-icon>
				</up-form-item>
				<up-form-item label="结束时间" labelWidth="80" prop="end_time" @click="showEnd = true; hideKeyboard()"
					:required="true">
					<up-input v-model="form.end_time" disabled disabledColor="#ffffff" placeholder="请选择结束时间"></up-input>
					<up-icon slot="right" name="arrow-right"></up-icon>
				</up-form-item>
				<up-form-item label="简介" prop="brief">
					<up-textarea placeholder="请输入简介" v-model="form.brief" count></up-textarea>
				</up-form-item>
				<up-form-item label="是否公开" labelWidth="80" prop="is_show" :required="true">
					<up-radio-group v-model="form.is_show" placement="row">
						<up-radio :customStyle="{marginRight: '16px'}" v-for="(item, index) in showList" :key="index"
							:label="item.label" :name="item.value">
						</up-radio>
					</up-radio-group>
				</up-form-item>
			</up-form>
			<view class="bottom">
				<button class="button" type="default" size="mini" @click="submit">保存</button>
			</view>
			<up-datetime-picker :show="showStart" :value="form.start_time" mode="datetime" closeOnClickOverlay
				@confirm="StartConfirm" @cancel="StartClose" @close="StartClose"
				:minDate="Number(new Date())"></up-datetime-picker>
			<up-datetime-picker :show="showEnd" :value="form.end_time" mode="datetime" closeOnClickOverlay
				@confirm="EndConfirm" @cancel="EndClose" @close="EndClose"
				:minDate="Number(new Date())"></up-datetime-picker>
		</view>
	</view>
</template>

<script setup lang="ts">
	import moment from 'moment';
	import { inject, computed, ref } from 'vue';
	//该依赖已内置不需要单独安装
	import { onLoad, onReady } from "@dcloudio/uni-app";
	// 请求接口
	const $api = inject('$api');
	// user
	const user = computed(() => {
		return uni.getStorageSync('user');
	})
	const id = ref('');
	// 响应式表单数据  
	const form = ref({ name: '', subject: '', grade: '', type: '', money: '', start_time: '', end_time: '', is_show: '' });
	const rules = ref({
		name: [{ required: true, message: '请输入姓名', trigger: ['blur', 'change'] }],
		subject: [{ required: true, message: '请选择学科', trigger: ['blur', 'change'] }],
		grade: [{ required: true, message: '请选择年级', trigger: ['blur', 'change'] }],
		type: [{ required: true, message: '请选择类型', trigger: ['blur', 'change'] }],
		money: [{ required: true, message: '请输入金额', trigger: ['blur', 'change'] }],
		start_time: [{ required: true, message: '请选择开始时间', trigger: ['blur', 'change'] }],
		end_time: [
			{ required: true, message: '请选择结束时间', trigger: ['blur', 'change'] },
			{ validator: (rule, value, callback) => { return moment(form.value.start_time).isBefore(form.value.end_time) }, message: '开始时间必须大于结束时间！' }
		],
		is_show: [{ required: true, message: '请选择是否公开', trigger: ['blur', 'change'] }],
	});
	// 表单引用  
	const uFormRef = ref(null);
	// 字典表
	const subjectList = ref([])
	const gradeList = ref([])
	const showList = ref([])
	const typeList = ref([])
	const showStart = ref(false)
	const showEnd = ref(false)
	onLoad(async (options) => {
		id.value = options && options.id
		await searchOther();
		await search();
	});
	onReady(() => {
		uFormRef.value.setRules(rules.value)
	})
	// 其他查询信息
	const searchOther = async () => {
		let res;
		// 学科
		res = await $api(`dictData`, 'GET', { code: 'subject', is_use: '0' });
		if (res.errcode === 0) subjectList.value = res.data;
		// 年级
		res = await $api(`dictData`, 'GET', { code: 'grade', is_use: '0' });
		if (res.errcode === 0) gradeList.value = res.data;
		// 类型
		res = await $api(`dictData`, 'GET', { code: 'courseType', is_use: '0' });
		if (res.errcode === 0) typeList.value = res.data;
		// 是否公开
		res = await $api(`dictData`, 'GET', { code: 'show', is_use: '0' });
		if (res.errcode === 0) showList.value = res.data;
	};
	// 查询
	const search = async () => {
		if (id.value) {
			const res = await $api(`course/${id.value}`, 'GET', {});
			if (res.errcode === 0) {
				if (res.data.subject) {
					const data = subjectList.value.find(i => i.value === res.data.subject)
					if (data) res.data.subject_name = data.label
				}
				if (res.data.grade) {
					const data = gradeList.value.find(i => i.value === res.data.grade)
					if (data) res.data.grade_name = data.label
				}
				if (res.data.type) {
					const data = typeList.value.find(i => i.value === res.data.type)
					if (data) res.data.type_name = data.label
				}
				form.value = res.data
			} else {
				uni.showToast({
					title: res.errmsg || '',
					icon: 'error',
				});
			}
		}
	};
	// 类型选择
	const typeChange = (e) => {
		const data = typeList.value[e.detail.value]
		if (data) {
			form.value.type = data.value
			form.value.type_name = data.label
		}
	};
	// 学科选择
	const subjectChange = (e) => {
		const data = subjectList.value[e.detail.value]
		if (data) {
			form.value.subject = data.value
			form.value.subject_name = data.label
		}
	};
	// 年级选择
	const gradeChange = (e) => {
		const data = gradeList.value[e.detail.value]
		if (data) {
			form.value.grade = data.value
			form.value.grade_name = data.label
		}
	};
	const StartClose = async () => {
		showStart.value = false
		uFormRef.value.validateField('start_time')
	}
	const StartConfirm = async (e) => {
		showStart.value = false
		form.value.start_time = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
		uFormRef.value.validateField('start_time')
	}
	const EndClose = async () => {
		showEnd.value = false
		uFormRef.value.validateField('end_time')
	}
	const EndConfirm = async (e) => {
		showEnd.value = false
		form.value.end_time = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
		uFormRef.value.validateField('end_time')
	}
	// 提交方法
	const submit = async () => {
		uFormRef.value.validate().then(async valid => {
			if (valid) {
				const data = JSON.parse(JSON.stringify(form.value))
				data.teacher = user.value._id
				delete data.subject_name
				delete data.grade_name
				delete data.type_name
				let res;
				if (id.value) res = await $api(`course/${id.value}`, 'POST', data)
				else res = await $api(`course`, 'POST', data);
				if (res.errcode == '0') {
					uni.showToast({
						title: '维护信息成功',
						icon: 'none'
					})
					uni.navigateBack({
						delta: 1
					})
				} else {
					uni.showToast({
						title: res.errmsg,
						icon: 'none'
					})
				}
			} else {
				uni.$u.toast('校验失败')
			}
		}).catch(() => {
			// 处理验证错误  
			uni.$u.toast('校验失败')
		});
	}
	const hideKeyboard = () => {
		uni.hideKeyboard()
	}
</script>
<style lang="scss" scoped>
	.teacher {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: var(--footColor);

		.one {
			margin: 2vw;
			padding: 2vw;
			border-radius: 5px;
			background-color: var(--mainColor);

			.picker {
				padding: 9px;
				border: 0.5px solid #dadbde;
				color: #303133;
				font-size: 15px;
				text-align: left;
				border-radius: 4px;
			}

			.bottom {
				text-align: center;

				.button {
					margin: 2vw 0 0 0;
					color: var(--mainColor);
					background-color: var(--3c9Color);
					font-size: var(--font14Size);
					border-radius: 2vw;
				}
			}

			:deep(.u-form-item__body__left__content) {
				padding: 5rpx 10rpx !important;
			}

			:deep(.u-form-item__body) {
				padding: 5rpx 0 !important;
			}
		}
	}
</style>