import { PropType, defineComponent, onMounted, reactive, ref } 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';

export default defineComponent({
  name: 'assign-homework',
  props: {
    classGroupId: {
      type: String,
      default: ''
    },
    courseScheduleId: {
      type: String,
      default: ''
    },
    item: {
      type: Object,
      default: () => ({})
    },
    /** 初始数据 */
    trainList: {
      type: Array,
      default: () => []
    },
    homeworkType: {
      type: String as PropType<'CLASSWORK' | 'HOMEWORK'>,
      default: 'HOMEWORK'
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const message = useMessage();
    const prepareStore = usePrepareStore();
    const forms = reactive({
      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,
      gradeList: [] as any,
      classList: [] as any,
      currentGradeNum: null,
      expireDate: dayjs().add(7, 'day').format('YYYY-MM-DD') 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
        });
        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 = 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: forms.expireDate + ' 23:59:59',
            classGroupId: forms.classGroupId
              ? forms.classGroupId.join(',')
              : null,
            studentIds: null as any,
            courseScheduleId: forms.courseScheduleId
          };

          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;
      });
    };

    onMounted(async () => {
      await getClassGroupList();
    });
    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="date"
              clearable
              valueFormat="yyyy-MM-dd"
              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}
          preset="card"
          showIcon={false}
          class={['modalTitle background']}
          title={'布置作业'}
          style={{ width: '640px' }}
          blockScroll={false}>
          <AssignStudent
            classGroupId={props.classGroupId}
            selectIds={forms.selectIds}
            classList={forms.classList}
            onClose={() => (forms.workVisiable = false)}
            onConfirm={(val: any) => {
              forms.studentList = val || [];
              forms.workVisiable = false;
            }}
          />
        </NModal>
      </div>
    );
  }
});
