import {
  PropType,
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRef
} from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NDatePicker,
  NForm,
  NFormItem,
  NInput,
  NModal,
  NScrollbar,
  NSelect,
  NSpace,
  useMessage
} from 'naive-ui';
import { BOOK_DATA } from '/src/views/natural-resources/model/add-teaching';
import { classGroupPage, lessonTrainingAdd } from '../../../api';
import dayjs from 'dayjs';
import { classGroupList } from '/src/views/home/api';
import { gradeToCN } from '/src/utils/contants';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import AssignStudent from './assign-student';
import { state } from '/src/state';
import { nextTick } from 'process';
import { api_getCurrentGradeYear } from '/src/views/studentList/api';
import useDrag from '@/hooks/useDrag';
import Dragbom from '@/hooks/useDrag/dragbom';
import { useUserStore } from '@/store/modules/users';

export default defineComponent({
  name: 'assign-homework',
  props: {
    classGroupId: {
      type: String,
      default: ''
    },
    courseScheduleId: {
      type: String,
      default: ''
    },
    /** 课件编号 */
    chapterLessonCoursewareId: {
      type: String,
      default: ''
    },
    item: {
      type: Object,
      default: () => ({})
    },
    /** 初始数据 */
    trainList: {
      type: Array,
      default: () => []
    },
    homeworkType: {
      type: String as PropType<'CLASSWORK' | 'HOMEWORK'>,
      default: 'CLASSWORK'
    },
    from: {
      // 来自哪里
      type: String,
      default: ''
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const message = useMessage();
    const prepareStore = usePrepareStore();
    const forms = reactive({
      gradeYear: '' as any,
      currentTime: dayjs(dayjs().format('YYYY-MM-DD')).valueOf(),
      homeworkObj: 'CLASS' as 'PERSON' | 'CLASS',
      homeworkType: props.homeworkType,
      workVisiable: false,
      id: null as any,
      uploading: false,
      title: props.item.title,
      courseScheduleId: props.courseScheduleId || null,
      chapterLessonCoursewareId: props.chapterLessonCoursewareId || null,
      gradeList: [] as any,
      classList: [] as any,
      currentGradeNum: null,
      expireDate: dayjs().add(7, 'day').format('YYYY-MM-DD HH:mm') as any, // 默认7天
      classGroupId: null as any,
      studentList: [] as any,
      selectIds: [] as any
    });
    const formsRef = ref();

    // 获取年级班级
    const getClassGroupList = async () => {
      try {
        const defaultSelectClassGroupId =
          props.classGroupId || prepareStore.getClassGroupId;
        const { data } = await classGroupList({
          upgradeFlag: true,
          gradeYear: forms.gradeYear
        });
        const cList = data || [];
        const gradeList: any = [];
        cList.forEach((item: any) => {
          const classList: any = [];
          item.classGroupList.forEach((i: any) => {
            classList.push({
              label: i.currentClass + '班',
              value: i.id,
              lastStudy: i.lastStudy,
              preStudentNum: i.preStudentNum
            });

            if (i.id === defaultSelectClassGroupId) {
              forms.currentGradeNum = i.currentGradeNum;
              forms.classGroupId = [i.id];
            }
          });

          gradeList.push({
            label: gradeToCN[item.currentGradeNum],
            value: item.currentGradeNum,
            childrens: classList
          });
        });
        forms.gradeList = gradeList;

        if (forms.currentGradeNum) {
          getClassList();
        }
      } catch {
        //
      }
    };

    const getClassList = async () => {
      try {
        forms.gradeList.forEach((item: any) => {
          if (item.value === forms.currentGradeNum) {
            forms.classList = item.childrens;
          }
        });
      } catch {
        //
      }
    };

    const onSubmit = async () => {
      formsRef.value?.validate(async (err: any) => {
        if (err) {
          return;
        }
        forms.uploading = true;
        try {
          const trainList: any = props.item.lessonPreTrainingDetails || [];
          const details: any[] = [];
          trainList.forEach((item: any) => {
            details.push({
              trainingType: item.trainingType,
              musicId: item.musicId,
              trainingConfigJsonObject: item.trainingConfigJson
            });
          });
          const params = {
            name: forms.title,
            homeworkObj: forms.homeworkObj,
            homeworkType: forms.homeworkType,
            lessonTrainingDetails: details,
            expireDate: dayjs(forms.expireDate).format('YYYY-MM-DD HH:mm:ss'),
            classGroupId: forms.classGroupId
              ? forms.classGroupId.join(',')
              : null,
            studentIds: null as any,
            courseScheduleId: forms.courseScheduleId,
            chapterLessonCoursewareId: forms.chapterLessonCoursewareId // 课件编号
          };
          if (forms.homeworkObj === 'PERSON') {
            params.classGroupId = '';
            const ids: any[] = [];
            forms.studentList.forEach((item: any) => {
              ids.push(item.id);
            });
            params.studentIds = ids.join(',');
          }
          await lessonTrainingAdd(params);
          message.success('布置成功');
          emit('close');
          emit('confirm');
        } catch {
          //
        }
        forms.uploading = false;
      });
    };
    const getCurrentGradeYear = async () => {
      try {
        const { data } = await api_getCurrentGradeYear({});
        console.log(data);
        forms.gradeYear = data;
      } catch {
        //
      }
    };

    onMounted(async () => {
      await getCurrentGradeYear();
      await getClassGroupList();
    });
    // 选择学生
    let assignHomeworkStuBoxDragData: any;
    let assignHomeworkStuBoxClass: string;
    if (props.from === 'class') {
      const users = useUserStore();
      assignHomeworkStuBoxClass = 'assignHomeworkStuBoxClass_drag';
      assignHomeworkStuBoxDragData = useDrag(
        [
          `${assignHomeworkStuBoxClass}>.n-card-header`,
          `${assignHomeworkStuBoxClass} .bom_drag`
        ],
        assignHomeworkStuBoxClass,
        toRef(forms, 'workVisiable'),
        users.info.id
      );
    }
    return () => (
      <div class={styles.assignHomeworkContainer}>
        <NForm
          ref={formsRef}
          model={forms}
          labelAlign="right"
          labelWidth={'auto'}
          labelPlacement="left">
          <NFormItem
            label="布置方式"
            path="homeworkObj"
            rule={[{ required: true, message: '请选择布置方式' }]}>
            <NSpace>
              <NButton
                secondary
                class={[
                  styles.switch,
                  forms.homeworkObj === 'CLASS' ? styles.active : ''
                ]}
                onClick={() => (forms.homeworkObj = 'CLASS')}>
                按班级布置
              </NButton>
              <NButton
                secondary
                class={[
                  styles.switch,
                  forms.homeworkObj === 'PERSON' ? styles.active : ''
                ]}
                onClick={() => (forms.homeworkObj = 'PERSON')}>
                按学生布置
              </NButton>
            </NSpace>
          </NFormItem>
          <NFormItem
            label="作业标题"
            path="title"
            rule={[
              {
                required: true,
                message: '请输入作业标题',
                trigger: 'blur'
              }
            ]}>
            <NInput
              v-model:value={forms.title}
              placeholder="请选择作业标题"
              clearable
            />
          </NFormItem>

          <NFormItem
            label="年级"
            path="currentGradeNum"
            rule={[
              {
                required: true,
                message: '请选择年级',
                trigger: 'change',
                type: 'number'
              }
            ]}>
            <NSelect
              disabled={props.classGroupId ? true : false}
              v-model:value={forms.currentGradeNum}
              placeholder="请选择年级"
              options={forms.gradeList}
              clearable
              onUpdate:value={() => {
                forms.classGroupId = null;
                getClassList();
              }}
            />
          </NFormItem>
          {forms.homeworkObj === 'CLASS' ? (
            <NFormItem
              label="班级"
              path="classGroupId"
              rule={[
                {
                  required: true,
                  message: '请选择班级',
                  trigger: 'change',
                  type: 'array'
                }
              ]}>
              <NSelect
                disabled={props.classGroupId ? true : false}
                options={forms.classList}
                v-model:value={forms.classGroupId}
                placeholder="请选择班级"
                clearable
                multiple
              />
            </NFormItem>
          ) : (
            <NFormItem
              label="学生"
              path="studentList"
              rule={[
                {
                  required: true,
                  message: '请选择学生',
                  trigger: 'change',
                  type: 'array'
                }
              ]}
              class={styles.studentSection}>
              <span
                class={[
                  styles.selectStudentBtn,
                  !forms.currentGradeNum && styles.disabled
                ]}
                onClick={() => {
                  if (!forms.currentGradeNum) {
                    return;
                  }
                  const tempIds: any = [];
                  forms.studentList.forEach((item: any) => {
                    tempIds.push(item.id);
                  });
                  forms.selectIds = tempIds;
                  forms.workVisiable = true;
                }}>
                选择学生
              </span>
              {forms.studentList.length > 0 && (
                <NScrollbar class={styles.studentList}>
                  <span class={styles.firstName}>
                    当前选中({forms.studentList.length || 0}):
                  </span>
                  {forms.studentList.map((item: any, index: number) => (
                    <span class={styles.studentItem}>
                      {item.name}{' '}
                      <i
                        class={styles.iconDelete}
                        onClick={() => {
                          forms.studentList.splice(index, 1);
                        }}></i>
                    </span>
                  ))}
                </NScrollbar>
              )}
            </NFormItem>
          )}

          <NFormItem
            label="截止时间"
            path="expireDate"
            rule={[
              { required: true, message: '请选择截止时间', trigger: 'change' }
            ]}>
            <NDatePicker
              v-model:formatted-value={forms.expireDate}
              type="datetime"
              clearable
              // valueFormat="yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm"
              style={{ width: '100%' }}
              isDateDisabled={(ts: number) => {
                return ts < forms.currentTime;
              }}
            />
          </NFormItem>

          <NSpace class={styles.updateBtnGroup}>
            <NButton strong type="default" round onClick={() => emit('close')}>
              取消布置
            </NButton>
            <NButton
              strong
              type="primary"
              round
              disabled={forms.uploading}
              loading={forms.uploading}
              onClick={onSubmit}>
              确认布置
            </NButton>
          </NSpace>
        </NForm>

        <NModal
          v-model:show={forms.workVisiable}
          style={
            props.from === 'class'
              ? {
                  width: '640px',
                  ...assignHomeworkStuBoxDragData.styleDrag.value
                }
              : {
                  width: '640px'
                }
          }
          preset="card"
          showIcon={false}
          class={['modalTitle background', assignHomeworkStuBoxClass]}
          title={'选择学生'}
          blockScroll={false}>
          <AssignStudent
            classGroupId={props.classGroupId}
            currentGradeNum={forms.currentGradeNum as any}
            selectIds={forms.selectIds}
            studentList={forms.studentList}
            classList={forms.classList}
            onClose={() => (forms.workVisiable = false)}
            onConfirm={(val: any) => {
              forms.studentList = val || [];
              forms.workVisiable = false;
            }}
          />
          {props.from === 'class' && <Dragbom></Dragbom>}
        </NModal>
      </div>
    );
  }
});
