<template>
  <view class="sort-answer">
    <uni-forms ref="baseForm" :modelValue="formData" label-position="top" label-width="auto">
      <uni-forms-item
          v-for="(item,index) in formData.answerList"
          :name="`answerList[${index}].answer`"
          :rules="[{
				required: true,
				errorMessage: item.question.includes('请上传')?'请上传照片':'请输入考试答题' ,
			}]"
          :label="item.order+'、'+item.question" required>
        <up-textarea v-if="!item.question.includes('请上传')" v-model="item.answer" :maxlength="1000"
                     placeholder="请输入内容,600百字以内" :height="200"
                     count></up-textarea>
        <uni-file-picker v-else v-model="item.answer" @select="(e)=>successUpload(e,item)" limit="6"
                         title="最多选择6张图片"
                         :image-styles="imageStyles"></uni-file-picker>
      </uni-forms-item>
    </uni-forms>
  </view>
  <submitBut text="提交" @click="handleClick"></submitBut>
</template>
<script setup>
import submitBut from "../../../components/submitBut/index.vue"
import {getTrainQuestion, submitTrainCheckAnswer} from "../../../api/work/work";
import {ref} from "vue"
import tab from "../../../plugins/tab";
import {getStorage} from "../../../utils/auth";

const formData = ref({
  answerList: [],
  staffId: getStorage("userInfo").id
})
const imageStyles = ref({
  width: 100,
  height: 100,
})
const baseForm = ref()
const value = ref()
const getTrainQuestions = async () => {
  const {data} = await getTrainQuestion()
  formData.value.answerList = data || []
}
getTrainQuestions()
const handleClick = async () => {
  baseForm.value.validate((valida, err) => {
    console.log(!valida);
  })
  await submitTrainCheckAnswer(formData.value)
  tab.navigateTo("/otherPages/workbenchManage/queryResults/index")
}
// 新增图片
const successUpload = async (event, item) => {
  console.log(event);
  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.tempFiles)
  let fileList = item.answer || []
  let fileListLen = fileList.length
  lists.map((item) => {
    fileList.push({
      ...item
    })
  })
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url)
    let item = fileList[fileListLen]
    fileList.splice(fileListLen, 1, Object.assign(item, {
      status: 'success',
      message: '',
      url: result
    }))
    fileListLen++
  }
  item.answer = fileList
}
const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'https://store-test.catmdogd.com/test-api/h5/oss/upload', // 仅为示例，非真实的接口地址
      filePath: url,
      name: 'file',
      formData: {
        user: 'test'
      },
      success: (res) => {
        setTimeout(() => {
          if (res && res.data) {
            let resData = JSON.parse(res.data);
            resolve(resData.url);
          }
          reject("上传失败");
        }, 1000)
      }
    });
  })
}
</script>
<style scoped lang="scss">
.sort-answer {
  padding: 40rpx 40rpx 140rpx;
  background: #FFFFFF;

  &-item {
    margin-bottom: 30rpx;
  }

  &-question {
    display: flex;
    margin-bottom: 20rpx;
    line-height: 50rpx;
  }

  :deep(.uni-forms-item__label) {
    height: auto !important;
    align-items: start !important;
  }
}
</style>