import { Tag, Image, Button } from 'vant'
import { computed, defineComponent, nextTick, onMounted, PropType, reactive } from 'vue'
import { AnswerType, labelOptions, QuestionType } from '../../unit'
import Draggable from 'vuedraggable'
import styles from './index.module.less'
import Sortable from 'sortablejs'
import deepClone from '@/helpers/deep-clone'
import AnserTitle from '../anser-title'
import AnswerAnalysis from '../answer-analysis'

// 单选和多选题
export default defineComponent({
  name: 'choice-question',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    index: {
      // 题目是第几道
      type: Number,
      default: 1
    },
    data: {
      type: Object,
      default: () => ({})
    },
    /* 只读 */
    readOnly: {
      type: Boolean,
      default: false
    },
    showRate: {
      // 是否显示答题的正确率
      type: Boolean,
      default: false
    },
    showAnalysis: {
      // 是否显示解析
      type: Boolean,
      default: false
    },
    analysis: {
      type: Object,
      default: () => ({
        message: '',
        topic: false, // 是否显示结果
        userResult: true // 用户答题对错
      })
    }
  },
  emits: ['update:value'],
  setup(props, { emit }) {
    const state = reactive({
      domId: 'draggableContainer' + +new Date(),
      drag: false,
      sortable: null as any,
      list: [] as any,
      options: [] as any
    })

    onMounted(() => {
      nextTick(() => {
        const el = document.getElementById(state.domId)
        state.sortable = Sortable.create(el, {
          disabled: props.readOnly,
          animation: 150,
          sort: true,
          fallbackTolerance: 3,
          onUpdate: (evt: any) => {
            const updatePosition = (list: any) =>
              list.splice(evt.newIndex, 0, list.splice(evt.oldIndex, 1)[0])
            if (state.list && state.list.length > 0) {
              updatePosition(state.list)
            } else {
              state.list = [...state.options]
              updatePosition(state.list)
            }
            onSelect()
          }
        })
      })
    })

    // 返回选中的结果
    const onSelect = () => {
      // const options = state.options || []
      const list = state.list || []
      const result: any = []

      console.log(list, '1212')
      list.forEach((item: any, index: number) => {
        console.log(index, '测试返回')
        result.push({
          answerId: item.index,
          answer: item.leftValue,
          answerExtra: index + 1
        })
      })
      emit('update:value', result)
    }

    // 修改题目逻辑
    const onSelectAnswer = (item: any) => {
      // 判断是否已经选中了
      if (item.checked) return
      const result: any = []
      state.options.forEach((option: any, index: any) => {
        result.push({
          answerId: option.index,
          answer: option.leftValue,
          answerExtra: index + 1
        })
      })
      result.push({
        answerId: item.examinationQuestionAnswerId,
        answer: item.questionAnswer,
        answerExtra: state.options.length + 1
      })
      emit('update:value', result)

      initOptions()
    }

    const answers = computed(() => {
      const list: any = props.data.answers || []
      const value: any = props.value || []

      list.forEach((item: any) => {
        const tempIndex = value.findIndex(
          (c: any) => c.answerId === item.examinationQuestionAnswerId
        )
        if (tempIndex !== -1) {
          item.checked = tempIndex !== -1 ? true : false
        }
      })
      return list
    })
    const initOptions = () => {
      const answers = props.data.answers || []
      const userAnswer = props.data.userAnswer || [] // 用户填写的答案
      console.log(answers, userAnswer)
      state.options = []
      if (userAnswer.length > 0) {
        userAnswer.forEach((answer: any, index: any) => {
          const rightOption = answers.find(
            (child: any) => answer.answerId === child.examinationQuestionAnswerId
          )
          const rightValue = answers.find(
            (child: any) => answer.answerExtra === child.questionExtra
          )
          const tmp = {
            itemIndex: index,
            index: answer.answerId, // 左边的值
            leftValue: answer.answer, // 左边的值
            rightValue: answer.answerExtra, // 右边的值
            leftType: rightOption.questionAnswerTypeCode || 'TXT', // 左边类型
            rightType: rightOption.questionExtraTypeCode || 'TXT', // 右边类型
            rightIndex: rightValue ? rightValue.examinationQuestionAnswerId : ''
          }
          state.options.push(tmp)
        })
      }
      //  else {
      //   const resultValue: any = []
      //   answers.forEach((answer: any) => {
      //     const tmp = {
      //       index: answer.examinationQuestionAnswerId, // 左边的值
      //       leftValue: answer.questionAnswer, // 左边的值
      //       rightValue: answer.questionExtra, // 右边的值
      //       leftType: answer.questionAnswerTypeCode || 'TXT', // 左边类型
      //       rightType: answer.questionExtraTypeCode || 'TXT' // 右边类型
      //     }
      //     resultValue.push({
      //       answerId: answer.examinationQuestionAnswerId,
      //       answer: answer.questionAnswer,
      //       answerExtra: answer.questionExtra
      //     })
      //     state.options.push(tmp)
      //   })
      //   // 进页面就默认初始化答案
      // }
    }

    onMounted(() => {
      initOptions()
    })

    return () => (
      <>
        <div class={styles.unitSubject}>
          {/* 标题 */}
          <AnserTitle
            index={props.index}
            name={props.data.name}
            showRate={props.showRate}
            score={props.data.totalScore}
            answerType={QuestionType.SORT}
            extra={{
              rightRate: props.data.rightRate,
              questionDetail: props.data.questionDetail,
              mediaUrls: props.data.mediaUrls
            }}
          />

          <div class={[styles.unitAnswers]}>
            {answers.value.map((item: any, index: number) => (
              <div
                class={[styles.unitAnswer, item.checked && styles.active]}
                onClick={() => onSelectAnswer(item)}
              >
                <div class={styles.answerContent}>
                  <span class={styles.option}>{labelOptions[index + 1]}.</span>
                  {item.questionAnswerTypeCode === AnswerType.IMAGE && (
                    <div class={styles.value}>
                      <Image src={item.questionAnswer} />
                    </div>
                  )}
                  {item.questionAnswerTypeCode === AnswerType.TXT && (
                    <div class={styles.value}>{item.questionAnswer}</div>
                  )}
                </div>
              </div>
            ))}
            <div class={[styles.sortReset, 'van-hairline--top']}>
              <span class={styles.tips}>我的回答（可拖拽）</span>
              <Button
                type="primary"
                round
                disabled={props.readOnly}
                onClick={() => {
                  const ids: any = []
                  const answers = state.options || []
                  // console.log(answers, 'reset')
                  answers.forEach((item: any) => {
                    ids.push(item.itemIndex)
                  })
                  console.log(ids)
                  state.sortable.sort(
                    ids.sort((a: any, b: any) => a - b),
                    true
                  )

                  // state.options.forEach((item: any) => {
                  //   item.checked = false
                  // })
                  // state.list = []

                  onSelect()
                }}
              >
                重置
              </Button>
            </div>
            <div id={state.domId}>
              {state.options.map((item: any) => (
                <>
                  {item.leftType === AnswerType.TXT && (
                    <Tag class={[styles.items]} data-id={item.itemIndex}>
                      {item.leftValue}
                    </Tag>
                  )}
                  {item.leftType === AnswerType.IMAGE && (
                    <Image
                      src={item.leftValue}
                      data-id={item.index}
                      class={[styles.imgs, 'van-hairline--surround']}
                      fit="cover"
                    />
                  )}
                </>
              ))}
            </div>
          </div>
        </div>
        {props.showAnalysis && (
          <div class={styles.unitSubject}>
            <AnswerAnalysis
              answerAnalysis={props.analysis.message}
              topic={props.analysis.topic}
              userResult={props.analysis.userResult}
            />
          </div>
        )}
      </>
    )
  }
})
