import request from '@/helpers/request'
import { state } from '@/state'
import {
  Button,
  Dialog,
  Empty,
  Field,
  Grid,
  GridItem,
  Icon,
  showConfirmDialog,
  showToast,
  Tab,
  Tabs
} from 'vant'
import OSticky from '@/components/o-sticky'
import { defineComponent, onMounted, reactive, onUnmounted, ref } from 'vue'
import iconEdit from '@/views/unit-test/images/icon-edit.png'
import styles from './uni-last.module.less'
import { useRoute, useRouter } from 'vue-router'
import NewspaperItem from './modals/newspaper-item'
import questIcon from '@/school/images/quest-icon.png'
import { postMessage } from '@/helpers/native-message'
// import { browser } from '@/helpers/utils'
export default defineComponent({
  name: 'uni-test',
  setup() {
    const route = useRoute()
    const router = useRouter()
    // const browserInfo = browser()
    const activeName = ref('one')
    // const catchList = store
    const forms = ref({} as any)
    const datas = reactive({
      loading: true,
      list: [] as any,
      uniDetail: {} as any
    })
    const showTip = ref(false)
    // const getList = async () => {
    //   data.loading = true
    //   try {
    //     const res: any = await request.post(
    //       state.platformApi + '/courseSchedule/queryUnitExamination',
    //       {
    //         requestType: 'form',
    //         data: {
    //           lessonCoursewareId: route.query.lessonCoursewareId,
    //           classGroupId: forms.value.classGroupId
    //         }
    //       }
    //     )
    //     //      classGroupId: forms.value.classGroupId
    //     data.list = res.data || []
    //   } catch (error) {}

    //   data.loading = false
    // }

    const getClassDetail = async () => {
      try {
        const { data } = await request.get(
          state.platformApi + `/classGroup/detail/${forms.value.classGroupId}`
        )
        forms.value.preStudentNum = data.preStudentNum || 0
      } catch (e) {
        console.log(e)
      }
    }

    // 获取详情
    const getCourseLessonDetail = async () => {
      try {
        //   const query = route.query
        // // api-teacher/lessonCoursewareExaminationMapper/detailByCourseId
        // // 判断是从课程结束后，还是正常创建
        const { data } = await request.post(
          state.platformApi + `/lessonCoursewareExaminationMapper/detailByCourseId`,
          {
            requestType: 'form',
            data: {
              courseScheduleId: route.query.courseScheduleId
            }
          }
        )

        forms.value.classGroupId = data.classGroupId
        forms.value.classGroupName = data.classGroupName
        forms.value.testName = data.lessonCoursewareExaminationMapperName
        forms.value.orchestraName = data.orchestraName
        forms.value.coursewareName = data.lessonCoursewareName
        forms.value.lessonCoursewareId = data.lessonCoursewareExaminationMapper.lessonCoursewareId
        forms.value.preStudentNum = data.studentNum || 0
        forms.value.testId = data.lessonCoursewareExaminationMapper.id

        const details = data.lessonCoursewareExaminationMapper.details || []
        details.forEach((item: any) => {
          datas.uniDetail[item.level] = item
        })

        console.log(forms.value, 'forms')
      } catch (e) {
        console.log(e)
      }
    }

    onMounted(() => {
      forms.value = { ...JSON.parse(sessionStorage.getItem('unit-create') || '{}') } as any
      console.log(forms.value)
      const query = route.query
      // api-teacher/lessonCoursewareExaminationMapper/detailByCourseId
      // 判断是从课程结束后，还是正常创建
      if (query.courseScheduleId) {
        getCourseLessonDetail()
      } else {
        if (!forms.value.classGroupId) {
          showToast('请选择班级')
          return
        }
        getClassDetail()
        getStudentUni()
      }
    })
    const getStudentUni = async () => {
      try {
        const res = await request.post(
          state.platformApi + `/lessonCoursewareExaminationMapper/detail`,
          {
            requestType: 'form',
            data: {
              lessonCoursewareExaminationMapperId: forms.value.testId
            }
          }
        )
        res.data.details.forEach((item: any) => {
          datas.uniDetail[item.level] = item
        })
      } catch (e) {
        console.log(e)
      }
    }
    const onSubmit = async () => {
      if (!forms.value.expiryDate) {
        showToast('请输入截止时间')
        return
      }
      try {
        await request.post(
          state.platformApi + `/classGroupUnitExamination/publishUnitExamination`,
          {
            data: {
              classGroupId: forms.value.classGroupId,
              lessonCoursewareExaminationMapperId: forms.value.testId,
              unitExaminationName: `${forms.value?.coursewareName}-${forms.value?.testName}`,
              expiryDate: forms.value.expiryDate
            }
          }
        )
        showToast('创建成功')
        sessionStorage.removeItem('unit-create')
        // 如果连接上面有班级编号，说明当前页面是从原生来的
        if (route.query.classGroupId) {
          postMessage({ api: 'back' })
        } else {
          router.replace('/unit-list')
        }
      } catch (e) {
        console.log(e)
      }
    }
    return () => (
      <>
        <div class={styles.lastWrap}>
          <h4 class={styles.uniTitle}>
            <Icon name={iconEdit} class={styles.editIcon}></Icon>
            {forms.value?.coursewareName}-{forms.value?.testName}
          </h4>
          <div class={styles.infoWrap}>
            <p>乐团：{forms.value?.orchestraName}</p>
            <p>班级：{forms.value?.classGroupName}</p>
            <p>学生人数：{forms.value?.preStudentNum}人</p>
            <Field
              v-model={forms.value.expiryDate}
              type="number"
              placeholder="请输入截止日期"
              input-align="right"
            >
              {{
                extra: () => (
                  <div class={styles.loctionIconWrap}>
                    <span style={{ color: '#777' }}> 天后截止</span>
                    {/* <Image width={19} height={18} src={locIcon}></Image> */}
                  </div>
                ),
                label: () => <span class={styles.addP}>截止时间</span>
              }}
            </Field>
          </div>
          <div class={styles.tabsWrap}>
            <Icon
              class={styles.tabsWrapIcon}
              name={questIcon}
              size={18}
              color="#333"
              onClick={() => {
                showTip.value = true
              }}
            />
            <Tabs
              v-model:active={activeName.value}
              class={styles.rankTabs}
              background={'#F8F8F8'}
              title-active-color={'#333333'}
              title-inactive-color={'#777'}
              color={'#FF8057'}
              shrink
            >
              <Tab name="one" title="I类学生">
                <NewspaperItem item={datas.uniDetail[1]}></NewspaperItem>
              </Tab>
              <Tab name="two" title="II类学生">
                <NewspaperItem item={datas.uniDetail[2]}></NewspaperItem>
              </Tab>
              <Tab name="three" title="III类学生">
                <NewspaperItem item={datas.uniDetail[3]}></NewspaperItem>
              </Tab>
            </Tabs>
          </div>
          <OSticky position="bottom">
            <div class={'btnGroup'}>
              <Button block round type="primary" onClick={onSubmit}>
                创建完成
              </Button>
            </div>
          </OSticky>
          <Dialog
            class="exercisDetailDialog"
            v-model:show={showTip.value}
            title="提示框"
            confirmButtonText="我知道了"
            v-slots={{
              title: () => (
                <div class={styles.DialogTitle}>
                  <span></span>
                  <p>学生分类</p>
                </div>
              ),
              default: () => (
                <div class={styles.DialogConent}>
                  <p>
                    根据学生入团的批次对不同训练阶段的学生进行分类，不同训练阶段的学生可布置不同标准的课后训练和单元测验内容。
                  </p>
                  <br />
                  <p>&nbsp;&nbsp;&nbsp;I类学生：最新进入本乐团的学员</p>
                  <p>&nbsp;II 类学生：较早进入本乐团的学员</p>
                  <p>III 类学生：最早进入本乐团的学员</p>
                </div>
              )
            }}
          ></Dialog>
        </div>
      </>
    )
  }
})
