import OHeader from '@/components/o-header'
import OPopup from '@/components/o-popup'
import OSticky from '@/components/o-sticky'
import request from '@/helpers/request'
import { Button, Cell, CellGroup, Field, showToast } from 'vant'
import { defineComponent, onMounted } from 'vue'
import styles from '../index.module.less'
import { state as baseState } from '@/state'
import StudentList from '../modal/student-list'
import SubjectList from '../modal/subject-list'
import { createState as state, resestState } from './create'
import { useRouter } from 'vue-router'
import deepClone from '@/helpers/deep-clone'

export default defineComponent({
  name: 'create-orchestra',
  setup() {
    const router = useRouter()
    // const state = reactive({
    //   subjectStatus: false,
    //   subjectList: [] as any, // 声部列表
    //   selectSubjectIds: [] as any,
    //   selectSubjects: [] as any, // 选中的声部
    //   studentStatus: false,
    //   teacherStatus: false,
    //   orchestraList: [] as any, // 乐团列表
    //   selectSubjectStudents: {} as any
    // })
    // 获取声部
    const getSubjects = async () => {
      try {
        const { data } = await request.post('/api-school/subjectBasicConfig/page', {
          data: {
            page: 1,
            rows: 50
          }
        })
        state.subjectList = data.rows || []
      } catch {
        //
      }
    }

    // 获取乐团列表
    const getOrchestras = async () => {
      try {
        const { data } = await request.post('/api-school/orchestra/page', {
          data: {
            page: 1,
            rows: 100,
            schoolId: baseState.user.data.school.id
          }
        })
        const temps = data.rows || []
        const s = [] as any
        temps.forEach((item: any) => {
          s.push({
            text: item.name,
            value: item.id
          })
        })
        state.orchestraList = [...s]
      } catch {
        //
      }
    }

    // 初始化选择声部
    const onSelectSubject = (ids: any) => {
      state.selectSubjectIds = [...ids]
      const temps: any = []
      console.log(state.selectSubjects, '1212', state.subjectList)
      state.subjectList.forEach((item: any) => {
        const index = state.selectSubjects.findIndex((select: any) => select.id === item.subjectId)
        if (ids.includes(item.subjectId)) {
          // 判断是否在数据里，如果在则直接添加，不能重置数据
          if (index < 0) {
            temps.push({
              id: item.subjectId,
              name: item.subjectName,
              code: item.code,
              type: null,
              teacher: {}, // 老师信息
              students: [] as any // 选中的数据数
            })
          } else {
            temps.push(state.selectSubjects.find((select: any) => select.id === item.subjectId))
          }
        }
      })
      state.selectSubjects = [...temps]
    }

    const onSubmit = () => {
      if (!state.orchestraName) {
        showToast('请输入乐团名称')
        return
      }
      if (state.selectSubjects && state.selectSubjects.length <= 0) {
        showToast('请选择声部')
        return
      }

      const selectSubjects = state.selectSubjects || []
      let isSelect = false
      selectSubjects.forEach((item: any) => {
        if (!item.students || (item.students && item.students.length <= 0)) {
          isSelect = true
        }
      })
      if (isSelect) {
        showToast('请选择学生')
        return
      }

      // 初始化班级
      const tempSelect: any = []
      // 添加所在学生
      const tempStudents: any = []
      let largeUpSubject: any = {} // 上低音号和大号合集，目前根据编码处理，待定
      state.selectSubjects.forEach((item: any) => {
        console.log(item, 'item.name')
        tempStudents.push(...item.students)
        if (item.code !== 'BARITONE' && item.code !== 'TUBA') {
          tempSelect.push(item)
        } else {
          // 获取学生
          const temps = largeUpSubject.students ? largeUpSubject.students : []
          largeUpSubject = {
            id: largeUpSubject.id ? largeUpSubject.id + ',' + item.id : item.id,
            name: largeUpSubject.name ? largeUpSubject.name + '-' + item.name : item.name,
            type: null,
            teacher: {},
            students: [...temps, ...item.students]
          }
        }
      })

      state.selectLastTeacherSubjects = deepClone(tempSelect)

      // 判断是否有大号或者上低音号, 如果有则添加
      if (largeUpSubject.id) {
        state.selectLastTeacherSubjects.push(largeUpSubject)
      }
      // 默认添加两个班级
      state.selectLastTeacherSubjects.push(
        {
          id: null,
          name: '乐理班',
          type: 'MUSIC_THEORY',
          teacher: {}, // 老师信息
          students: [...tempStudents] as any // 选中的数据数
        },
        {
          id: null,
          name: '合奏班',
          type: 'INSTRUMENTAL_ENSEMBLE',
          teacher: {}, // 老师信息
          students: [...tempStudents] as any // 选中的数据数
        }
      )

      // 选择老师
      router.push({
        path: '/create-orchestra-teacher'
      })
    }

    onMounted(() => {
      resestState()
      getSubjects()
      getOrchestras()
    })
    return () => (
      <div class={styles['create-orchestra']}>
        <OHeader />

        <CellGroup inset>
          <Field
            label="乐团名称"
            v-model={state.orchestraName}
            placeholder="请输入乐团名称"
            inputAlign="right"
            maxlength={30}
          />
          <Field
            label="乐团声部"
            readonly
            placeholder={
              state.selectSubjects.length > 0 ? `已选${state.selectSubjects.length}个` : '选择声部'
            }
            isLink
            inputAlign="right"
            onClick={() => (state.subjectStatus = true)}
          />

          {state.selectSubjects.map((item: any) => (
            <Cell
              title={item.name}
              isLink
              onClick={() => {
                state.studentStatus = true
                state.selectSubjectStudents = item
              }}
            >
              {{
                value: () => (
                  <>
                    已选
                    <span style={{ color: 'var(--van-primary-color)' }}>
                      {item.students?.length || 0}
                    </span>
                    名学生
                  </>
                )
              }}
            </Cell>
          ))}
        </CellGroup>

        <OSticky position="bottom">
          <div class={['btnGroup']}>
            <Button type="primary" block round onClick={onSubmit}>
              下一步
            </Button>
          </div>
        </OSticky>

        {/* 选择声部 */}
        <OPopup v-model:modelValue={state.subjectStatus} style="background: #F8F8F8;">
          {state.subjectStatus && (
            <SubjectList
              onClose={() => (state.subjectStatus = false)}
              subjectList={state.subjectList}
              selectSubjects={state.selectSubjectIds}
              onSelect={onSelectSubject}
            />
          )}
        </OPopup>

        {/* 选择学生 */}
        <OPopup v-model:modelValue={state.studentStatus} style="background: #f8f8f8;">
          {state.studentStatus && (
            <StudentList
              orchestraList={state.orchestraList}
              subjectId={state.selectSubjectStudents.id}
              selectStudentIds={state.selectSubjectStudents.students}
              onClose={() => (state.studentStatus = false)}
              onSelect={(item: any) => {
                // console.log(item, 'select student')
                state.selectSubjectStudents.students = [...item]
              }}
            />
          )}
        </OPopup>
      </div>
    )
  }
})
