import OHeader from '@/components/o-header'
import OSticky from '@/components/o-sticky'
import { Button, Cell, CellGroup, Dialog, Icon, Image, showToast, Tab, Tabs, Tag } from 'vant'
import { defineComponent, onMounted, reactive, ref, nextTick } from 'vue'
import styles from './index.module.less'
import iconTimer from '../../images/icon-timer.png'
import iconTeacher from '@common/images/icon_teacher.png'
import { useRoute, useRouter } from 'vue-router'
import request from '@/helpers/request'
import dayjs from 'dayjs'
import { forms } from '../../create'
import { postMessage } from '@/helpers/native-message'

export default defineComponent({
  name: 'course-preview',
  setup() {
    // SAME_SCHOOL_TEACHER("同学校老师课程冲突"),
    // DIFF_SCHOOL_TEACHER("不同学校老师课程冲突"),
    // STUDENT("学生课程冲突"),
    // LEAVE 请假冲突
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      type: route.query.type,
      conflictStatus: false,
      conflictMessage: '该时间段伴学指导在其他学校有课',
      tabValue: '',
      courseValue: '',
      selectClasses: [] as any, // 选中的班级列表
      selectCourse: [] as any, // 选中的课程
      choiceCourse: {}, // 选中需要调整的课程
      isClick: false
    })
    const courseTabsRef: any = ref()

    // 获取所有
    const getClasses = async (loading = true) => {
      try {
        const { data } = await request.post('/api-school/orchestra/trainingPlanListCache', {
          requestType: 'form',
          hideLoading: !loading,
          data: {
            cacheId: route.query.cacheId
          }
        })
        // 初始化数据
        formatClasses(data)

        if (forms.planList.orchestra.length > 0) {
          const selectOrchestra = forms.selectOrchestraId
            ? { orchestraId: forms.selectOrchestraId }
            : forms.planList.orchestra[0]
          state.tabValue = selectOrchestra.orchestraId
          console.log(forms.selectClassGroupId, forms.planList.classes[selectOrchestra.orchestraId])
          const selectClasses = forms.selectClassGroupId
            ? { classGroupId: forms.selectClassGroupId }
            : forms.planList.classes[selectOrchestra.orchestraId]
            ? forms.planList.classes[selectOrchestra.orchestraId][0]
            : {}
          state.selectClasses = forms.planList.classes[selectOrchestra.orchestraId] || []
          state.selectCourse = forms.planList.course[selectClasses.classGroupId]

          state.courseValue = selectClasses.classGroupId

          console.log(selectClasses.classGroupId, 'selectClasses.classGroupId')

          // 判断是否有数据
          forms.selectOrchestraId = null
          forms.selectClassGroupId = null

          console.log(selectClasses.classGroupId, 'selectClasses.classGroupId 333333')
        }
      } catch {
        //
      }
    }

    // 格式化班级数据
    const formatClasses = async (data: any) => {
      // 判断是否有班级编号，如果有就说明接口只会返回该班的数据
      // if (forms.selectClassGroupId) {
      //   forms.planList.course[forms.selectClassGroupId] = data || []
      //   return
      // }

      // 初始化乐团
      const orchestra: any = []
      data.forEach((item: any) => {
        const index = orchestra.findIndex((o: any) => o.orchestraId === item.orchestraId)
        // 判断是否已经添加过
        if (index === -1) {
          orchestra.push({
            orchestraId: item.orchestraId,
            orchestraName: item.orchestraName
          })
        }
      })
      // 初始化班级
      const classes: any = {}
      orchestra.forEach((item: any) => {
        data.forEach((child: any) => {
          // 判断是否是同一个乐团
          if (item.orchestraId === child.orchestraId) {
            const classInOrchestra = classes[item.orchestraId]
            // // 判断是否已经存在乐团数据
            if (classInOrchestra) {
              const index = classInOrchestra.findIndex(
                (c: any) => c.classGroupId === child.classGroupId
              )
              if (index === -1) {
                classes[item.orchestraId].push({
                  classGroupId: child.classGroupId,
                  className: child.className
                })
              }
            } else {
              classes[item.orchestraId] = [
                {
                  classGroupId: child.classGroupId,
                  className: child.className
                }
              ]
            }
          }
        })
      })

      // 初始化课程数据
      const course: any = {}
      for (const item in classes) {
        const oList = classes[item] || []
        oList.forEach((child: any) => {
          const courseList = data.filter((d: any) => d.classGroupId === child.classGroupId)
          course[child.classGroupId] = courseList
        })
      }

      forms.planList = {
        orchestra,
        classes,
        course
      }
    }

    const onChoiceCourse = (course: any) => {
      forms.selectOrchestraId = state.tabValue || null
      forms.selectClassGroupId = state.courseValue || null
      router.push({
        path: '/course-adjust',
        query: {
          id: course.id,
          cacheId: route.query.cacheId
        }
      })
    }

    const onSubmit = async () => {
      try {
        state.isClick = true
        await request.post('/api-school/orchestra/trainingPlan/' + route.query.cacheId)
        setTimeout(() => {
          showToast(state.type === 'change' ? '调整成功' : '排课成功')
        }, 100)
        setTimeout(() => {
          state.isClick = false
          if (route.query.type === 'change') {
            router.replace('/companion-teacher')
          } else {
            postMessage({ api: 'back', content: {} })
          }
        }, 1100)
      } catch {
        //
        state.isClick = false
        getClasses(false)
        // setTimeout(() => {
        // }, 1100)
      }
    }

    onMounted(() => {
      getClasses()
    })
    return () => (
      <div class={styles.coursePreview}>
        <OSticky position="top">
          <OHeader border={false} />

          <Tabs
            lineWidth={20}
            lineHeight={4}
            v-model:active={state.tabValue}
            swipeThreshold={3}
            class={styles.orchestraTabs}
            onChange={(val: any) => {
              console.log(val, 'val', state.tabValue)
              // 乐团变化时
              if (!forms.selectClassGroupId) {
                state.selectClasses = forms.planList.classes[val] || []

                const selectClasses = forms.planList.classes[val]
                  ? forms.planList.classes[val][0]
                  : {}
                state.selectCourse = forms.planList.course[selectClasses.classGroupId]
                state.courseValue = selectClasses.classGroupId
              }
            }}
          >
            {forms.planList.orchestra.map((item: any) => (
              <Tab title={item.orchestraName} name={item.orchestraId}></Tab>
            ))}
          </Tabs>

          <div class={styles.courseTabsContainer}>
            {state.courseValue && (
              <Tabs
                swipeThreshold={3}
                class={styles.courseTabs}
                v-model:active={state.courseValue}
                lineHeight={0}
                shrink
                ref={courseTabsRef}
                onChange={(val: any) => {
                  state.selectCourse = forms.planList.course[val]
                }}
              >
                {state.selectClasses.map((item: any) => (
                  <Tab title={item.className} name={item.classGroupId}></Tab>
                ))}
              </Tabs>
            )}
          </div>
        </OSticky>

        {state.selectCourse.map((item: any) => (
          <CellGroup inset class={styles.cellGroup}>
            <Cell center class={styles.cellDatetime}>
              {{
                title: () => (
                  <div class={styles.cellDate}>
                    <Icon name={iconTimer} class={styles.iconTimer} />
                    {dayjs(item.classDate).format('YYYY-MM-DD')}
                  </div>
                ),
                value: () => <span class={styles.cellTime}>{item.singleCourseTime}分钟</span>
              }}
            </Cell>

            <div
              class={[
                styles.cellTimeRange,
                item.conflictType && item.conflictType.length > 0 && styles.conflictType
              ]}
            >
              {dayjs(item.startTime).format('HH:mm')}-{dayjs(item.endTime).format('HH:mm')}
            </div>
            <Cell center class={styles.cellTeacher} border={false}>
              {{
                icon: () => (
                  <Image src={item.teacherAvatar || iconTeacher} class={styles.img} fit="cover" />
                ),
                title: () => (
                  <div class={styles.teacherInfo}>
                    <p class={[styles.teacherName, 'van-ellipsis']}>{item.teacherName}</p>
                    <Tag type="primary">{item.className}</Tag>
                  </div>
                ),
                value: () => (
                  <Button
                    round
                    plain
                    type="primary"
                    class={styles.btn}
                    onClick={() => onChoiceCourse(item)}
                  >
                    调整
                  </Button>
                )
              }}
            </Cell>
            <Cell center border={false} class={[styles.cellTeacher, styles.conflictGrouop]}>
              {{
                title: () => (
                  <>
                    {item.conflictType && item.conflictType.includes('STUDENT') && (
                      <Tag
                        class={styles.conflict}
                        color="#F44541"
                        size="large"
                        onClick={() => {
                          state.conflictMessage = '学生时间冲突'
                          state.conflictStatus = true
                          state.choiceCourse = item
                        }}
                      >
                        学生冲突
                      </Tag>
                    )}
                    {item.conflictType && item.conflictType.includes('DIFF_SCHOOL_TEACHER') && (
                      <Tag
                        class={styles.conflict}
                        color="#F44541"
                        size="large"
                        onClick={() => {
                          state.conflictMessage = '该时间段伴学指导在其他学校有课'
                          state.conflictStatus = true
                          state.choiceCourse = item
                        }}
                      >
                        学校冲突
                      </Tag>
                    )}
                    {item.conflictType && item.conflictType.includes('SAME_SCHOOL_TEACHER') && (
                      <Tag
                        class={styles.conflict}
                        color="#ff8057"
                        size="large"
                        onClick={() => {
                          state.conflictMessage = '伴学指导在本学校时间有冲突'
                          state.conflictStatus = true
                          state.choiceCourse = item
                        }}
                      >
                        老师冲突
                      </Tag>
                    )}
                    {item.conflictType && item.conflictType.includes('LEAVE') && (
                      <Tag
                        class={styles.conflict}
                        color="#F44541"
                        size="large"
                        onClick={() => {
                          state.conflictMessage = '伴学指导请假冲突'
                          state.conflictStatus = true
                          state.choiceCourse = item
                        }}
                      >
                        请假冲突
                      </Tag>
                    )}
                  </>
                )
              }}
            </Cell>
          </CellGroup>
        ))}

        <OSticky position="bottom">
          <div class={'btnGroup'}>
            <Button round block type="primary" onClick={onSubmit} disabled={state.isClick}>
              {state.type === 'change' ? '确认调整' : '确认排课'}
            </Button>
          </div>
        </OSticky>

        <Dialog
          v-model:show={state.conflictStatus}
          message={state.conflictMessage}
          messageAlign="center"
          confirmButtonText="去调整"
          cancelButtonText="知道了"
          showCancelButton
          onConfirm={() => {
            state.conflictStatus = false
            onChoiceCourse(state.choiceCourse)
          }}
        >
          {{
            title: () => (
              <div class={styles.dialogTitle}>
                <i></i>
                课程冲突
              </div>
            )
          }}
        </Dialog>
      </div>
    )
  }
})
