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 { 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 useDrag from '@/hooks/useDrag';
import Dragbom from '@/hooks/useDrag/dragbom';
import { useUserStore } from '@/store/modules/users';
import { api_getCurrentGradeYear } from '/src/views/studentList/api';
import request from '/src/utils/request';
import { modalClickMask } from '/src/state';
import TheTipDialog from '@/components/TheTipDialog';
import router from '/src/router';
import ResetSubjectList from '/src/views/classList/modals/resetSubjectList';

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 as any,
      currentClassList: [], // 当前选择的年级
      expireDate: dayjs().add(7, 'day').format('YYYY-MM-DD') as any, // 默认7天
      classGroupId: null as any,
      studentList: [] as any,
      selectIds: [] as any
    });

    const showResetClass = ref(false);
    const setClassSubjects = ref<any[]>([]);

    const formsRef = ref();
    const maxDeadlineTime = ref(0);
    const maxExpireTime = ref(0);
    const pickerEndTime = ref<any>(null);
    // 获取年级班级
    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 + '班',
              defaultLabel: i.name,
              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 tipDialog = reactive({
      show: false,
      msg: '',
      confirmButtonText: '',
      cancelBtn: false,
      type: 'CLASS' as 'CLASS' | 'PERSON' | 'MUSIC'
    });
    function handleLessonAddErr(data: any) {
      const { type, errList } = data;
      // if (type === 'CLASS') {
      // 班级乐器没有设置
      // tipDialog.cancelBtn = true;
      // tipDialog.confirmButtonText = '去设置';
      // const msg = errList.map((item: any) => {
      //   return `<div><span style="color:#F44541">【${
      //     item.classGroupName
      //   }】</span>未设置乐器，请设置乐器后布置作业${
      //     errList.length > 1 ? '；' : ''
      //   }</div>`;
      // });
      // tipDialog.msg = msg.join('');
      // } else if (type === 'PERSON') {
      // 学生乐器没有设置
      // tipDialog.cancelBtn = true;
      // tipDialog.confirmButtonText = '去设置';
      // const msg = errList.map((item: any) => {
      //   return `<div><span style="color:#F44541">【${
      //     item.studentName
      //   }】</span>所在<span style="color:#F44541">【${
      //     item.classGroupName
      //   }】</span>未设置乐器，请设置乐器后布置作业${
      //     errList.length > 1 ? '；' : ''
      //   }</div>`;
      // });
      // tipDialog.msg = msg.join('');
      // } else
      if (type === 'CLASS' || type === 'PERSON') {
        showResetClass.value = true;
        const msgList = errList.map((item: any) => {
          return {
            classGroupId: item.classGroupId,
            classGroupName: item.classGroupName
          };
        });
        setClassSubjects.value = msgList;
      } else if (type === 'MUSIC') {
        tipDialog.type = type;
        // 曲目和当前选择学生的乐器对不上的时候
        tipDialog.cancelBtn = false;
        tipDialog.confirmButtonText = '我知道了';
        const msg = errList.map((item: any) => {
          return `<div>曲目<span style="color:#F44541">【${
            item.musicSheetName
          }】</span>不支持<span style="color:#F44541">【${
            item.instrumentName
          }】</span>练习，请更换曲目或取消<span style="color:#F44541">【${
            item.instrumentName
          }】</span>的学生${errList.length > 1 ? '；' : ''}</div>`;
        });
        tipDialog.msg = msg.join('');
        tipDialog.show = true;
      }
    }
    function handleTipConfirm() {
      if (['CLASS', 'PERSON'].includes(tipDialog.type)) {
        router.push({
          path: '/classList'
        });
      } else if (tipDialog.type === 'MUSIC') {
        tipDialog.show = false;
      }
    }
    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') + ' 23:59:59',
            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(',');
          }
          const lessonRes = await lessonTrainingAdd(params);
          if (lessonRes.code === 200) {
            if (lessonRes.data.status) {
              message.success('布置成功');
              emit('close');
              emit('confirm');
            } else {
              handleLessonAddErr(lessonRes.data);
            }
          }
        } catch {
          //
        }
        forms.uploading = false;
      });
    };
    const getCurrentGradeYear = async () => {
      try {
        const { data } = await api_getCurrentGradeYear({});
        console.log(data);
        forms.gradeYear = data;
      } catch {
        //
      }
    };

    const getDefaultParamConfig = async () => {
      try {
        const { data } = await request.get(
          '/edu-app/open/paramConfig/queryByParamNameList',
          {
            params: {
              paramNames: 'homework_max_deadline_time,homework_file_expire_time'
            }
          }
        );
        const result = data || [];
        result.forEach((item: any) => {
          if (item.paramName === 'homework_file_expire_time') {
            maxExpireTime.value = item.paramValue || 0;
          } else if (item.paramName === 'homework_max_deadline_time') {
            maxDeadlineTime.value = item.paramValue || 0;
          }
        });

        // 处理截止时间显示
        /**
         1、当时间没有设置时，全部时间；
         2、设置了时间，小于7天；
         3、设置了时间，大于7天；
         */
        if (maxDeadlineTime.value > 0) {
          pickerEndTime.value = dayjs(
            dayjs()
              .add(Number(maxDeadlineTime.value) + 1, 'day')
              .format('YYYY-MM-DD')
          ).valueOf();
          if (Number(maxDeadlineTime.value) < 7) {
            forms.expireDate = dayjs()
              .add(Number(maxDeadlineTime.value), 'day')
              .format('YYYY-MM-DD HH:mm');
          }

          // console.log(
          //   dayjs()
          //     .add(Number(maxDeadlineTime.value), 'day')
          //     .format('YYYY-MM-DD'),
          //   'pickerEndTime.value'
          // );
          // state.pickerEndTime =
        }
      } catch {
        //
      }
    };

    const dateDisabled = (ts: number): boolean => {
      /**
        1、当时间没有设置时，全部时间；
        2、设置了时间，小于7天；
        3、设置了时间，大于7天；
        */
      let status = false;
      if (pickerEndTime.value) {
        status = ts < forms.currentTime || ts >= pickerEndTime.value;
      } else {
        status = ts < forms.currentTime;
      }
      // console.log(
      //   status,
      //   '1212',
      //   ts > pickerEndTime.value,
      //   forms.currentTime,
      //   ts,
      //   pickerEndTime.value
      // );
      // pickerEndTime.value && pickerEndTime.value > ts;
      return status;
    };

    const changeHomeWork = (type: any) => {
      forms.homeworkObj = type;
      if (!props.classGroupId) {
        forms.currentGradeNum = null;
        forms.classGroupId = null;
      }
    };

    onMounted(async () => {
      await getDefaultParamConfig();
      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={'80'}
          labelPlacement="left">
          <NFormItem
            label="布置方式"
            path="homeworkObj"
            rule={[{ required: true, message: '请选择布置方式' }]}>
            <NSpace>
              <NButton
                secondary
                class={[
                  styles.switch,
                  forms.homeworkObj === 'CLASS' ? styles.active : ''
                ]}
                onClick={() => changeHomeWork('CLASS')}>
                按班级布置
              </NButton>
              <NButton
                secondary
                class={[
                  styles.switch,
                  forms.homeworkObj === 'PERSON' ? styles.active : ''
                ]}
                onClick={() => changeHomeWork('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:
                  forms.homeworkObj === 'CLASS' || props.classGroupId
                    ? 'number'
                    : 'array'
              }
            ]}>
            <NSelect
              disabled={props.classGroupId ? true : false}
              v-model:value={forms.currentGradeNum}
              placeholder="请选择年级"
              multiple={
                forms.homeworkObj === 'CLASS' || props.classGroupId
                  ? false
                  : true
              }
              options={forms.gradeList}
              clearable
              onUpdate:value={() => {
                forms.classGroupId = null;
                forms.studentList = [];
                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.length <= 0) {
                    return;
                  }
                  const tempClass: any = [];
                  forms.gradeList.forEach((item: any) => {
                    // 为了区分上课页面和作业页面
                    if (Array.isArray(forms.currentGradeNum)) {
                      if (forms.currentGradeNum.includes(item.value)) {
                        const child = item.childrens || [];
                        tempClass.push(...child);
                      }
                    } else {
                      if (forms.currentGradeNum === item.value) {
                        const child = item.childrens || [];
                        tempClass.push(...child);
                      }
                    }
                  });

                  forms.currentClassList = tempClass;

                  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 HH:mm"
              format="yyyy-MM-dd"
              style={{ width: '100%' }}
              isDateDisabled={dateDisabled}
            />
          </NFormItem>

          {maxExpireTime.value > 0 && (
            <NFormItem label=" " class={styles.maxExpireTime}>
              <div class={styles.expireDateTip}>
                <i class={styles.expireDateIcon}></i>
                <span>
                  作业截止{maxExpireTime.value}
                  天后，学生上传的文件将过期，请及时查看
                </span>
              </div>
            </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
          maskClosable={modalClickMask}
          v-model:show={forms.workVisiable}
          style={
            props.from === 'class'
              ? {
                  width: '780px',
                  ...assignHomeworkStuBoxDragData.styleDrag.value
                }
              : {
                  width: '780px'
                }
          }
          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.currentClassList}
            onClose={() => (forms.workVisiable = false)}
            onConfirm={(val: any) => {
              forms.studentList = val || [];
              forms.workVisiable = false;
            }}
          />
          {props.from === 'class' && <Dragbom></Dragbom>}
        </NModal>
        <TheTipDialog
          show={tipDialog.show}
          content={tipDialog.msg}
          onClose={() => {
            tipDialog.show = false;
          }}
          onConfirm={handleTipConfirm}
          cancelButtonText={'暂不设置'}
          cancelBtn={tipDialog.cancelBtn}
          confirmButtonText={tipDialog.confirmButtonText}></TheTipDialog>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={showResetClass.value}
          style={{ width: '392px' }}
          display-directive="if"
          preset="card"
          class={['modalTitleNew']}
          title={'选择乐器'}>
          <ResetSubjectList
            activeRow={setClassSubjects.value}
            // onGetList={() => {}}
            onClose={() => (showResetClass.value = false)}
          />
        </NModal>
      </div>
    );
  }
});
