import { defineComponent, reactive, onMounted, ref, nextTick } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NImage,
  NModal,
  NSelect,
  NSpace,
  useDialog,
  useMessage
} from 'naive-ui';
import SearchInput from '@/components/searchInput';
import CSelect from '@/components/CSelect';
import Pagination from '@/components/pagination';
import { classGroupList, deleteClass, getSubject } from './api';

import CreateClass from './modals/createClass';
import RestStudentBox from './modals/restStudentBox';
import TrainDetail from './modals/Gotoclass';
import { getgradeNumList, classArray } from './contants';
import add from '@/views/studentList/images/add.png';
import ClassGuide from '@/custom-plugins/guide-page/class-guide';
import { useRouter } from 'vue-router';
import { rowDark } from 'naive-ui/es/legacy-grid/styles';
import TheEmpty from '/src/components/TheEmpty';
import TheTooltip from '/src/components/TheTooltip';
import PreviewWindow from '../preview-window';
import { state as globalState } from '/src/state';
import { courseSchedulePage } from '../home/api';
import ResetSubject from './modals/resetSubject';
import { fscreen } from '/src/utils';
import UpdateSubject from './modals/updateSubject';
export default defineComponent({
  name: 'class-classList',
  setup(props, { emit }) {
    const state = reactive({
      searchForm: {
        keyword: null as any,
        currentClass: null,
        currentGradeNum: null,
        subjectId: null
      },
      orchestraType: null,
      courseTypeCode: null,
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 6
      },
      gradeNumList: [] as any,
      tableList: [] as any,
      studentVisible: false,
      activeRow: null as any,
      showaddClass: false,
      goCourseVisiable: false,
      removeVisiable: false,
      removeRow: {} as any,
      previewModal: false,
      previewParams: {} as any,
      lastCourse: null as any,
      subjectList: [] as any,
      showResetClass: false,
      showSubjectClass: false
    });
    const formRef = ref();
    const dialog = useDialog();
    const message = useMessage();
    const router = useRouter();
    const search = () => {
      state.pagination.page = 1;
      getList();
      console.log('search', state);
    };
    const showGuide = ref(false);
    state.gradeNumList = getgradeNumList();
    const onReset = () => {
      state.searchForm = {
        keyword: null as any,
        currentClass: null,
        currentGradeNum: null,
        subjectId: null
      };
      getList();
    };

    const removeClass = async () => {
      try {
        await deleteClass({ ids: state.removeRow.id });
        getList();
        message.success(`删除成功`);
        state.removeVisiable = false;
      } catch (e) {
        console.log(e);
      }
    };
    const getList = async () => {
      // classGroupList
      state.loading = true;
      try {
        const res = await classGroupList({
          ...state.searchForm,
          ...state.pagination
        });
        state.tableList = res.data.rows;
        state.pagination.pageTotal = res.data.total;
        state.loading = false;

        setTimeout(() => {
          if (state.tableList.length > 0) {
            showGuide.value = true;
          }
        }, 500);
      } catch (e) {
        state.loading = false;
        console.log(e);
      }
      console.log('getList');
    };
    const getSubjectList = async () => {
      const res = await getSubject({ page: 1, rows: 9999 });
      state.subjectList = res.data.rows.map((item: any) => {
        return {
          value: item.id,
          label: item.name
        };
      });
      state.subjectList.unshift({ value: null, label: '选择声部' });
    };
    const columns = () => {
      return [
        {
          title: '班级名称',
          key: 'name',
          width: '20%'
        },
        {
          title: '班级声部',
          key: 'subjectName',
          width: '20%'
        },
        {
          title: '学生人数',
          key: 'preStudentNum',
          width: '20%'
        },
        {
          title: '上次学习',
          key: 'lastStudy',
          width: '20%',
          render(row: any) {
            return row.lastStudy ? (
              <TheTooltip
                maxWidth={300}
                showContentWidth={300}
                content={row.lastStudy}
              />
            ) : (
              '--'
            );
          }
        },
        {
          title: '操作',
          key: 'id',

          render(row: any, index: number) {
            return (
              <div>
                <NSpace>
                  {index == 0 ? (
                    <div id="class-0">
                      <NButton
                        type="primary"
                        text
                        onClick={() => {
                          router.push({
                            path: '/classDetail',
                            query: { name: row.name, id: row.id }
                          });
                        }}>
                        详情
                      </NButton>
                    </div>
                  ) : (
                    <NButton
                      type="primary"
                      text
                      onClick={() => {
                        router.push({
                          path: '/classDetail',
                          query: { name: row.name, id: row.id }
                        });
                      }}>
                      详情
                    </NButton>
                  )}
                  <NButton
                    type="primary"
                    text
                    onClick={() => resetClassSubject(row)}>
                    修改声部
                  </NButton>
                  {index == 0 ? (
                    <NButton
                      type="primary"
                      {...{ id: 'class-1' }}
                      text
                      onClick={() => {
                        startResetStudent(row);
                      }}>
                      学生调整
                    </NButton>
                  ) : (
                    <NButton
                      type="primary"
                      text
                      onClick={() => {
                        startResetStudent(row);
                      }}>
                      学生调整
                    </NButton>
                  )}
                  {index == 0 ? (
                    <NButton
                      {...{ id: 'class-2' }}
                      disabled={!(row.preStudentNum > 0)}
                      type="primary"
                      text
                      onClick={() => classesBegin(row)}>
                      开始上课
                    </NButton>
                  ) : (
                    <NButton
                      disabled={!(row.preStudentNum > 0)}
                      type="primary"
                      text
                      onClick={() => classesBegin(row)}>
                      开始上课
                    </NButton>
                  )}

                  {!(row.preStudentNum > 0) ? (
                    <p
                      style={{ color: '#EA4132', cursor: 'pointer' }}
                      onClick={() => {
                        state.removeVisiable = true;
                        state.removeRow = row;
                      }}>
                      删除
                    </p>
                  ) : null}
                </NSpace>
              </div>
            );
          }
        }
      ];
    };

    const startResetStudent = (row: any) => {
      state.activeRow = row;
      state.studentVisible = true;
    };

    const classesBegin = async (row: any) => {
      try {
        console.log(row, 'row');
        // 判断是否有声部
        if (row.subjectId) {
          //
          router.push({
            path: '/prepare-lessons',
            query: {
              lastUseCoursewareId: row.lessonCoursewareId,
              unit: row.lessonCoursewareKnowledgeDetailId,
              subjectId: row.subjectId,
              name: row.name, // 班级名称
              classGroupId: row.id // 班级编号
            }
          });
        } else {
          state.showSubjectClass = true;
          state.activeRow = row;
        }
      } catch (e) {
        console.log(e);
      }
    };

    const resetClassSubject = (row: any) => {
      state.activeRow = row;
      state.showResetClass = true;
    };
    onMounted(() => {
      getList();
      getSubjectList();
    });
    return () => (
      <div class={styles.listWrap}>
        <div class={styles.searchList}>
          <NForm label-placement="left" inline ref={formRef}>
            <NFormItem>
              <SearchInput
                {...{ placeholder: '请输入班级名称' }}
                class={styles.searchInput}
                searchWord={state.searchForm.keyword}
                onChangeValue={(val: string) =>
                  (state.searchForm.keyword = val)
                }></SearchInput>
            </NFormItem>

            <NFormItem>
              <CSelect
                {...({
                  options: state.gradeNumList,
                  placeholder: '选择年级',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.currentGradeNum}></CSelect>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: classArray,
                  placeholder: '选择班级',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.currentClass}></CSelect>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: state.subjectList,
                  placeholder: '选择声部',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.subjectId}></CSelect>
            </NFormItem>
            <NFormItem>
              <NSpace justify="end">
                <NButton type="primary" class="searchBtn" onClick={search}>
                  搜索
                </NButton>
                <NButton
                  type="primary"
                  ghost
                  class="resetBtn"
                  onClick={onReset}>
                  重置
                </NButton>
              </NSpace>
            </NFormItem>
          </NForm>
        </div>
        <NButton
          class={styles.addBtn}
          type="primary"
          onClick={() => (state.showaddClass = true)}
          v-slots={{
            icon: () => (
              <>
                <NImage
                  class={styles.addBtnIcon}
                  previewDisabled
                  src={add}></NImage>
              </>
            )
          }}>
          创建班级
        </NButton>
        <div class={styles.tableWrap}>
          <NDataTable
            v-slots={{
              empty: () => <TheEmpty></TheEmpty>
            }}
            class={styles.classTable}
            loading={state.loading}
            columns={columns()}
            data={state.tableList}></NDataTable>
          <Pagination
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          />
        </div>
        <NModal
          v-model:show={state.studentVisible}
          preset="card"
          class={['modalTitle background', styles.studentVisible]}
          title={'学员调整'}>
          <RestStudentBox
            activeRow={state.activeRow}
            onClose={() => (state.studentVisible = false)}
            onGetList={() => getList()}></RestStudentBox>
        </NModal>
        <NModal
          v-model:show={state.showaddClass}
          style={{ width: '500px' }}
          preset="card"
          class={['modalTitle background']}
          title={'创建班级'}>
          {state.showaddClass ? (
            <CreateClass
              gradeNumList={state.gradeNumList}
              classArray={classArray}
              subjectList={state.subjectList}
              onGetList={() => getList()}
              onClose={() => (state.showaddClass = false)}
            />
          ) : null}
        </NModal>
        <NModal
          v-model:show={state.showResetClass}
          style={{ width: '500px' }}
          preset="card"
          class={['modalTitle background']}
          title={'修改声部'}>
          {state.showResetClass ? (
            <ResetSubject
              activeRow={state.activeRow}
              subjectList={state.subjectList}
              onGetList={() => getList()}
              onClose={() => (state.showResetClass = false)}
            />
          ) : null}
        </NModal>

        <NModal
          v-model:show={state.showSubjectClass}
          style={{ width: '500px' }}
          preset="card"
          class={['modalTitle background']}
          title={'修改声部'}>
          {state.showSubjectClass ? (
            <UpdateSubject
              activeRow={state.activeRow}
              onGetList={() => getList()}
              onConfirm={(item: any) => {
                //
                router.push({
                  path: '/prepare-lessons',
                  query: {
                    ...item
                  }
                });
              }}
              onClose={() => (state.showSubjectClass = false)}
            />
          ) : null}
        </NModal>

        {/* 上课弹窗 */}
        <PreviewWindow
          v-model:show={state.previewModal}
          type="attend"
          params={state.previewParams}
        />

        <NModal
          v-model:show={state.removeVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable]}
          title={'删除班级'}>
          <div class={styles.studentRemove}>
            <p>
              确定要删除班级么？
              <span>删除班级信息将会清空</span>。
            </p>

            <NSpace class={styles.btnGroup} justify="center">
              <NButton round type="primary" onClick={removeClass}>
                确定
              </NButton>
              <NButton round onClick={() => (state.removeVisiable = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
        </NModal>
        {showGuide.value ? <ClassGuide></ClassGuide> : null}
      </div>
    );
  }
});
