import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NDatePicker,
  NForm,
  NFormItem,
  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';

export default defineComponent({
  name: 'assign-homework',
  props: {
    /** 初始数据 */
    trainList: {
      type: Array,
      default: () => []
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const message = useMessage();
    const prepareStore = usePrepareStore();
    const forms = reactive({
      currentTime: dayjs(dayjs().format('YYYY-MM-DD')).valueOf(),
      id: null as any,
      uploading: false,
      gradeList: [] as any,
      classList: [] as any,
      currentGradeNum: null,
      expireDate: dayjs().add(7, 'day').format('YYYY-MM-DD') as any, // 默认7天
      classGroupId: null as any
    });
    const formsRef = ref();

    // 获取年级班级
    const getClassGroupList = async () => {
      try {
        const defaultSelectClassGroupId = prepareStore.getClassGroupId;
        console.log('defaultSelectClassGroupId:', defaultSelectClassGroupId);
        const { data } = await classGroupList({ removeZeroClass: 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
            });

            if (i.id === defaultSelectClassGroupId) {
              console.log('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.trainList || [];
          const details: any[] = [];
          trainList.forEach((item: any) => {
            details.push({
              trainingType: item.trainingType,
              musicId: item.musicId,
              trainingConfigJsonObject: item.trainingConfigJson
            });
          });
          const params = {
            lessonTrainingDetails: details,
            expireDate: forms.expireDate + ' 23:59:59',
            classGroupId: forms.classGroupId
          };
          await lessonTrainingAdd(params);
          message.success('布置成功');
          emit('close');
        } catch {
          //
        }
        forms.uploading = false;
      });
    };

    onMounted(() => {
      getClassGroupList();
    });
    return () => (
      <div class={styles.assignHomeworkContainer}>
        <NForm
          ref={formsRef}
          model={forms}
          labelAlign="right"
          labelWidth={'auto'}
          labelPlacement="left">
          <NFormItem
            label="年级"
            path="currentGradeNum"
            rule={[
              {
                required: true,
                message: '请选择年级',
                trigger: 'change',
                type: 'number'
              }
            ]}>
            <NSelect
              v-model:value={forms.currentGradeNum}
              placeholder="请选择年级"
              options={forms.gradeList}
              clearable
              onUpdate:value={() => {
                forms.classGroupId = null;
                getClassList();
              }}
            />
          </NFormItem>
          <NFormItem
            label="班级"
            path="classGroupId"
            rule={[
              { required: true, message: '请选择班级', trigger: 'change' }
            ]}>
            <NSelect
              v-model:value={forms.classGroupId}
              placeholder="请选择班级"
              clearable
              options={forms.classList}
            />
          </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>
      </div>
    );
  }
});
