import { defineComponent, onMounted, reactive, ref, watch } from 'vue'
import { NButton, NIcon, NInput, NSpace, NTooltip, useMessage } from 'naive-ui'
import styles from '../index.module.less'
import { Menu } from '@vicons/ionicons5'
import { DeleteFilled } from '@vicons/antd'
import Draggable from 'vuedraggable'
import UploadFile from '@/components/upload-file'
import { uniqueId } from 'lodash'

export default defineComponent({
  name: 'topicRadio',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    answers: {
      type: Array,
      default: () => []
    },
    questionTypeCode: {
      type: String,
      default: ''
    },
    optionType: {
      type: String,
      default: ''
    },
    optionAnswerType: {
      type: String,
      default: 'TXT'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    value: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['update'],
  setup(props, { emit }) {
    const createItem = (isRight = false, item?: any) => {
      if (item) {
        const n: any = {
          eleId: uniqueId(),
          questionExtra: item.questionExtra, // 附加答案内容
          questionAnswer: item.questionAnswer, // 答案内容
          answerAnalysis: item.answerAnalysis, // 答案解析
          rightAnswerFlag: item.rightAnswerFlag // 是否是正确答案
        }
        const questionAnswerTypeCode = item.questionAnswerTypeCode || props.optionType
        const questionExtraTypeCode = item.questionExtraTypeCode || props.optionAnswerType
        if (questionAnswerTypeCode === 'TXT') {
          n.text = item.questionAnswer
        } else if (questionAnswerTypeCode === 'IMAGE') {
          n.img = item.questionAnswer
        } else {
          n.audio = item.questionAnswer
        }
        if (props.questionTypeCode == 'SORT') {
          n.sort = item.questionExtra
        }
        if (props.questionTypeCode == 'LINK') {
          console.log()
          n.text1 = questionExtraTypeCode === 'TXT' ? item.questionExtra : ''
          n.img1 = questionExtraTypeCode === 'IMAGE' ? item.questionExtra : ''
        }
        return n
      }
      return {
        eleId: uniqueId(),
        questionExtra: '', // 附加答案内容
        questionAnswer: '', // 答案内容
        answerAnalysis: '', // 答案解析
        rightAnswerFlag: isRight, // 是否是正确答案
        text: '',
        img: '',
        audio: '',
        errorText: '',
        sort: '', // 排序专用
        text1: '', //连连看专用
        img1: '' //连连看专用
      }
    }
    const message = useMessage()
    const sortRef = ref()
    const data = reactive({
      list: [createItem(true)] as any
    })
    // 初始化
    if (props.answers?.length) {
      data.list = []
      props.answers.forEach((n: any) => {
        data.list.push(createItem(true, n))
      })
    }
    watch(
      () => data.list,
      () => {
        createList()
      },
      { deep: true }
    )
    // 生成数据
    const createList = () => {
      let list: any = []
      for (let i = 0; i < data.list.length; i++) {
        const item = data.list[i]
        if (props.questionTypeCode == 'SORT') {
          item.sort = i + 1 + ''
        }
        const newItem = {
          questionAnswerTypeCode: props.optionType, //答案类型,可用值:TXT,IMAGE,AUDIO
          questionExtraTypeCode: props.optionAnswerType,
          questionExtra:
            props.questionTypeCode == 'SORT'
              ? i + 1
              : props.optionAnswerType == 'TXT'
              ? item.text1
              : item.img1, // 附加答案内容
          questionAnswer:
            props.optionType === 'TXT'
              ? item.text
              : props.optionType === 'IMAGE'
              ? item.img
              : item.audio, // 答案内容
          answerAnalysis: item.answerAnalysis, // 答案解析
          rightAnswerFlag: item.rightAnswerFlag // 是否是正确答案
        }
        list.push(newItem)
      }
      emit('update', list)
    }
    // 修改正确答案
    const handleChangeAnswer = (item: any, isRight: boolean) => {
      //单选
      if (props.multiple) {
        const rightList = data.list.filter((n: any) => n.rightAnswerFlag)
        if (rightList.length === 1) {
          if (item.eleId === rightList[0].eleId) {
            message.error('最少需要一个正确答案')
            return
          }
        }
        item.rightAnswerFlag = isRight
        return
      }
      for (let i = 0; i < data.list.length; i++) {
        if (!props.multiple) data.list[i].rightAnswerFlag = false
        if (item.eleId === data.list[i].eleId) {
          data.list[i].rightAnswerFlag = true
        }
      }
    }
    // 删除答案
    const hanldeDelete = (item: any) => {
      const index = data.list.findIndex((n: any) => n.eleId == item.eleId)
      if (index > -1) {
        data.list.splice(index, 1)
      }
    }
    return () => (
      <div style={{ width: '100%' }}>
        <div ref={sortRef}>
          <Draggable v-model:modelValue={data.list} item-key="eleId">
            {{
              item: (value: any) => {
                const item = value.element
                const index = value.index + 1
                return (
                  <div>
                    <div class={styles.answerItem}>
                      {props.disabled ? null : (
                        <div class={styles.handle}>
                          <NIcon size="30" component={<Menu />} />
                        </div>
                      )}
                      <div data-draggable="handle" class={[styles.itemContent, 'handle']}>
                        <span style={{ width: '30px' }}>{index}.</span>
                        {['SORT'].includes(props.questionTypeCode) && (
                          <span style={{ width: '80px' }}>答案:</span>
                        )}
                        {['LINK'].includes(props.questionTypeCode) && (
                          <span style={{ width: '80px' }}>题目:</span>
                        )}
                        {props.optionType === 'TXT' && (
                          <NInput placeholder="请输入选项内容" v-model:value={item.text} />
                        )}
                        {props.optionType === 'IMAGE' && (
                          <UploadFile
                            accept="image/*"
                            v-model:fileList={item.img}
                            bucketName="question-bank"
                          />
                        )}
                        {props.optionType === 'AUDIO' && (
                          <NSpace style={{ width: '100%' }} wrap={false}>
                            <UploadFile
                              disabled={props.disabled}
                              listType="image"
                              accept=".mp3"
                              v-model:fileList={item.audio}
                              bucketName="question-bank"
                            />
                            {item.audio && <audio src={item.audio} controls></audio>}
                          </NSpace>
                        )}
                      </div>
                      {['SORT', 'LINK'].includes(props.questionTypeCode) && (
                        <div data-draggable="handle" class={[styles.itemContent, 'handle']}>
                          <span style={{ width: '80px' }}>答案:</span>
                          {props.questionTypeCode === 'SORT' ? (
                            <NInput
                              disabled
                              placeholder="请输入排序值"
                              readonly
                              v-model:value={item.sort}
                            />
                          ) : (
                            <>
                              {props.optionAnswerType === 'TXT' && (
                                <NInput placeholder="请输入选项内容" v-model:value={item.text1} />
                              )}
                              {props.optionAnswerType === 'IMAGE' && (
                                <UploadFile
                                  disabled={props.disabled}
                                  accept="image/*"
                                  v-model:fileList={item.img1}
                                  bucketName="question-bank"
                                />
                              )}
                            </>
                          )}
                        </div>
                      )}
                      <NSpace inline>
                        {['RADIO', 'CHECKBOX'].includes(props.questionTypeCode) && (
                          <>
                            <NButton
                              disabled={props.disabled}
                              color={item.rightAnswerFlag ? '#18a058' : '#adadad'}
                              onClick={() => handleChangeAnswer(item, true)}
                            >
                              正确答案
                            </NButton>
                            <NButton
                              disabled={props.disabled}
                              color={!item.rightAnswerFlag ? '#d03050' : '#adadad'}
                              onClick={() => handleChangeAnswer(item, false)}
                            >
                              错误答案
                            </NButton>
                          </>
                        )}
                        <NButton
                          disabled={props.disabled}
                          quaternary
                          circle
                          onClick={() => hanldeDelete(item)}
                        >
                          <NIcon component={<DeleteFilled />} />
                        </NButton>
                      </NSpace>
                    </div>
                    {item.errorText && <div style={{ color: 'red' }}>{item.errorText}</div>}
                  </div>
                )
              }
            }}
          </Draggable>
        </div>
        {props.disabled ? null : (
          <NButton
            block
            onClick={() => {
              data.list.push(createItem())
            }}
          >
            + 添加选项
          </NButton>
        )}
      </div>
    )
  }
})
