import {
  FormInst,
  FormItemRule,
  FormRules,
  NAlert,
  NButton,
  NCascader,
  NForm,
  NFormItem,
  NIcon,
  NImage,
  NInput,
  NInputNumber,
  NModal,
  NRadioGroup,
  NSelect,
  NSpace,
  NSpin,
  NTabPane,
  NTabs,
  NTag,
  useMessage
} from 'naive-ui'
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  onUnmounted,
  PropType,
  reactive,
  ref
} from 'vue'
import {
  examinationKnowledgePointCategorySave,
  examinationKnowledgePointCategoryUpdate,
  examinationQuestionDetail,
  examinationQuestionSave,
  examinationQuestionUpdate
} from '../../api'
import TopicText from '../component/topicText'
import { questionTypeCode } from '../question-bank'
import styles from '../index.module.less'
import Editor from '@/components/editor'
import UploadFile from '@/components/upload-file'
import SelectMusicSheet from '@/views/educational-manage/model/selectMusicSheet'
import { useUserStore } from '@/store/modules/user'
import WangEditor from '@/components/WangEditor'
import { DeleteFilled } from '@vicons/antd'
import { lessonType } from '@/views/knowledge-manage/knowledgeTypeData'

const optionsType = [
  { label: '文本', value: 'TXT' },
  { label: '图片', value: 'IMAGE' },
  { label: '音频', value: 'AUDIO' }
  //   { label: '视频', value: 'video' }
]
interface IAnswers {
  /**附加答案内容 */
  questionExtra: string
  /**答案类型,可用值:TXT,IMAGE,AUDIO */
  questionAnswerTypeCode: 'TXT' | 'IMAGE' | 'AUDIO'
  /**答案类型,可用值:TXT,IMAGE,AUDIO */
  questionExtraTypeCode: 'TXT' | 'IMAGE' | 'AUDIO'
  /**答案内容 */
  questionAnswer: string
  /**答案解析 */
  answerAnalysis: string
  /**是否是正确答案 */
  rightAnswerFlag: boolean
}
interface ExaminationQuestionAdd {
  id?: string
  /**考点名称 */
  name: string
  /**题目类型 */
  questionTypeCode: string
  /**问题明细 */
  questionDetail: string | null
  /**问题的扩展信息 */
  questionExtendsInfo: string | null
  /**多媒体链接,多个,隔开 */
  mediaUrls: string | null
  /**总分 */
  totalScore: number | null
  /**考点 */
  examinationKnowledgePointCategoryId: number | null
  /**难度系数,可用值:ONE,TWO,THREE */
  difficultyCoefficient: string | null
  courseTypeCode: string | null
  /**答案 */
  answers: IAnswers[]
  answerAnalysis: string | null
}

const apiUrls = {
  dev: 'https://dev.kt.colexiu.com',
  test: 'https://test.kt.colexiu.com',
  online: 'https://mec.colexiu.com'
}

const environment = location.origin.includes('//dev')
  ? 'dev'
  : location.origin.includes('//test')
  ? 'test'
  : location.origin.includes('//mec.colexiu')
  ? 'online'
  : 'dev'
const apiUrl = apiUrls[environment]

export default defineComponent({
  name: 'addQuestionBank',
  emits: ['handleSuccess', 'close'],
  props: {
    item: {
      type: Object,
      default: () => {}
    },
    categorys: {
      type: Object,
      default: () => {}
    }
  },
  setup(props, { emit }) {
    const message = useMessage()
    const loading = ref(false)
    const formRef = ref<FormInst | null>(null)
    const uploadFileRef = ref()
    const questions = Object.entries(questionTypeCode).map(([value, label]) => ({ label, value }))
    const userStore = useUserStore()
    // console.log('🚀 ~ questions', questions)
    const saveLoading = ref(false)
    const saveModel = reactive<ExaminationQuestionAdd>({
      id: null as any,
      name: '', //
      questionTypeCode: props?.item?.questionTypeCode || 'RADIO', //题目类型
      questionDetail: '', // 问题明细
      questionExtendsInfo: '', //问题的扩展信息
      mediaUrls: props?.item?.mediaUrls || '', // 多媒体链接,多个,隔开
      totalScore: null, //总分
      examinationKnowledgePointCategoryId: null, //考点
      difficultyCoefficient: 'ONE', //难度系数,可用值:ONE,TWO,THREE
      courseTypeCode: null,
      answerAnalysis: null,
      answers: [] as any
    })
    const imageList = ref<any[]>([])
    const handleInit = async () => {
      if (!props.item?.id) return
      loading.value = true
      try {
        const res: any = await examinationQuestionDetail(props.item.id)
        if (res?.data) {
          console.log(res.data, 'res.data')
          for (let key in saveModel) {
            ;(saveModel as any)[key] = res.data[key] || ''
          }
          if (saveModel.questionTypeCode == 'PLAY') {
            try {
              const _palyData = JSON.parse(saveModel.questionExtendsInfo as any)
              playData.difficulty = _palyData.difficulty
              playData.start = _palyData.start
              playData.end = _palyData.end
              playData.score = _palyData.score
              playData.musicSheetId = _palyData.musicSheetId
              playData.musicName = _palyData.musicName
              // const prefix = /(localhost|192)/.test(location.host)
              //   ? 'https://ponline.colexiu.com'
              //   : location.origin
              // musicSheetSrc.value =
              //   prefix +
              //   `/orchestra-music-score/?_t=${Date.now()}&id=${
              //     _palyData.musicSheetId
              //   }&modelType=practice&Authorization=${userStore.getToken}`

              const prefix = /(localhost)/.test(location.host)
                ? 'https://test.kt.colexiu.com'
                : apiUrl
              musicSheetSrc.value =
                prefix +
                `/instrument/?_t=${Date.now()}&id=${
                  _palyData.musicSheetId
                }&modelType=practise&modeType=json&Authorization=${
                  userStore.getToken
                }&isCbs=true&zoom=0.8`
            } catch (error) {}
          }
          if (saveModel.mediaUrls) {
            imageList.value = saveModel.mediaUrls?.split(',').filter(Boolean)
          }
          if (saveModel?.answers && saveModel.answers?.[0]) {
            optionType.value = saveModel.answers[0].questionAnswerTypeCode as any
            if (saveModel.questionTypeCode === 'LINK') {
              optionAnswerType.value =
                saveModel.answers[0].questionExtraTypeCode ||
                ((saveModel.answers[0]?.questionExtra?.includes('http') ? 'IMAGE' : 'TXT') as any)
            }
          }
        }
      } catch (error) {}
      nextTick(() => {
        loading.value = false
      })
    }
    const sendMusic = (event: MessageEvent) => {
      /** 云教练选段 */
      // console.log(event.data)
      const data = event.data
      if (data.api === 'admin-selectMusicMeasure') {
        playData.start = playData.start && !data.change ? playData.start : data.start + ''
        playData.end = playData.end && !data.change ? playData.end : data.end + ''
      }
    }
    onMounted(() => {
      handleInit()
      window.addEventListener('message', sendMusic)
    })
    onUnmounted(() => {
      window.removeEventListener('message', sendMusic)
    })
    const playData = reactive({
      musicName: '',
      musicSheetId: '',
      start: '',
      end: '',
      score: null,
      difficulty: '1'
    })
    const musicSheetSrc = ref('')
    const optionType = ref<'TXT' | 'IMAGE' | 'AUDIO'>('TXT')
    const optionAnswerType = ref<'TXT' | 'IMAGE' | 'AUDIO'>('TXT')
    function validateScore(rule: any, value: any) {
      if (value === null) {
        return new Error('请输入分数')
      }
      return true
    }
    const rules: FormRules = {
      name: [{ required: true, message: '请填写题目名称', trigger: ['blur', 'change'] }],
      examinationKnowledgePointCategoryId: [
        { required: true, message: '请选择考点', trigger: ['blur', 'change'] }
      ],
      totalScore: [{ validator: validateScore, trigger: ['blur', 'change'] }],
      // questionDetail: [{ required: true, message: '请输入题干', trigger: ['blur', 'change'] }],
      answerAnalysis: [{ required: true, message: '请输入答案解析', trigger: ['blur', 'change'] }]
    }
    const submit = () => {
      formRef.value?.validate(async (err) => {
        if (!err) {
          // 演奏题, 配置
          if (saveModel.questionTypeCode === 'PLAY') {
            if (!playData.musicSheetId || !playData.score) {
              message.error('请配置曲谱测验内容!')
              return
            }
            saveModel.mediaUrls = playData.musicSheetId
            saveModel.questionExtendsInfo = JSON.stringify(playData)
          } else {
            // 其它类型题,需要验证答案是否有内容
            if (!saveModel.answers.length) {
              message.error('请配置答案!')
              return
            }
            for (let i = 0; i < saveModel.answers.length; i++) {
              if (!saveModel.answers[i].questionAnswer) {
                message.error('请配置答案内容!')
                return
              }
              if (
                ['SORT', 'LINK'].includes(saveModel.questionTypeCode) &&
                !saveModel.answers[i].questionExtra
              ) {
                message.error('请配置答案内容!')
                return
              }
              // 排序题,和连线题答案都是正确的
              if (['SORT', 'LINK'].includes(saveModel.questionTypeCode)) {
                saveModel.answers[i].rightAnswerFlag = true
              }
            }
          }
          if (['RADIO', 'CHECKBOX'].includes(saveModel.questionTypeCode)) {
            const hasAnwer = saveModel.answers.filter((n: any) => n.rightAnswerFlag)
            if (hasAnwer.length < 1) {
              message.error('最少需要一个正确答案!')
              return
            }
          }
          const params: any = {
            ...saveModel
          }
          let res: any = null
          console.log(params)
          saveLoading.value = true
          if (saveModel.id) {
            res = await examinationQuestionUpdate(params)
          } else {
            res = await examinationQuestionSave(params)
          }
          if (res?.code == 200) {
            message.success('保存成功')
            emit('handleSuccess')
          } else {
            message.warning('保存失败')
          }
          saveLoading.value = false
        }
      })
    }

    // 获取选项类型
    const getOptionTypes = computed(() => {
      let typeList = ['TXT', 'IMAGE', 'AUDIO']
      if (['SORT', 'LINK'].includes(saveModel.questionTypeCode)) {
        optionType.value = 'TXT'
        typeList = ['TXT', 'IMAGE']
        return optionsType.filter((n: any) => typeList.includes(n.value))
      }
      console.log(optionsType, typeList)
      return optionsType.filter((n: any) => typeList.includes(n.value))
    })

    const modalData = reactive({
      open: false
    })
    return () => (
      <div>
        <NSpin show={loading.value}>
          <NAlert style={{ marginBottom: '10px' }} showIcon={false} type="info" title="题目信息" />
          <NForm
            disabled={props.item?.isLock ? true : false}
            ref={formRef}
            onSubmit={submit}
            labelPlacement="top"
            model={saveModel}
            rules={rules}
            require-mark-placement="left"
          >
            <NFormItem label="题目名称" path="name" required>
              <NInput placeholder="请输入题目名称" v-model:value={saveModel.name} />
            </NFormItem>
            <NFormItem label="题目类型" path="questionTypeCode" required>
              <NSpace>
                {questions.map((n: any) => (
                  <NButton
                    disabled={props.item?.isLock ? true : false}
                    color={saveModel.questionTypeCode == n.value ? '#2d8cf0' : '#adadad'}
                    onClick={() => (saveModel.questionTypeCode = n.value)}
                  >
                    {n.label}
                  </NButton>
                ))}
              </NSpace>
            </NFormItem>
            <NSpace justify="space-around" itemStyle={{ flex: 1 }}>
              <NFormItem label="考点" path="examinationKnowledgePointCategoryId" required>
                <NCascader
                  placeholder="请选择考点"
                  v-model:value={saveModel.examinationKnowledgePointCategoryId}
                  options={props.categorys as any}
                  checkStrategy="child"
                  childrenField="children"
                  expandTrigger="hover"
                  valueField="categoryId"
                  labelField="name"
                  clearable
                />
              </NFormItem>
              <NFormItem label="难度" path="difficultyCoefficient" required>
                <NSelect
                  placeholder="请选择难度"
                  clearable
                  v-model:value={saveModel.difficultyCoefficient}
                  options={[
                    { label: '初级', value: 'ONE' },
                    { label: '中级', value: 'TWO' },
                    { label: '高级', value: 'THREE' }
                  ]}
                />
              </NFormItem>
              <NFormItem label="分值" path="totalScore" required>
                <NInputNumber
                  placeholder="请输入分值"
                  min={0}
                  max={100}
                  v-model:value={saveModel.totalScore}
                  clearable
                />
              </NFormItem>
              {/* <NFormItem path="courseTypeCode" label="课程类型">
                <NSelect
                  placeholder="请选择课程类型"
                  clearable
                  v-model:value={saveModel.courseTypeCode}
                  options={lessonType}
                />
              </NFormItem> */}
            </NSpace>

            <NAlert
              style={{ marginBottom: '10px' }}
              showIcon={false}
              type="info"
              title="题目详情"
            />

            {/* <NFormItem label="题干" path="questionDetail">
              {!loading.value && (
                <WangEditor
                  bucketName="question-bank"
                  html={saveModel.questionDetail || ''}
                  onChange={(_html: string) => {
                    saveModel.questionDetail = _html
                  }}
                />
              )}
            </NFormItem> */}
            {saveModel.questionTypeCode === 'PLAY' ? (
              <>
                <NSpace itemStyle={{ flex: 1 }}>
                  <NFormItem label="测验曲目" required>
                    <NButton onClick={() => (modalData.open = true)}>选择曲谱</NButton>
                  </NFormItem>
                  <NFormItem label="练习小节">
                    <NInput placeholder="开始小节" v-model:value={playData.start}></NInput>-
                    <NInput placeholder="结束小节" v-model:value={playData.end}></NInput>
                  </NFormItem>
                  <NFormItem label="测验难度" required>
                    <NSelect
                      v-model:value={playData.difficulty}
                      options={[
                        { label: '普通级', value: '1' },
                        { label: '进阶级', value: '2' },
                        { label: '大师级', value: '3' }
                      ]}
                    >
                      选择曲谱
                    </NSelect>
                  </NFormItem>
                </NSpace>
                <NFormItem label="合格分数" required>
                  <NInputNumber min={0} max={100} v-model:value={playData.score}></NInputNumber>分
                </NFormItem>
                <NFormItem label="曲谱">
                  {musicSheetSrc.value && (
                    <iframe
                      style={{ maxWidth: '663px', margin: 'auto' }}
                      width={'100%'}
                      height={'375px'}
                      frameborder="0"
                      src={musicSheetSrc.value}
                    ></iframe>
                  )}
                </NFormItem>
              </>
            ) : (
              <>
                <NFormItem label="上传题库(图片或音频)">
                  <NSpace vertical style={{ width: '100%' }}>
                    <NSpace>
                      {saveModel.mediaUrls?.split(',').map((n: any) => {
                        if (!n) return ''
                        const isAudio = n?.includes('.mp3')
                        return (
                          <>
                            {isAudio && (
                              <NSpace align="center">
                                <audio
                                  style={{ width: '300px', height: '38px' }}
                                  src={n}
                                  controls
                                ></audio>
                                <NButton
                                  quaternary
                                  circle
                                  onClick={() => {
                                    imageList.value = []
                                    saveModel.mediaUrls = ''
                                  }}
                                >
                                  <NIcon component={<DeleteFilled />} />
                                </NButton>
                              </NSpace>
                            )}
                          </>
                        )
                      })}
                    </NSpace>
                    {!loading.value && (
                      <UploadFile
                        accept="image/*,.mp3"
                        disabled={props.item?.isLock ? true : false}
                        style={{ width: '100%' }}
                        ref={uploadFileRef}
                        imageList={imageList.value}
                        bucketName={'question-bank'}
                        onUpdate:fileList={(val: string) => {
                          saveModel.mediaUrls = [saveModel.mediaUrls, val].filter(Boolean).join(',')
                          imageList.value = saveModel.mediaUrls?.split(',').filter(Boolean)
                        }}
                        onRemove={() => {
                          imageList.value = []
                          saveModel.mediaUrls = ''
                        }}
                      />
                    )}
                  </NSpace>
                </NFormItem>
                <NSpace itemStyle={{ flex: 1 }}>
                  <NFormItem label="选项类型" required>
                    <NSpace>
                      {getOptionTypes.value.map((n: any) => (
                        <NButton
                          disabled={props.item?.isLock ? true : false}
                          color={optionType.value == n.value ? '#2d8cf0' : '#adadad'}
                          onClick={() => {
                            optionType.value = n.value
                          }}
                        >
                          {n.label}
                        </NButton>
                      ))}
                    </NSpace>
                  </NFormItem>
                  {saveModel.questionTypeCode === 'LINK' ? (
                    <NFormItem label="答案类型" required>
                      <NSpace>
                        {getOptionTypes.value.map((n: any) => (
                          <NButton
                            disabled={props.item?.isLock ? true : false}
                            color={optionAnswerType.value == n.value ? '#2d8cf0' : '#adadad'}
                            onClick={() => {
                              optionAnswerType.value = n.value
                            }}
                          >
                            {n.label}
                          </NButton>
                        ))}
                      </NSpace>
                    </NFormItem>
                  ) : null}
                </NSpace>
                <NFormItem label="题目选项" path="answers" required>
                  {!loading.value && (
                    <TopicText
                      disabled={props.item?.isLock ? true : false}
                      answers={saveModel.answers}
                      multiple={['CHECKBOX'].includes(saveModel.questionTypeCode)}
                      optionType={optionType.value}
                      optionAnswerType={optionAnswerType.value}
                      questionTypeCode={saveModel.questionTypeCode}
                      onUpdate={(answers: any) => {
                        saveModel.answers = answers.map((an: any) => {
                          return {
                            ...an,
                            questionAnswerTypeCode: optionType.value
                          }
                        })
                      }}
                    />
                  )}
                </NFormItem>
              </>
            )}

            <NFormItem label="答案解析" path="answerAnalysis">
              <NInput type="textarea" rows={3} showCount v-model:value={saveModel.answerAnalysis} />
            </NFormItem>

            <NSpace justify="end">
              <NButton onClick={() => emit('close')}>取消</NButton>
              {props.item?.isLock ? null : (
                <NButton type="primary" onClick={submit} loading={saveLoading.value}>
                  保存
                </NButton>
              )}
            </NSpace>
          </NForm>
        </NSpin>
        <NModal
          preset="dialog"
          showIcon={false}
          title="选择曲谱"
          v-model:show={modalData.open}
          style={{ width: '80vw' }}
        >
          <div>
            <SelectMusicSheet
              onSelect={(row: any) => {
                playData.musicSheetId = row.id
                playData.musicName = row.name
                modalData.open = false
                // const prefix = /(localhost|192)/.test(location.host)
                //   ? 'https://ponline.colexiu.com'
                //   : location.origin
                // musicSheetSrc.value =
                //   prefix +
                //   `/orchestra-music-score/?_t=${Date.now()}&id=${
                //     row.id
                //   }&modelType=practice&Authorization=${userStore.getToken}`

                const prefix = /(localhost|192)/.test(location.host)
                  ? 'https://test.kt.colexiu.com'
                  : apiUrl
                musicSheetSrc.value =
                  prefix +
                  `/instrument/?_t=${Date.now()}&id=${
                    row.id
                  }&modelType=practise&modeType=json&Authorization=${
                    userStore.getToken
                  }&isCbs=true&zoom=0.8`
              }}
            />
          </div>
        </NModal>
      </div>
    )
  }
})
