<template>
	<div class="system-systemParameter-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd100">
			<el-divider content-position="center"><h4 class="table-title">系统参数设置</h4></el-divider>
			<el-form :model="ruleForm" label-width="200px" ref="ruleFormRef" v-loading="loading" class="form">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-for="items in data" :key="items.id">
						<!-- <el-divider content-position="left">{{ items.groupName }}</el-divider> -->
						<div v-for="item in items.systemSettings" :key="item.id">
							<el-form-item :label="item.settingName">
								<!-- 单选框 -->
								<template v-if="item.valueType === 0">
									<el-radio-group v-model="item.settingValue" class="ml-4" @change="changeVal($event, item.id)">
										<el-radio :label="item1.value" v-for="item1 in item.presetValue" :key="item1.value">{{ item1.key }}</el-radio>
									</el-radio-group>
								</template>
								<!-- 多选框 -->
								<template v-else-if="item.valueType === 1">
									<el-checkbox-group v-model="item.settingValue" @change="changeVal($event, item.id)">
										<el-checkbox v-for="item1 in item.presetValue" :key="item1.value" :label="item1.value">{{ item1.key }}</el-checkbox>
									</el-checkbox-group>
								</template>
								<!-- 文本 -->
								<template v-else-if="item.valueType === 2">
									<el-input
										v-model="item.settingValue"
										:placeholder="'请输入' + item.settingName"
										class="maxwidth400"
										@input="changeVal($event, item.id)"
									/>
								</template>
								<!-- 数字 -->
								<template v-else-if="item.valueType === 3">
									<el-input-number v-model="item.settingValue" :placeholder="'请输入' + item.settingName" @input="changeVal($event, item.id)" />
								</template>
								<!-- 下拉框 -->
								<template v-else-if="item.valueType === 4">
									<el-select v-model="item.settingValue" :placeholder="'请选择' + item.settingName" @change="changeVal($event, item.id)">
										<el-option v-for="item1 in item.presetValue" :key="item1.value" :label="item1.key" :value="item1.value" />
									</el-select>
								</template>
								<!-- 开关 -->
								<template v-else-if="item.valueType === 5">
									<el-switch v-model="item.settingValue" @change="changeVal($event, item.id)" />
								</template>
								<!-- 时间 -->
								<template v-else-if="item.valueType === 6">
									<el-time-select
										v-model="item.settingValue"
										start="00:00"
										step="00:30"
										end="23:30"
										:placeholder="'请选择' + item.settingName"
										@change="changeVal($event, item.id)"
									/>
								</template>
								<!-- 日期 -->
								<template v-else-if="item.valueType === 7">
									<el-date-picker
										v-model="item.settingValue"
										value-format="YYYY-MM-DD[T]HH:mm:ss.sss[Z]"
										type="date"
										:placeholder="'请选择' + item.settingName"
										@change="changeVal($event, item.id)"
									/>
								</template>
								<!-- 日期区间 -->
								<template v-else-if="item.valueType === 8">
									<div>
										<el-date-picker
											v-model="item.settingValue"
											value-format="YYYY-MM-DD[T]HH:mm:ss.sss[Z]"
											type="daterange"
											:placeholder="'请选择' + item.settingName"
											@change="changeVal($event, item.id)"
											range-separator="至"
											start-placeholder="开始日期"
											end-placeholder="结束日期"
										/>
									</div>
								</template>
								<!-- 时间区间 -->
								<template v-else-if="item.valueType === 9">
									<el-time-select
										v-model="item.settingValue[0]"
										:max-time="item.settingValue[1]"
										placeholder="开始时间"
										start="00:00"
										step="00:30"
										end="23:30"
										@change="changeVal($event, item.id, 'startTime')"
									/>
									<el-time-select
										v-model="item.settingValue[1]"
										:min-time="item.settingValue[0]"
										placeholder="结束时间"
										start="00:00"
										step="00:30"
										end="23:30"
										@change="changeVal($event, item.id, 'endTime')"
									/>
								</template>
								<!-- 单个图片上传 -->
								<template v-else-if="item.valueType === 10">
									<el-upload
										class="avatar-uploader"
										accept=".jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PBG, .GIF, .BMP"
										action=""
										:show-file-list="false"
										:on-success="handleAvatarSuccess"
										:http-request="(file:any) => uploadImg(file, item.id)"
										:before-upload="beforeAvatarUpload"
									>
										<img v-if="imageUrl" :src="imageUrl" class="avatar" />
										<SvgIcon v-else class="avatar-uploader-icon" name="ele-Plus" size="32px" />
									</el-upload>
								</template>
								<!-- 多个图片上传 -->
								<template v-else-if="item.valueType === 11">
									<el-upload
										v-model:file-list="fileList"
										accept=".jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PBG, .GIF, .BMP"
										action=""
										list-type="picture-card"
										ref="uploadListRef"
										:autoUpload="false"
										:on-change="(file:any, fileList:any) => uploadImgList(file, fileList, item.id)"
									>
										<SvgIcon name="ele-Plus" size="32px" />
										<template #file="file">
											<div style="text-align: center" class="w100 h100">
												<div class="images w100 h100" v-viewer>
													<img class="w100 h100" :src="file.file.url" />
												</div>
												<span class="el-upload-list__item-actions">
													<span title="预览图片" class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
														<SvgIcon name="ele-ZoomIn" size="18px" />
													</span>
													<span title="删除图片" class="el-upload-list__item-delete" @click="handleRemove(file)">
														<SvgIcon name="ele-Delete" size="18px" />
													</span>
												</span>
											</div>
										</template>
									</el-upload>
								</template>
							</el-form-item>
						</div>
					</el-col>
				</el-row>
				<el-form-item>
					<el-button type="primary" @click="submitForm" :loading="loading" v-auth="'100301'">保 存 </el-button>
					<el-button @click="resetForm" :loading="loading" v-auth="'100301'">重 置</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script lang="ts" setup name="systemParameter">
import { reactive, ref, toRefs, onMounted } from 'vue';
import { getsyssettings, modifysettings } from '/@/api/system/parameter';
import { ElMessage } from 'element-plus';
import type { UploadProps, UploadUserFile } from 'element-plus';
import { api as viewerApi } from 'v-viewer';

// 定义接口来定义对象的类型
interface SystemState {
	ruleForm: object;
	data: Array<any>;
	formateData: Array<any>;
	loading: boolean;
}

// 定义变量内容
const timeRageRef = ref<any>(['', '']);
const uploadListRef = ref();
const state = reactive<SystemState>({
	ruleForm: {},
	data: [],
	formateData: [],
	loading: false,
});
const { ruleForm, data, loading } = toRefs(state);
//获取参数列表
const getSetList = () => {
	loading.value = true;
	state.formateData = [];
	getsyssettings()
		.then((res: any) => {
			state.data = res?.result ?? [];
			for (let j of state.data) {
				for (let i of j.systemSettings) {
					state.formateData.push({
						id: i.id,
						value: i.settingValue ? i.settingValue : i.valueType == 5 ? 'false' : null,
						valueType: i.valueType,
					});
					if (i.presetValue) {
						// 默认数据
						i.presetValue = JSON.parse(i.presetValue);
					}
					if (i.valueType == 1 && i.settingValue == null) {
						//多选
						i.settingValue = [];
					} else if (i.valueType == 1 && i.settingValue) {
						i.settingValue = i.settingValue.split(',');
					} else if (i.valueType == 8 && i.settingValue) {
						i.settingValue = i.settingValue.split(',');
					} else if (i.valueType == 9 && i.settingValue) {
						// 时间区间
						i.settingValue = i.settingValue.split(',');
						timeRageRef.value = [i.settingValue[0], i.settingValue[1]];
					}
					if (i.valueType == 5 && i.settingValue) {
						// 开关
						i.settingValue = JSON.parse(i.settingValue);
					}
					if (i.valueType == 3 && i.settingValue) {
						// 开关
						i.settingValue = Number(i.settingValue);
					}
				}
			}
			loading.value = false;
		})
		.catch(() => {
			loading.value = false;
		});
};
// 处理提交数据
const changeVal = (val: any, id: string | number, startOrEnd?: string) => {
	state.formateData.forEach((item: any) => {
		if (item.id == id) {
			item.value = val;
			if (item.valueType == 1 || item.valueType == 8) {
				// 多选 日期区间
				item.value = val.join(',');
			}
			if (item.valueType == 9) {
				// 时间区间
				if (startOrEnd == 'startTime') {
					// 开始时间
					timeRageRef.value[0] = val;
					item.value = timeRageRef.value.join(',');
				} else if (startOrEnd == 'endTime') {
					// 结束时间
					timeRageRef.value[1] = val;
					item.value = timeRageRef.value.join(',');
				}
			}
			if (item.valueType == 5 || item.valueType == 3) {
				// 开关 数字输入
				item.value = String(val);
			}
		}
	});
};
// 单个上传列表
const imageUrl = ref('https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100');
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
	imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};
// 单个图片上传
const uploadImg = (response:any, uploadFile:any) => {
	console.log(response, uploadFile);
};
// 上传之前限制大小和类型
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
	if (rawFile.type !== 'image/jpeg') {
		ElMessage.error('Avatar picture must be JPG format!');
		return false;
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('Avatar picture size can not exceed 2MB!');
		return false;
	}
	return true;
};
// 上传列表
const fileList = ref<UploadUserFile[]>([
	{
		name: 'food.jpeg',
		url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
	},
]);
// 多张图片上传
const uploadImgList = (file:any, list:any, id:any) => {
	console.log(file, list, id);
	fileList.value = list;
};
// 删除图片（多张）
const handleRemove = (uploadFile: any) => {
	uploadListRef.value[0].handleRemove(uploadFile.file);
};
// 预览图片 多张
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile:any) => {
	for (let i = 0; i < document.querySelectorAll('.images').length; i++) {
		if (uploadFile.file.url === document.querySelectorAll('.images')[i].getElementsByTagName('img')[0].src) {
			viewerApi({
				options: {
					toolbar: true,
					url: 'url',
					initialViewIndex: i,
				},
				images: fileList.value,
			});
			break;
		}
	}
};
// 保存
const submitForm = () => {
	modifysettings({ list: state.formateData })
		.then(() => {
			ElMessage.success('配置成功');
			getSetList();
		})
		.catch(() => {});
};
const resetForm = () => {
	getSetList();
};
// 页面加载时
onMounted(() => {
	getSetList();
});
</script>

<style lang="scss" scoped>
.system-systemParameter-container {
	.pd100 {
		padding: 0 10vw;
	}
	.maxwidth400 {
		max-width: 214px;
	}
	.form {
		flex: 1;
		overflow-y: auto;
		overflow-x: hidden;
	}
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
}
</style>
<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
