<template>
	<view class="body">
		<view class="content uni-column">
			<view class="uni-column uni-jcc top">
				<my-topbar :title="title" :showBack="true" @btnBackClick="btnBack"></my-topbar>
				<view class="top-content uni-row">
				</view>
			</view>

			<view class="main uni-column">
				<uni-forms ref="form" class="form" :modelValue="formData" :rules="checkRules">
					<uni-forms-item label="赛事名称" name="compName">
						<uni-easyinput maxlength="25" placeholder="请输入赛事名称" v-model="formData.compName" />
					</uni-forms-item>
					<uni-forms-item label="赛事起始时间" name="compBeginTime">
						<uni-datetime-picker v-model="formData.compBeginTime" type="datetime" placeholder="选择赛事起始时间" />
					</uni-forms-item>
					<uni-forms-item label="赛事截止时间" name="compEndTime">
						<uni-datetime-picker v-model="formData.compEndTime" type="datetime" placeholder="选择赛事截止时间" />
					</uni-forms-item>
					<uni-forms-item label="赛事简介" name="description">
						<uni-easyinput type="textarea" autoHeight maxlength="500" v-model="formData.description"
							placeholder="请输入赛事简介" />
					</uni-forms-item>
					<uni-forms-item label="活动规则" name="rules">
						<uni-easyinput type="textarea" autoHeight maxlength="500" v-model="formData.rules"
							placeholder="请输入活动规则" />
					</uni-forms-item>
					<uni-forms-item label="赛事LOGO" name="matchLogo">
						<uni-file-picker v-model="matchLogoObj" :auto-upload="false" limit="1" title="请选择赛事使用的LOGO图片"
							:sizeType="['original', 'compressed']" file-mediatype="image"
							file-extname="jpg,jpeg,png,gif,bmp,heic" @select="onLogoUploadSelect"
							@delete="onLogoUploadDelete"></uni-file-picker>
					</uni-forms-item>
					<uni-forms-item label="赛事场地" name="mapId">
						<e-select v-model="formData.mapId" :options="mapRs" :props="mapSelectionProps" clearable
							maxHeight="40vh" :placeholder="'请选择赛事场地（可输入关键字）'" @getText="getMapSelectText"
							@change="mapSelectChange"></e-select>
					</uni-forms-item>
					<uni-forms-item label="赛事方案" name="planId">
						<e-select v-model="formData.planId" :options="planRs" :props="planSelectionProps" clearable
							maxHeight="40vh" :placeholder="'请选择赛事方案'" @getText="getPlanSelectText"
							@change="planSelectChange"></e-select>
					</uni-forms-item>
					<uni-forms-item label="联系人姓名" name="contactName">
						<uni-easyinput maxlength="20" placeholder="请输入联系人姓名" v-model="formData.contactName" />
					</uni-forms-item>
					<uni-forms-item label="联系人电话" name="phone">
						<uni-easyinput maxlength="11" placeholder="请输入联系人电话" v-model="formData.phone" />
					</uni-forms-item>
				</uni-forms>

				<view class="uni-row uni-jcse" style="width: 90%;">
					<button class="button button-save" @click="saveClick">暂存</button>
					<button class="button button-submit" @click="submitClick">提交审核</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapGetters
	} from 'vuex';
	import tools from '/utils/tools.js';
	// import { tplStyleList, userLevel, pubState } from '/utils/define.js';
	import {
		apiCompInfoAdd,
		apiUploadFiles,
		apiSelectSsctQuery,
		apiSelectMapQuery,
		apiSelectPlanQuery,
		checkResCode
	} from '/utils/api.js';

	export default {
		data() {
			return {
				queryObj: {},
				queryString: "",
				saveKey: "actCreate",

				title: "自助开赛",
				mapSelectionProps: {
					text: 'Label',
					value: 'Value',
				},
				planSelectionProps: {
					text: 'Label',
					value: 'Value',
				},
				mapRs: [], // 地图（场地）信息集合
				planRs: [], // 方案信息集合

				matchLogoObj: {},
				formData: {
					matchLogo: "", // 赛事LOGO
					matchBanner: "", // 赛事BANNER
					compName: "", // 赛事名称
					description: "", // 赛事简介
					rules: "", // 活动规则
					contactName: "", // 联系人姓名
					phone: "", // 联系人电话
					regBeginTime: "", // 报名开始时间 (格式 2025-01-02 15:42:35)
					regBeginSecond: "", // 报名开始时间戳，单位 秒
					regEndTime: "", // 报名结束时间
					regEndSecond: "", // 报名结束时间戳，单位 秒
					compBeginTime: "", // 赛事开始时间
					compBeginSecond: "", // 赛事开始时间戳，单位 秒
					compEndTime: "", // 赛事结束时间
					compEndSecond: "", // 赛事结束时间戳，单位 秒
					mapId: null, // 场地ID
					planId: null // 方案ID
				},

				checkRules: {
					compName: {
						rules: [{
								required: true,
								errorMessage: '请输入赛事名称',
							},
							{
								minLength: 5,
								maxLength: 25,
								errorMessage: '赛事名称长度在 {minLength} 到 {maxLength} 个字符',
							}
						]
					},
					compBeginTime: {
						rules: [{
							required: true,
							errorMessage: '请选择赛事起始时间',
						}]
					},
					compEndTime: {
						rules: [{
								required: true,
								errorMessage: '请选择赛事截止时间',
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value <= data.compBeginSecond) {
										callback('截止时间必须大于起始时间');
										return false;
									} else {
										return true;
									}
								}
							}
						]
					},
					description: {
						rules: [{
								required: true,
								errorMessage: '请输入赛事简介',
							},
							{
								minLength: 20,
								maxLength: 500,
								errorMessage: '赛事简介长度在 {minLength} 到 {maxLength} 个字符',
							}
						]
					},
					rules: {
						rules: [{
								required: true,
								errorMessage: '请输入活动规则',
							},
							{
								minLength: 20,
								maxLength: 500,
								errorMessage: '活动规则长度在 {minLength} 到 {maxLength} 个字符',
							}
						]
					},
					// matchLogo: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请选择赛事LOGO',
					// 	}]
					// },
					mapId: {
						rules: [{
								required: true,
								errorMessage: '请选择赛事场地',
							},
							{
								minimum: 1,
								errorMessage: '请选择赛事场地',
							}
						]
					},
					planId: {
						rules: [{
								required: true,
								errorMessage: '请选择赛事方案',
							},
							{
								minimum: 1,
								errorMessage: '请选择赛事方案',
							}
						]
					},
					contactName: {
						rules: [{
								required: true,
								errorMessage: '请输入联系人姓名',
							},
							{
								minLength: 2,
								maxLength: 20,
								errorMessage: '联系人姓名长度在 {minLength} 到 {maxLength} 个字符',
							}
						]
					},
					phone: {
						rules: [{
								required: true,
								errorMessage: '请输入联系人电话',
							},
							{
								pattern: "^((1[3456789][0-9]{1})+\\d{8})$",
								errorMessage: '请输入合法的手机号',
							}
						]
					}
				}
			}
		},
		computed: {
			...mapState([
				'username', // 映射 this.username 为 store.state.username
				'token'
			]),
			...mapGetters([
				'metadata'
			]),
		},
		onLoad(query) {
			// console.log(query);
			this.queryObj = query;
			this.queryString = tools.objectToQueryString(this.queryObj);
			// console.log(queryString);
			// console.log("token", this.token);

			// uni.setStorageSync(this.saveKey, "");
			this.getSaveData();
			this.selectMapQuery();
		},
		mounted() {},
		methods: {
			getSaveData() {
				const saveData = uni.getStorageSync(this.saveKey);
				console.log("getSaveData", saveData);
				// if (saveData) {
				// 	this.formData = saveData;
				// }
				if (saveData.mapRs) {
					this.mapRs = saveData.mapRs;
				}
				if (saveData.planRs) {
					this.planRs = saveData.planRs;
				}
				if (saveData.matchLogoObj) {
					this.matchLogoObj = saveData.matchLogoObj;
				}
				if (saveData.formData) {
					this.formData = saveData.formData;
				}
				// console.log(this.formData);
			},
			// 自助新建赛事信息
			compInfoAdd() {
				this.formData.regBeginTime = this.formData.compBeginTime;
				this.formData.regEndTime = this.formData.compEndTime;
				
				this.formData.regBeginSecond = Date.parse(this.formData.regBeginTime) / 1000;
				this.formData.regEndSecond = Date.parse(this.formData.regEndTime) / 1000;
				this.formData.compBeginSecond = Date.parse(this.formData.compBeginTime) / 1000;
				this.formData.compEndSecond = Date.parse(this.formData.compEndTime) / 1000;

				console.log("[compInfoAdd] formData:", this.formData);
				console.log("[compInfoAdd] formData:", JSON.stringify(this.formData));

				uni.request({
					url: apiCompInfoAdd,
					header: this.metadata,
					method: "POST",
					data: {
						inJson: JSON.stringify(this.formData)
					},
					success: (res) => {
						console.log("compInfoAdd", res);
						if (checkResCode(res)) {
							// const data = res.data.data;
							uni.showToast({
								title: `提交成功`,
								icon: 'none',
								duration: 3000
							});

							uni.setStorageSync(this.saveKey, "");
							setTimeout(() => {
								this.btnBack();
								// this.$router.go(0);	// 刷新当前页面
							}, 1000);
						}
					},
					fail: (err) => {
						console.log("compInfoAdd err", err);
					},
				});
			},
			// 自助选择公共模板
			selectSsctQuery() {				
				uni.request({
					url: apiSelectSsctQuery,
					header: this.metadata,
					method: "POST",
					data: {},
					success: (res) => {
						console.log("selectSsctQuery", res);
						if (checkResCode(res)) {
							// const data = res.data.data;
						}
					},
					fail: (err) => {
						console.log("selectSsctQuery err", err);
					},
				});
			},
			// 自助选择地图
			selectMapQuery() {				
				uni.request({
					url: apiSelectMapQuery,
					header: this.metadata,
					method: "POST",
					data: {},
					success: (res) => {
						console.log("selectMapQuery", res);
						if (checkResCode(res)) {
							const data = res.data.data;
							this.mapRs = data;
						}
					},
					fail: (err) => {
						console.log("selectMapQuery err", err);
					},
				});
			},
			// 自助根据地图选择方案
			selectPlanQuery(mapId) {				
				uni.request({
					url: apiSelectPlanQuery,
					header: this.metadata,
					method: "POST",
					data: {
						mapId: mapId
					},
					success: (res) => {
						console.log("selectPlanQuery", res);
						if (checkResCode(res)) {
							const data = res.data.data;
							this.planRs = data;
						}
					},
					fail: (err) => {
						console.log("selectPlanQuery err", err);
					},
				});
			},
			btnBack() {
				const url = "/pages/actManage/index";
				tools.appAction(url, "uni.switchTab");
			},
			onLogoUploadSelect(e) {
				console.log('[onLogoUploadSelect] 选择文件：', e);
				// const imgUrl = e.tempFilePaths[0]; // 获取图片的本地路径
				const img = e.tempFiles[0]; // 获取图片信息
				// 上传图片
				if (img) {
					uni.uploadFile({
						url: apiUploadFiles, // 你的服务器上传接口地址
						filePath: img.path, // 选择的图片路径
						name: 'uploadFile', // 必填，后台用来解析的文件名
						header: {
							// "Content-Type": "multipart/form-data", // H5端不需要添加本句代码
							"token": this.token
						},
						formData: {
							// 'user': 'test'
						},
						success: (uploadFileRes) => {
							// console.log("[onLogoUploadSelect] uploadFileRes", uploadFileRes);
							// console.log("上传成功", JSON.parse(uploadFileRes.data));
							let data = JSON.parse(uploadFileRes.data).data;
							this.formData.matchLogo = data.url;
							this.matchLogoObj = {
								"name": img.name,
								"extname": img.extname,
								"url": data.url
							};
						},
						fail: (err) => {
							console.error("上传失败", err);
						}
					});
				}
			},
			onLogoUploadDelete() {
				this.formData.matchLogo = "";
			},
			saveClick() {
				console.log(this.formData);
				// const saveData = this.formData;
				const saveData = {
					mapRs: this.mapRs,
					planRs: this.planRs,
					matchLogoObj: this.matchLogoObj,
					formData: this.formData
				};
				uni.setStorageSync(this.saveKey, saveData);
				uni.showToast({
					title: `暂存成功`,
					icon: 'none',
					duration: 3000
				});
			},
			submitClick() {
				// console.log(this.formData);
				this.$refs.form.validate().then(res => {
					// console.log('表单数据信息：', res);
					this.compInfoAdd();
				}).catch(err => {
					console.log('表单错误信息：', err);
					uni.showToast({
						title: `错误: ${err[0].errorMessage}`,
						icon: 'none',
						duration: 3000
					});
				});
			},
			// 获取 赛事场地 输入框中值
			getMapSelectText(data) {
				// console.log("getMapSelectText:", data);
				// this.coiName = data;
			},
			// 获取 赛事方案 输入框中值
			getPlanSelectText(data) {
				// console.log("getPlanSelectText:", data);
				// this.coiName = data;
			},
			// 获取 赛事场地 选择选项值
			mapSelectChange(data) {
				// console.log("mapSelectChange:", data);
				if (data == "clear") {	// 用户点击清空图标
					this.planRs = [];
				}
				
				const mapId = data.Value;
				if (mapId > 0) {
					this.selectPlanQuery(mapId);
				}
			},
			// 获取 赛事方案 选择选项值
			planSelectChange(data) {
				// console.log("mapSelectChange:", data);
			},
		},
	}
</script>

<style scoped>
	.top {
		height: 36px;
		flex-shrink: 0;
		background: rgb(255, 195, 0, 0.26);
	}

	.main {}

	.form {
		width: 90%;
		margin-top: 20px;
	}

	.uni-forms-item {
		align-items: center;
		margin-bottom: 22px;
	}

	.input {
		width: 90%;
		height: 30px;
		padding: 0 8px;
		border: 1px solid;
		border-color: #c6c6c6;
		border-radius: 3px;
		font-size: 14px;
	}

	.input-placeholder {
		font-weight: 300;
		color: #bfbfbf;
		font-size: 14px;
	}

	.button {
		width: 36vw;
		margin-top: 5px;
		margin-bottom: 25px;
		border-radius: 6px;
		font-weight: 500;
		color: #333333;
		word-spacing: 15px;
	}

	.button-save {
		color: #ffffff;
		background-color: #5b8839;
	}

	.button-submit {
		color: #ffffff;
		background-color: #e39700;
	}
	
</style>