<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" :disabled="pubState > 1 ? true : false" />
					</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="请输入赛事简介" :disabled="pubState > 1 ? true : false" />
					</uni-forms-item>
					<uni-forms-item label="活动规则" name="rules">
						<uni-easyinput type="textarea" autoHeight maxlength="500" v-model="formData.rules"
							placeholder="请输入活动规则" :disabled="pubState > 1 ? true : false" />
					</uni-forms-item>
					<uni-forms-item label="赛事LOGO" name="matchLogo">
						<uni-file-picker v-model="matchLogoObj" :auto-upload="false" limit="1" :title="pubState > 1 ? '' : '请选择赛事使用的LOGO图片'"
							:sizeType="['original', 'compressed']" file-mediatype="image"
							file-extname="jpg,jpeg,png,gif,bmp,heic" @select="onLogoUploadSelect"
							@delete="onLogoUploadDelete" :readonly="pubState > 1 ? true : false"></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" :disabled="pubState > 1 ? true : false"></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" :disabled="pubState > 1 ? true : false"></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" @click="btnBack">返回</button>
					<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 {
		apiCompInfoDetail,
		apiCompInfoEdit,
		apiUploadFiles,
		apiSelectSsctQuery,
		apiSelectMapQuery,
		apiSelectPlanQuery,
		checkResCode
	} from '/utils/api.js';

	export default {
		data() {
			return {
				queryObj: {},
				queryString: "",
				from: "",
				compId: 0, // 赛事ID
				pubState: 0, //发布状态  0:审核中 1:内测 2:已发布

				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);
			
			this.from = query["from"] ?? "";
			this.compId = query["compId"] ?? 0;

			this.compInfoDetail();
			this.selectMapQuery();
		},
		mounted() {},
		methods: {
			// 自助赛事详情查询
			compInfoDetail() {
				uni.request({
					url: apiCompInfoDetail,
					header: this.metadata,
					method: "POST",
					data: {
						compId: this.compId
					},
					success: (res) => {
						console.log("[compInfoDetail] res", res);
						if (checkResCode(res)) {
							this.pubState = res.data.data.otherInfo.pubState;
							const config = res.data.data.config;
							// console.log("[compInfoDetail] config", config);
							
							this.formData.matchLogo = config.tplInfo.matchLogo;
							this.formData.matchBanner = config.tplInfo.matchBanner;
							this.formData.compName = config.matchInfo.compName;
							this.formData.description = config.matchInfo.description;
							this.formData.rules = config.matchInfo.rules;
							this.formData.contactName = config.matchInfo.contactName;
							this.formData.phone = config.matchInfo.phone;
							this.formData.regBeginTime = tools.timestampToTime(config.matchInfo.regBeginSecond * 1000);
							this.formData.regBeginSecond = config.matchInfo.regBeginSecond;
							this.formData.regEndTime = tools.timestampToTime(config.matchInfo.regEndSecond * 1000);
							this.formData.regEndSecond = config.matchInfo.regEndSecond;
							this.formData.compBeginTime = tools.timestampToTime(config.matchInfo.compBeginSecond * 1000);
							this.formData.compBeginSecond = config.matchInfo.compBeginSecond;
							this.formData.compEndTime = tools.timestampToTime(config.matchInfo.regEndSecond * 1000);
							this.formData.compEndSecond = config.matchInfo.compEndSecond;
							this.formData.mapId = config.mapInfo[0].mapId;
							this.formData.planId = config.mapInfo[0].planId;
							
							this.matchLogoObj = {
								// "name": "",
								// "extname": "",
								"url": config.tplInfo.matchLogo
							};
							
							this.selectPlanQuery(this.formData.mapId);
						}
					},
					fail: (err) => {
						console.log("[compInfoDetail] err", err);
					},
				});
			},
			// 自助修改赛事信息
			compInfoEdit() {
				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("[compInfoEdit] formData:", this.formData);
				console.log("[compInfoEdit] formData:", JSON.stringify(this.formData));

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

							setTimeout(() => {
								this.btnBack();
								// this.$router.go(0);	// 刷新当前页面
							}, 200);
						}
					},
					fail: (err) => {
						console.log("compInfoEdit 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() {
				if (this.from == "index") {
					const url = "/pages/actManage/index";
					tools.appAction(url, "uni.switchTab");
				} else if (this.from == "actDetail") {
					const url = "/pages/actManage/actDetail?compId=" + this.compId;
					tools.appAction(url, "uni.navigateTo");
				} else {
					window.history.back();
				}
			},
			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);
				let that = this;
				this.$refs.form.validate().then(res => {
					// console.log('表单数据信息：', res);
					uni.showModal({
						title: '提示',
						content: `修改后需要重新进行审核\r\n您确定要继续吗？`,
						confirmText: '确定', //确定文本的文字
						cancelText: '取消', //确定文本的文字
						showCancel: true, //没有取消按钮的弹框
						success: function(res) {
							if (res.confirm) {
								that.compInfoEdit();
							} else if (res.cancel) {
							}
						}
					});
				}).catch(err => {
					console.log('表单错误信息：', err);
					uni.showToast({
						title: `错误: ${err[0].errorMessage}`,
						icon: 'none',
						duration: 3000
					});
				});
			},
			submitClick() {
			},
			// 获取 赛事场地 输入框中值
			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: #55aa00;
	}

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