<template>
<view class="page">
	<u-form :model="form" ref="uForm" :label-width="120">
		<view class="form-box">
			<u-form-item label="问卷名称"><u-input v-model="form.title" /></u-form-item>
		</view>
		<view class="form-box">
			<u-form-item label="问卷说明" label-position="top"><u-input v-model="form.remarks" type="textarea"/></u-form-item>
		</view>
		<view class="select-item" v-for="(val,index) in items" :key="index">
			<view class="top">
				<view class="title" style="display: flex;align-items: center;">
					{{index + 1}}.<u-input v-model="val.tikuTitle" type="text" :border="false"  style="margin-left: 10px;"/>
				</view>
				<u-form-item label="题型"  borderBottom>
					<u-input v-model="val.questionType" type="select" @click="tixin(index)"
						placeholder='请选择题型' />
				</u-form-item>
				<u-radio-group class="radio-box" v-if="val.questionType=='单选'">
					<u-radio shape="circle" v-for="(item,val) in val.optionSettings"><u-input v-model="item.ules" type="text" :border="false" style="margin-left: 10px;"  /></u-radio>
				</u-radio-group>
				<u-checkbox-group   v-if="val.questionType=='多选'">
							<u-checkbox 
								 v-for="(item,val) in val.optionSettings"
							><u-input v-model="item.ules" type="text" :border="false" style="margin-left: 10px;"  /></u-checkbox>
						</u-checkbox-group>
			</view>
			<view class="bottom">
				<!-- <u-button type="primary" size="mini">编辑</u-button> -->
				<u-button type="success" size="mini" @click="addxuan(index)" v-if="val.questionType!=''">添加选项</u-button>
				<u-button type="success" size="mini" @click="moveUp(index)">上移</u-button>
				<u-button type="success" size="mini" @click="moveDown(index)">下移</u-button>
				<u-button type="error" size="mini" @click="del(index)">删除</u-button>
			</view>
		</view>
		 <view style="padding: 20px 45%;margin-bottom: 40px;color: #0FBB59;" @click="addItems"> + 添加</view>
	</u-form>
		<view class="page-footer">
			<u-button type="info" @click="go('/pages/setPage/setPage')"><u-icon name="setting" ></u-icon>设置</u-button>
			<u-button type="info" @click="goDetail()"><u-icon name="eye"></u-icon>预览</u-button>
			<u-button type="success" @click="tijiao"><u-icon name="checkmark-circle"></u-icon>提交</u-button>
		</view>	  
		<u-select v-model="typeShow" :list="questionnaireType" @confirm="typeChange"></u-select>
</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					title:'',
					remarks:'',
					questionId:'',
					
				},
				items: [{
					tikuTitle: '',
					questionBank:'用户端题库',
					questionType: '',
					optionSettings: [{
					1:''
						}],
				}],
				xuanSet:[{
					1:''
				}],
				value:0,
				typeShow:false,
				questionnaireType: [{
						value: 1,
						label: '单选'
					},
					{
						value: 2,
						label: '多选'
					}
				],
				tixinIndex:0,
				formS:{
					
				}
			}
		},
		onLoad(option) {
			if(option.data){
				this.form = {...this.form,...JSON.parse(option.data)}	
				this.formS = JSON.parse(option.data)
			}
		 
		},
		methods:{
			go(urls){
				uni.navigateTo({
					url:`${urls}`
				})
			},
			 bindTextAreaBlur: function (e) {
			            console.log(e.detail.value)
			        },
					addItems() {
						this.items.push({
					tikuTitle: '',
					questionBank:'用户端题库',
					questionType: '',
					optionSettings: [{
					1:''
						}],
				})
					},
					addxuan(index){
						this.items[index].optionSettings.push({
							index:'',
						})
					},
					del(index){
						this.items.splice(index, 1)
						
					},
					  moveUp(index) {
					      if (index > 0) {
					        // 使用数组的 splice 方法交换元素位置
					        this.items.splice(index - 1, 0, this.items.splice(index, 1)[0]);
					      }
					    },
					    moveDown(index) {
					      if (index < this.items.length - 1) {
					        // 使用数组的 splice 方法交换元素位置
					        this.items.splice(index + 1, 0, this.items.splice(index, 1)[0]);
					      }
					    },
						tijiao(){
					
						  let Ids = [];
						  let promises = this.items.map(tem => {
						 //    tem.optionSettings =  {}
							// tem.optionSettings =  tem.optionSettings.map((item,index) => `"${index + 1 }":"${item.ules}"`).join(',')
							let strSettings = tem.optionSettings.map((item, index) => `"${index + 1}":"${item.ules}"`).join(',');
							
							// 将字符串转换为对象
							let objSettings = JSON.parse('{' + strSettings + '}');
							tem.optionSettings =  JSON.stringify(objSettings)
					         
						    tem.user = uni.getStorageSync('shopId');
						    return this.$http.sendRequest('/cereQuestionManagement/add', 'POST', tem, 1).then(res => {
						      Ids.push(res.data.data.id)
						    })
						  })
							this.form.createTime = this.currentTime()
						  Promise.all(promises).then(() => {
						    this.form.questionId = Ids.join(',');
						    // let obj = { ...this.form, ...this.formS }
						
						    this.$http.sendRequest('/cereQuestionnaireTable/add', 'POST', this.form, 1).then(res => {
						      uni.redirectTo({
						        url: '/pages/questionnaire/questionnaire'
						      })
						    })
						  }).catch(error => {
						    console.error('Error:', error);
						  })
						},
						tixin(index){
							this.typeShow = true
							this.tixinIndex = index
						},
						typeChange(e) {
							this.items[this.tixinIndex].questionType = e[0].label
						},
						goDetail(){
						
							let obj ={
								msg :this.items
							}
							obj = JSON.stringify(obj)
							uni.navigateTo({
								url: `/pages/questionnaire/questDetail/questDetail?detail=${JSON.stringify(obj)}`
							})
					
						},
						// 获取时间
						currentTime() {
						  let date = new Date();
						  let year = date.getFullYear();
						  let month = date.getMonth() + 1; // 月份从0~11，所以加一
						  let day = date.getDate();
						  let hours = date.getHours();
						  let minutes = date.getMinutes();
						  let seconds = date.getSeconds();
						
						  // 为月、日、小时、分钟和秒添加前导零（如果需要）
						  month = month < 10 ? '0' + month : month;
						  day = day < 10 ? '0' + day : day;
						  hours = hours < 10 ? '0' + hours : hours;
						  minutes = minutes < 10 ? '0' + minutes : minutes;
						  seconds = seconds < 10 ? '0' + seconds : seconds;
						
						  // 返回格式化的日期和时间字符串
						  return `${year}-${month}-${day} ${hours}:${minutes}`;
						},
		}
	}
</script>

<style  scoped lang="scss">
	@import 'createQuestionnaire.scss';
</style>