<template>
	<view class="task-details-page">
		<ch-nav-bar title="作业详情" :height="66"></ch-nav-bar>
		<uni-list>
			<uni-list-item :showArrow="false" title="作业名称" :rightText="task.homeworkname" />
			<uni-list-item :showArrow="false" title="提交状态" :rightText="status" />
			<uni-list-item :showArrow="false" title="作业图片" />
			<ch-image-uploader
				v-model="files"
				ref="imgUploader"
				:limit="5"
				:url="uploadUrl">
			</ch-image-uploader>
		</uni-list>
		<button class="submit-btn" type="primary" :loading="uploading" :disabled="isDisable" @click="submitTask">提交图片</button>
	</view>
</template>

<script setup>
import { reactive, toRefs, ref, computed, onMounted } from 'vue';
import ChNavBar from '@/components/ch-nav-bar/ch-nav-bar.vue';
import ChImageUploader from '@/components/ch-image-uploader/ch-image-uploader.vue';
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user.js'
import { uploadTaskImg, getTaskInfo } from '@/api/task.js';
import config from '@/utils/network/config.js'

const userStore = useUserStore();
const userId = userStore.userId;
const imgUploader = ref(null);


const data = reactive({
	task: {},
	files: [],
	img: null,
	imgStyle: {
		"height": 400,
		"width": 400,
	},
	taskId: '',
	uploading: false,
	igUrl: ''
})

const { task, img, imgStyle , files, taskId, uploading, igUrl } = toRefs(data);

const isDisable = computed(() => !files.value.length || uploading.value)

const status = computed(() => {
	if (!task.value.status) return ''
	
	return task.value.status == 1 ? '未提交' : '已提交'
})

const uploadUrl = computed(() => {
	return `${config.baseUrl}/api/user.ashx?act=subhomeworkinfo&studentid=${userId}&homeworkid=${taskId.value}`
})

onLoad((option) => {
	taskId.value = option.id;
	console.log(uni.canIUse('chooseImage'))
})

onMounted(() => {
	const params = {
		homeworkid: taskId.value,
		studentid: userId
	}
	getTaskInfo(params, { loading: true }).then(info => {
		task.value = info;
		if (!info.studentimg) return;
		const imgArr = info.studentimg.split(',')
		console.log(imgArr)
		imgArr.forEach(item => {
			if (!item) return;
			uni.getImageInfo({
				src: `${config.baseUrl}/${item}`,
				success({ path, type }) {
					files.value.push({
						name: 'image' + (+new Date()),
						extname: `image/${type}`,
						path,
					})
				}	
			})
		})
	})
})

function submitTask () {
	uploading.value = true;
	console.log(imgUploader)
	imgUploader.value.upload()
	.finally(() => {
		uploading.value = false;
	})
}

function imgChange (e) {
	console.log(e)
	img.value = e.tempFiles[0]
}

// File 转 Blob
function fileToBlob (file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.addEventListener('load', (e) => {
				console.log(e.target.result)
				const blob = new Blob([e.target.result]);
				console.log("Blob对象", blob);
				resolve(blob)
		})
		reader.readAsArrayBuffer(file)
	})
}
</script>

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