<template>
	<view class="i-clicker-page">
		<ch-nav-bar title="答题器" :height="66" :rightWidth="120">
			<template v-slot:right>
				<uni-icons class="handle-icon" type="reload" size="56" color="#fff" @tap="refresh"/>
				<uni-icons class="handle-icon"  type="checkmarkempty" size="56" color="#fff" @tap="submitAnswer"/>
			</template>
		</ch-nav-bar>
		<ch-empty emptyText="暂无答题任务" v-if="!options.length"></ch-empty>
		<ch-flex class="answer-options" justify="around" items="center" @tap.native="selectOpt" v-else>
			<block v-for="option in options" :key="option.id">
				<view class="option" :class="{ 'selected': selectOpts.includes(option.text) }" :data-opt="option">
					{{ option.text }}
				</view>
			</block>
		</ch-flex>
	</view>
</template>

<script setup>
import { getIClickerData, submitIClickerData } from '@/api/iClicker.js'
import { reactive, toRefs } from 'vue';
import { useUserStore } from '../../store/user';

const defaultOptions = [
	{
		id: '001',
		text: 'A'
	},
	{
		id: '002',
		text: 'B'
	},
	{
		id: '003',
		text: 'C'
	},
	{
		id: '004',
		text: 'D'
	},
]

const userStore = useUserStore();
const userId = userStore.userId;

const data = reactive({
	options: [...defaultOptions],
	selectOpts: []
})

const { options, selectOpts } = toRefs(data);

function selectOpt (e) {
	const opt = e.target.dataset.opt || null;
	if (!opt) return;
	const index = selectOpts.value.findIndex(text => text == opt.text)
	selectOpts.value = index == -1 ? [...selectOpts.value, opt.text]
																	: selectOpts.value.filter(text => text!== opt.text)
}

function submitAnswer () {
	uni.showModal({
		content: '确定要提交答案？',
		confirmText: '提交',
		cancelText: '放弃',
		success: () => {
			const params = {
				studentanswer: selectOpts.value.join(','),
				studentid: userId
			}
			
			submitIClickerData(params).then(res => {
				uni.showToast({
					icon: 'success',
					title: '已提交'
				})
				refresh();
			}).catch(() => {
				uni.showToast({
					icon:'error',
					title: '提交失败'
				})
			})
		}
	})
}

function refresh () {
	selectOpts.value = [];
}
</script>

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