import { computed, defineComponent, onMounted, reactive, watch } from 'vue'
import styles from './index.module.less'
import { Button, CellGroup, Col, Dialog, Field, Icon, Popup, Row, showToast, Stepper } from 'vant'
import iconMenu from '../image/icon-menu.png'
import iconDelte from '../image/icon-delete.png'
import iconEdit from '../image/icon-edit.png'
import request from '@/helpers/request'
import { useRoute, useRouter } from 'vue-router'
import OHeader from '@/components/o-header'
import { unitData } from './data'

//题目类型
export const questionTypeCode: { [_: string]: any } = {
  RADIO: '单选题',
  CHECKBOX: '多选题',
  PLAY: '演奏题',
  SORT: '排序题',
  LINK: '连连看'
}
//难度
// { label: '普通级', value: '1' },
//                   { label: '进阶级', value: '2' },
//                   { label: '大师级', value: '3' }
// ONE('初级'), TWO('中级'), THREE('高级')
export const difficultyCoefficients: any = [
  { label: '普通级', value: '1' },
  { label: '进阶级', value: '2' },
  { label: '大师级', value: '3' }
]

export default defineComponent({
  name: 'unit-edit-test',
  setup() {
    const router = useRouter()
    const route = useRoute()

    const state = reactive({
      unitExaminationName: route.query.unitExaminationName,
      questionList: [] as any, // 系统自带题目
      level: route.query.level ? Number(route.query.level) : (null as any),
      dialogShow: false,
      activeRow: {} as any,
      settingStatus: false,
      pScore: null,
      pTime: null
    })

    const wTotalScore = computed(() => {
      const sQuestionList = state.questionList
      const aQuestionList = unitData['level' + state.level]?.questionList || []
      let countScore = 0
      sQuestionList.forEach((s: any) => {
        countScore += Number(s.question.totalScore) || 0
      })

      aQuestionList.forEach((s: any) => {
        countScore += Number(s.question.totalScore) || 0
      })
      unitData['level' + state.level].totalScore = countScore
      return countScore
    })

    const wQuestionNum = computed(() => {
      const sQuestionList = state.questionList
      const aQuestionList = unitData['level' + state.level]?.questionList || []
      unitData['level' + state.level].questionNum = sQuestionList.length + aQuestionList.length
      return sQuestionList.length + aQuestionList.length
    })

    // 初始化数据
    const __init = () => {
      const query = route.query
      // if (unitData['level' + state.level]?.questionList.length <= 0) {
      unitData['level' + state.level].totalScore = query.totalScore
      unitData['level' + state.level].questionNum = query.questionNum

      if (unitData['level' + state.level].passScore <= 0) {
        unitData['level' + state.level].passScore = query.passScore
      }
      if (unitData['level' + state.level].timeMinutes <= 0) {
        unitData['level' + state.level].timeMinutes = query.timeMinutes
      }
      unitData['level' + state.level].level = query.level
      // }
    }

    const getDetail = async () => {
      try {
        const { data } = await request.get(
          '/api-teacher/unitExaminationDetail/detail/' + route.query.unitExaminationId
        )
        state.questionList = data || []
      } catch {
        //
      }
    }

    const onDelete = (row: any) => {
      state.activeRow = row
      state.dialogShow = true
    }

    const onEdit = (row: any) => {
      router.push({
        path: '/add-unit-item',
        query: {
          level: state.level,
          musicId: row.question.mediaUrls
        }
      })
    }

    onMounted(() => {
      __init()
      getDetail()
    })
    return () => (
      <div class={styles.unitTest}>
        <OHeader />
        <div class={styles.itemWrap}>
          <div class={styles.uniTimeWrap}>
            <div class={styles.uniTimeWrapLeft}>
              <Icon name={iconMenu} class={styles.clockIcon}></Icon> {state.unitExaminationName}
            </div>

            <Button
              plain
              round
              class={styles.editBtn}
              onClick={() => {
                state.settingStatus = true
                state.pScore = unitData['level' + state.level]?.passScore
                state.pTime = unitData['level' + state.level]?.timeMinutes
              }}
            >
              修改
            </Button>
          </div>
          <div class={styles.itemBottom}>
            <div class={[styles.itemBottomDot, 'gridBorderRight']}>
              <p class={styles.dotMain} style={{ color: '#999999' }}>
                {wTotalScore.value || 0}
              </p>
              <p class={styles.dotSub}> 总分</p>
            </div>
            <div class={[styles.itemBottomDot, 'gridBorderRight']}>
              <p class={styles.dotMain} style={{ color: '#999999' }}>
                {wQuestionNum.value || 0}
              </p>
              <p class={styles.dotSub}>题目数 </p>
            </div>
            <div class={[styles.itemBottomDot, 'gridBorderRight']}>
              <p class={styles.dotMain}>{unitData['level' + state.level]?.passScore || 0}</p>
              <p class={styles.dotSub}>合格分 </p>
            </div>
            <div class={styles.itemBottomDot}>
              <p class={styles.dotMain}>{unitData['level' + state.level]?.timeMinutes || 0}</p>
              <p class={styles.dotSub}>测验时长/min </p>
            </div>
          </div>
        </div>

        <div class={styles.tableSection}>
          <Row class={[styles.title, 'van-hairline--bottom']}>
            <Col span={10}>题目名称</Col>
            <Col span={6}>题目类型</Col>
            <Col span={4}>分值</Col>
            <Col span={4}>操作</Col>
          </Row>
          {state.questionList.map((q: any) => (
            <Row class={[styles.content, 'van-hairline--bottom']}>
              <Col span={10} class="van-ellipsis">
                {q.question.name}
              </Col>
              <Col span={6}>{questionTypeCode[q.question.questionTypeCode]}</Col>
              <Col span={4}>{q.question.totalScore}</Col>
              <Col span={4}>--</Col>
            </Row>
          ))}
          {/* 新添加的曲目 */}
          {unitData['level' + state.level]?.questionList.map((q: any, index: number) => (
            <Row class={[styles.content, 'van-hairline--bottom']}>
              <Col span={10} class="van-ellipsis">
                {q.question.name}
              </Col>
              <Col span={6}>{questionTypeCode[q.question.questionTypeCode]}</Col>
              <Col span={4}>{q.question.totalScore}</Col>
              <Col span={4}>
                <div class={styles.btnGroup}>
                  <Icon name={iconEdit} class={styles.icon} onClick={() => onEdit(q)} />
                  <Icon
                    name={iconDelte}
                    class={styles.icon}
                    onClick={() => onDelete({ ...q, index })}
                  />
                </div>
              </Col>
            </Row>
          ))}

          <Button
            round
            class={styles.addBtn}
            onClick={() => {
              router.push('/add-unit-item?level=' + state.level)
            }}
          >
            <Icon name="plus" />
            添加测验曲目
          </Button>
        </div>

        <Dialog
          v-model:show={state.dialogShow}
          showCancelButton
          message={`请确认是否删除《${state.activeRow?.question?.name}》？`}
          messageAlign="left"
          confirmButtonText="删除"
          onConfirm={() => {
            unitData['level' + state.level]?.questionList.splice(state.activeRow.index, 1)
          }}
        >
          {{ title: () => <div class={styles.dialogDelete}>删除题目</div> }}
        </Dialog>

        <Popup
          position="bottom"
          round
          v-model:show={state.settingStatus}
          closeable
          class={styles.settingStatus}
        >
          <div class={styles.partContainer}>
            <div class={styles.partTitle}>修改</div>
            <CellGroup class={styles.cellGroup} border={false}>
              <Field
                inputAlign="right"
                label="合格分"
                type="number"
                autocomplete="off"
                maxlength={3}
                class={styles.inputControl}
                v-model={state.pScore}
                center
              >
                {{
                  input: () => (
                    <Stepper
                      v-model={state.pScore}
                      max={wTotalScore.value}
                      showMinus={false}
                      showPlus={false}
                    ></Stepper>
                  ),
                  extra: () => (
                    <div class={styles.loctionIconWrap}>
                      <span>
                        分<i style={{ color: '#fff' }}>钟</i>
                      </span>
                    </div>
                  )
                }}
              </Field>
              <Field
                inputAlign="right"
                label="测验时长"
                type="number"
                maxlength={3}
                autocomplete="off"
                class={styles.inputControl}
                center
              >
                {{
                  input: () => (
                    <Stepper v-model={state.pTime} showMinus={false} showPlus={false}></Stepper>
                  ),
                  extra: () => (
                    <div class={styles.loctionIconWrap}>
                      <span> 分钟</span>
                    </div>
                  )
                }}
              </Field>
            </CellGroup>
            <Button
              round
              block
              type="primary"
              class={styles.partBtn}
              onClick={() => {
                if (!state.pScore) return showToast('请输入合格分')
                if (!state.pTime) return showToast('请输入测试时长')

                unitData['level' + state.level].passScore = state.pScore
                unitData['level' + state.level].timeMinutes = state.pTime

                state.settingStatus = false
              }}
            >
              确认
            </Button>
          </div>
        </Popup>
      </div>
    )
  }
})
