import { Apis } from '@/gen/Apis'
import { getApiLoading } from '@/common/libraries/apiLoading'
import useModel from './model'
export default {
  getShow(id: string) {
    getApiLoading(Apis.Survey.Surveys.Questions, { release_id: id }).then(res => {
      useModel.showData.value = res?.data || {}
    })
  },
  handleSubmit() {
    let data = useModel?.showData?.value?.questions || []
    let formAnswers: any = []
    console.log(data, 'data')
    if (data?.length) {
      let isError = false
      data?.map((res: any, index: number) => {
        if (isError) return
        if (res?.required && res?.type === 'Score' && !res?.score) {
          uni.showToast({ title: `第${index + 1}题请选择！`, icon: 'none' })
          isError = true
          return
        }
        if (res?.required && res?.type === 'Fill' && !res?.answer_content) {
          uni.showToast({ title: `第${index + 1}题请填写！`, icon: 'none' })
          isError = true
          return
        }
        formAnswers.push({
          question_id: res?.id,
          answer_content: res?.answer_content,
          score: res?.score
        })
      })
      if (isError) {
        return
      }
      getApiLoading(Apis.Survey.Surveys.SubmitResponse, {
        answers: formAnswers,
        surveyId: useModel?.showData?.value?.survey?.id,
        release_id: useModel?.showData?.value?.survey?.release_id
      }).then(res => {
        uni.showToast({ title: '提交成功！', icon: 'none' })
        setTimeout(() => {
          uni.navigateBack({ delta: 1, fail: () => {
            uni.switchTab({ url: '/pages/index/index' })
          } })
        }, 1000)
        console.log(res)
      })
    }
  },
  setAnswer(index: number, score: number) {
    useModel.showData.value.questions[index].score = score
  }
}
