<template>
	<view class="page_body">
		<!-- 头部 -->
		<nav-bar height="96" :title="state.title" :onlyTitle="true" :showHeaderborder="true" @GoBack="GoBack"></nav-bar>
		<view :class="['page_content',{'view':state.type=='view'}]">
			<uni-forms ref="valiForm" :class="['forms_style',{'view':state.type=='view'}]" :rules="rules" :model="state.formData" border labelWidth="160rpx" label-align="right">
				<uni-forms-item label="荣誉类型：" required name="honorTypeValue">
					<template v-if="state.type=='view'">{{state.formData.honorTypeValue}}</template>
					<uni-data-select v-else v-model="state.formData.honorTypeValue" :clear="false" placeholder="请选择荣誉类型" :disabled="state.type=='upload'?false:true" :localdata="state.honorTypeData" style="width: 400rpx;" @change="ChangeDataSelect"></uni-data-select>
				</uni-forms-item>
				<template v-for="item in state.dynamicFormData">
					<uni-forms-item :label="`${item.dictName}：`" required :name="`input_${item.id}`">
						<template v-if="state.type=='view'">
							<template v-if="item.dictType == 1 || item.dictType == 2">{{state.formData[`${item.dictShowType}_${item.id}`]}}</template>
							<uni-dateformat v-else :date="state.formData[`${item.dictShowType}_${item.id}`]" format="yyyy-MM-dd"></uni-dateformat>
						</template>
						<template v-else>
							<uni-easyinput v-if="item.dictType == 1" v-model="state.formData[`${item.dictShowType}_${item.id}`]" :disabled="item.onlyRead == 1" :maxlength="100" :placeholder="`请输入${item.dictName}`" :style="{width: item.dictName=='获奖人'?'400rpx':''}" />
							<uni-data-select v-else-if="item.dictType == 2" v-model="state.formData[`${item.dictShowType}_${item.id}`]" :clear="false" :placeholder="`请选择${item.dictName}`" :localdata="item.dictList" style="width: 400rpx;"></uni-data-select>
							<uni-datetime-picker v-else type="date" :end="todayStr" :clear-icon="false" v-model="state.formData[`${item.dictShowType}_${item.id}`]" placeholder=" " style="width: 400rpx;" />
						</template>
					</uni-forms-item>
				</template>
				<uni-forms-item label="荣誉证书：" required name="certPicDatas">
					<uv-upload :maxCount="state.type=='view'?state?.formData?.certPicDatas?.length:50" :deletable="state.type!='view'" :fileList="state.formData.certPicDatas" width="240rpx" height="140rpx" multiple :previewFullImage="true" @AfterRead="AfterRead" @delete="DeletePic">
						<view class="upload_btn" v-if="state.type!='view'">
							<uni-icons class="upload_btn_icon" type="plusempty"></uni-icons>
							<view class="upload_btn_text">上传荣誉证书</view>
						</view>
					</uv-upload>
				</uni-forms-item>
				<uni-forms-item label="佐证材料：">
				</uni-forms-item>
				<uni-forms-item label="驳回原因 ：" v-if="state.formData.overruleContent">
					{{state.formData.overruleContent}}
				</uni-forms-item>
				<uni-forms-item label="审核人：" v-if="state.type=='view'">
					{{state.formData.reviewTeacherName}}
				</uni-forms-item>
			</uni-forms>
		</view>
		<view class="page_foot" v-if="state.type!='view'"><button class="btn_submit" type="primary" :loading="state.loading" @click="honorTypeConfirm">确认</button></view>
	</view>
</template>

<script setup>
	import navBar from '@/components/navBar.vue';
	import uniForms from '@/uni_modules/uni-forms/components/uni-forms/uni-forms.vue';
	import uniFormsItem from '@/uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue';
	import uniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
	import uniDataSelect from '@/uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue';
	import uniDatetimePicker from '@/uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue';
	import uniDateformat from '@/uni_modules/uni-dateformat/components/uni-dateformat/uni-dateformat.vue';
	import uvUpload from '@/uni_modules/uv-upload/components/uv-upload/uv-upload.vue';
	import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';
	import {queryHonorTypeDictList,queryHonorDataDetailById,addHonorCertData,updateHonorCertData} from '@/reqApi/teacherHonor.js';
	import { unioformDateTransform,fileSizeConvert } from '@/common/common.js';
	import {
		reactive,
		ref,
		onMounted,
		nextTick
	} from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	const state = reactive({
		id:'',//荣誉类型id
		title:'',//标题
		type:'',
		formData: {
			honorTypeValue: '',//荣誉类型id
			certPicDatas:[],//荣誉证书
			docDatas:[],//佐证材料
			overruleContent:'',//驳回原因
			reviewTeacherName:''//审核人
		},
		honorTypeData:[],//荣誉类型下拉
		dynamicFormData:[],//动态表单
		dictDatas:[],//动态表单传参
		loading:false
	})
	const todayStr = ref(new Date().toISOString().split('T')[0]);
	const rules = ref({
		honorTypeValue: { rules: [{ required: true, errorMessage: '请选择荣誉类型' }] },
		certPicDatas: { rules: [{ required: true, errorMessage: '请上传荣誉证书' }] },
	});
	onLoad(async(option) => {
		state.id = option.id;
		state.type = option.type;
		await GetHonorTypeDictList(option.type);//查询荣誉类型下拉数据
		if(option.type == 'upload'){
			state.title = '上传荣誉';
		}else{
			if(option.type == 'edit'){
				state.title = '修改荣誉';
			}else {
				state.title = decodeURIComponent(option.honorName);
			}
			GetHonorDataDetailById();
		}
		uni.setStorageSync('isLoadMyHonorList', false);//返回列表页是否重新加载我的荣誉列表
	})
	//查询荣誉类型下拉数据
	const GetHonorTypeDictList = async (type) => {
		await queryHonorTypeDictList().then(res=>{
			if(res.code == 200){
				const honorTypeData = res?.data?.honorTypeDictBOS || [];
				honorTypeData.forEach(item=>{
					item.value = item.id;
					item.text = item.honorTypeName;
					const honorTypeDictData = item?.honorTypeDictBOS || [];
					honorTypeDictData.forEach(itemList=>{
						if(itemList.dictType == 2){//单选
							itemList.dictShowType = 'radio';
							const dictList = itemList?.dictList || [];
							dictList.forEach(dic=>{
								dic.text = dic.dictName;
								dic.value = dic.id
							})
						}else if(itemList.dictType == 1){//输入框
							itemList.dictShowType = 'input';
						}else{//日期
							itemList.dictShowType = 'datetime';
						}
					})
				})
				state.honorTypeData = honorTypeData;//荣誉类型下拉数据;
				if(type == 'upload'){//荣誉类型默认值
					state.formData.honorTypeValue = honorTypeData?.[0].value || '';//荣誉类型默认值
					const honorTypeDictData = honorTypeData?.[0]?.honorTypeDictBOS || [];
					SetDynamicFormData(honorTypeDictData);//设置动态表单
				}
			}else{
				state.honorTypeData = [];
			}
		})
	}
	//设置动态表单的值
	const SetDynamicFormData = (honorTypeDictData) => {
		honorTypeDictData.forEach(item=>{
			if(item.dictType == 2){//单选
				state.formData[`${item.dictShowType}_${item.id}`] = '';
				rules.value[`${item.dictShowType}_${item.id}`] = { rules: [{ required: true, errorMessage: `请选择${item.dictName}` }] };
			}else {//输入框 日期
				const value = item?.dictList?.[0]?.dictName || '';
				state.formData[`${item.dictShowType}_${item.id}`] = value;
				const placeholder = item.dictType == 1 ? '请输入' : '请选择';
				rules.value[`${item.dictShowType}_${item.id}`] = { rules: [{ required: true, errorMessage: `${placeholder}${item.dictName}` }] };
			}
		})
		state.dynamicFormData = honorTypeDictData;//动态表单
	}
	//改变荣誉类型
	const ChangeDataSelect = (val) => {
		const selectedHonorType = state.honorTypeData.find(item=>item.id == val);
		const honorTypeDictData = selectedHonorType?.honorTypeDictBOS || [];
		SetDynamicFormData(honorTypeDictData)
	}
	//查看荣誉详情接口
	const GetHonorDataDetailById = () => {
		queryHonorDataDetailById(state.id).then(res=>{
			if(res.code == 200){
				const honorTypeId = res?.data?.honorTypeId || '';
				const honorTypeName = res?.data?.honorTypeName || '';
				state.formData.honorTypeValue = state.type=='view'?honorTypeName:honorTypeId;//荣誉类型默认值
				//给动态表单设置值
				const selectedHonorType = state.honorTypeData.find(item=>item.id == honorTypeId);
				const honorTypeDictData = selectedHonorType?.honorTypeDictBOS || [];
				state.dynamicFormData = honorTypeDictData;//动态表单
				const honorDataList = res?.data?.honorDataList || '';
				honorDataList.forEach(item=>{
					if(item.dictType == 2){//单选
						state.formData[`radio_${item.honorDictLibNameId}`] = state.type!='view'?item.honorDictLibValueId:item.honorDictLibValue;
					}else {//输入框 日期
						const type = item.dictType == 1 ? 'input' : 'datetime';
						state.formData[`${type}_${item.honorDictLibNameId}`] = item.honorDictLibValue;
					}
				})
				const honorDataCertList = res?.data?.honorDataCertList || [];//荣誉证书
				state.formData.certPicDatas = honorDataCertList.map(item=>({
					...item,
					url:item.picUrl
				}));//荣誉证书
				state.formData.docDatas = res?.data?.supportDocumentList || [];//佐证材料
				state.formData.overruleContent = res?.data?.overruleContent || '';//驳回原因
				state.formData.reviewTeacherName = res?.data?.reviewTeacherName || '';//审核人
			}
		})
	}
	//提交
	const honorTypeConfirm = () => {
		for (const key in rules.value) {
			if (state.formData?.[key] === "" || state.formData?.[key] === null || state.formData?.[key]&&state.formData?.[key]?.length === 0) {
				const errorMessage = rules.value[key].rules[0].errorMessage;
				uni.showToast({
					title: errorMessage,
					icon: 'none'
				})
				return false
			}
		}
		state.loading = true;
		const certPicDatas = state.formData.certPicDatas.map(item=>({
			name:item.picName,
			url:item.url,
			fileSize:item?.fileSize || '',
			time:item?.time || '',
		}))
		const docDatas = state.formData.docDatas.map(item=>({
			name:item.documentName,
			url:item.documentUrl,
			fileSize:item.fileSize,
			time:item.createdAt,
		}))
		const dictDatas = [];
		state.dynamicFormData.forEach(item=>{
			if(item.dictType == 2){//单选
				const valueData = state.formData[`${item.dictShowType}_${item.id}`];
				const dictList = item?.dictList || [];
				const valueName = dictList.find(dic=>dic.id == valueData);
				dictDatas.push({
					keyId: item.id,
					keyName: item.dictName,
					valueId: valueData,
					valueName: valueName?.dictName || ''
				})
			}else{
				let valueData = state.formData[`${item.dictShowType}_${item.id}`];
				if(state.type == 'upload' && Number(item.dictType) === 0){
					valueData = valueData + ' 00:00:00'
				}
				const dictList = item?.dictList || []; 
				dictDatas.push({
					keyId: item.id,
					keyName: item.dictName,
					valueId: dictList?.[0]?.id,
					valueName: valueData
				})
			}
		})
		let params =  {
			certPicDatas: certPicDatas,
			dictDatas: dictDatas,
			docDatas:docDatas,
			honorTypeId: state.formData.honorTypeValue
		}
		
		if(state.id){
			params.id = state.id;
			updateHonorCertData(params).then(res=>{
				if(res.code == 200){
					uni.showToast({
						title: '修改成功！',
						icon: 'none'
					})
					uni.setStorageSync('isLoadMyHonorList', true);//返回列表页是否重新加载我的荣誉列表
					GoBack();
				}
			}).finally(()=>{
				state.loading = false;
			})
		}else{//新建
			addHonorCertData(params).then(res=>{
				if(res.code == 200){
					uni.showToast({
						title: '上传成功！',
						icon: 'none'
					})
					uni.setStorageSync('isLoadMyHonorList', true);//返回列表页是否重新加载我的荣誉列表
					GoBack();
				}else{
					
				}
			}).finally(()=>{
				state.loading = false;
			})
		}
	}
	// 删除图片
	const DeletePic = (event) => {
		state.formData.certPicDatas.splice(event.index, 1);
	}
	// 新增图片
	const AfterRead = async(event) => {
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = state.formData.certPicDatas.length;
		lists.map((item) => {
			state.formData.certPicDatas.push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			if(result.code == 200){
				let item = state.formData.certPicDatas[fileListLen]
				state.formData.certPicDatas.splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					picName: result?.data?.fileName,
					url:result?.data?.url,
					fileSize:fileSizeConvert(lists?.[i]?.size || 0),
					time:unioformDateTransform(new Date())
				}))
				fileListLen++
			}
			
		}
	}
	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			const token = uni.getStorageSync('token'); // 假设从本地存储获取token
			let a = uni.uploadFile({
				url: '/api/v1/teach/oss/file/oss/upload_filesSele',
				filePath: url,
				name: 'file',
				header:{
					Authorization:token
				},
				success: (res) => {
					const resdata = JSON.parse(res.data);
					console.log(res,1323)
					resolve(resdata)
				}
			});
		})
	}
	const GoBack = () => {
		uni.navigateBack({
			delta: 1
		});
	}
</script>

<style lang="scss" scoped>
	.page_body{
		height: 100%;
		min-height: auto;
		overflow: hidden;
	}
	.page_content{
		height: calc(100% - 250rpx);
		overflow: auto;
		&.view{
			height: calc(100% - 96rpx);
		}
	}
	.forms_style{
		:deep(.uni-forms-item){
			&.uni-forms-item--border{
				border-top: 0;
				border-bottom: 2rpx solid #F3F3F3;
				.uni-forms-item__label{
					align-items: flex-start;
					padding-top: 16rpx;
				}
			}
			.uv-upload__wrap{
				// flex-direction: row-reverse;
				gap: 24rpx 32rpx;
				.uv-upload__wrap__preview{
					background-color: #FFFFFF;
					border-radius: 20rpx;
					border: 2rpx solid #CED1D8;
					box-sizing: border-box;
					margin: 0;
					.uv-upload__deletable{
						top:10rpx;
						right: 10rpx;
						background-color: transparent;
						height: 32rpx;
						width: 32rpx;
						border: 2rpx solid #999999;
						border-radius: 50%;
						.uvicon-close{
							color:#999999 !important;
							font-size: 11rpx !important;
						}
					}
					.uv-upload__deletable__icon{
						transform: scale(1);
						top:50%;
						right: 50%;
						transform: translate(50%, -50%);
					}
					.uv-upload__success{
						border-width: 20rpx;
					}
				}
				.upload_btn{
					width: 240rpx;
					height: 140rpx;
					background-color: #FAFBFF;
					border-radius: 20rpx;
					border: 2rpx solid #CCCED4;
					box-sizing: border-box;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					.upload_btn_icon{
						font-size: 40rpx !important;
						color: #CCCED4 !important;
					}
					.upload_btn_text{
						margin-top: 16rpx;
						font-weight: 400;
						font-size: 24rpx;
						color: #CCCED4;
					}
				}
			}
		}
	}
	.page_foot{
		position: fixed;
		left:0;
		right: 0;
		bottom: 0;
		padding: 20rpx 24rpx;
		background-color:#FFFFFF;
		.btn_submit{
			width: 100%;
			height: 88rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #2E64FA !important;
			border-radius: 20rpx;
			color: #FFFFFF;
			font-size: 28rpx;
		}
	}
</style>