import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NDatePicker,
  NModal,
  NScrollbar,
  NSpace,
  NSpin,
  useMessage
} from 'naive-ui';
import TrainType from '@/views/attend-class/model/train-type';
import TrainUpdate from '../train-update';
import SelectMusic from '@/views/prepare-lessons/model/select-music';
import {
  lessonPreTrainingPage,
  lessonTrainingAdd
} from '/src/views/prepare-lessons/api';
import { evaluateDifficult } from '/src/utils/contants';
import dayjs from 'dayjs';
import TheEmpty from '/src/components/TheEmpty';
import requestOrigin from 'umi-request';

export default defineComponent({
  name: 'train-settings',
  props: {
    /** 章节编号 */
    detailId: {
      type: String,
      default: ''
    },
    /** 声部编号 */
    subjectId: {
      type: String,
      default: ''
    },
    /** 班级编号 */
    classGroupId: {
      type: String,
      default: ''
    },
    /** 上课编号 */
    courseScheduleId: {
      type: String,
      default: ''
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const message = useMessage();
    const trainForms = reactive({
      type: 'add' as 'add' | 'update',
      btnLoading: false,
      loadingStatus: false,
      editStatus: false,
      editItem: {} as any,
      selectMusicStatus: false,
      trainList: [] as any,
      currentTime: dayjs(dayjs().format('YYYY-MM-DD')).valueOf(),
      expireDate: dayjs().add(7, 'day').format('YYYY-MM-DD') as any // 默认7天
    });
    const getList = async () => {
      trainForms.loadingStatus = true;
      try {
        // 判断是否有选择对应的课件
        const { data } = await lessonPreTrainingPage({
          coursewareKnowledgeDetailId: props.detailId,
          subjectId: props.subjectId,
          page: 1,
          rows: 99
        });
        const tempRows = data.rows || [];
        const temp: any = [];

        tempRows.forEach((row: any) => {
          const tList = typeFormat(row.trainingType, row.trainingConfigJson);
          temp.push({
            typeList: tList || [],
            ...row
          });
        });
        trainForms.trainList = temp || [];
      } catch {
        //
      }
      trainForms.loadingStatus = false;
    };

    const typeFormat = (trainingType: string, configJson: any) => {
      let tList: string[] = [];

      if (trainingType === 'EVALUATION') {
        tList = [
          `${evaluateDifficult[configJson.evaluateDifficult]}`,
          configJson.practiceChapterBegin || configJson.practiceChapterEnd
            ? `${configJson.practiceChapterBegin}-${configJson.practiceChapterEnd}小节`
            : '全部小节',
          // `速度${configJson.evaluateSpeed}`,
          `${configJson.trainingTimes}分合格`
        ];
      } else {
        tList = [
          `${configJson.practiceChapterBegin}-${configJson.practiceChapterEnd}小节`,
          `速度${configJson.practiceSpeed}`,
          `${configJson.trainingTimes}分钟`
        ];
      }
      return tList;
    };

    const onAdd = async (item: any) => {
      let xmlStatus = 'init';
      // 第一个声部小节
      let firstMeasures: any = null;
      try {
        // 获取文件
        const res = await requestOrigin.get(item.xmlFileUrl, {
          mode: 'cors'
        });
        const xmlParse = new DOMParser().parseFromString(res, 'text/xml');
        const parts = xmlParse.getElementsByTagName('part');
        firstMeasures = parts[0]?.getElementsByTagName('measure');
        xmlStatus = 'success';
      } catch (error) {
        xmlStatus = 'error';
      }

      // 判断读取小节数
      if (xmlStatus == 'success') {
        item.practiceChapterMax = firstMeasures.length;
      } else {
        item.practiceChapterMax = 0;
      }
      item.coursewareKnowledgeDetailId = props.detailId;
      item.subjectId = props.subjectId;

      trainForms.editItem = item;
      trainForms.editStatus = true;
    };

    const onSubmit = async () => {
      // 训练内容不能为空
      if (!trainForms.expireDate) {
        message.error('请选择截止日期');
        return;
      }
      if (trainForms.trainList.length <= 0) {
        message.error('训练内容不能为空');
        return;
      }
      trainForms.btnLoading = true;
      try {
        const trainList = trainForms.trainList || [];
        const details: any[] = [];
        trainList.forEach((item: any) => {
          details.push({
            trainingType: item.trainingType,
            musicId: item.musicId,
            trainingConfigJsonObject: item.trainingConfigJson
          });
        });
        const params = {
          lessonTrainingDetails: details,
          expireDate: trainForms.expireDate + ' 23:59:59',
          classGroupId: props.classGroupId,
          courseScheduleId: props.courseScheduleId || null
        };
        await lessonTrainingAdd(params);
        message.success('布置成功');

        emit('close');
        emit('confirm');
      } catch {
        //
      }
      trainForms.btnLoading = false;
    };

    onMounted(() => {
      // 判断是否有数据
      if (props.detailId && props.subjectId) {
        getList();
      }
    });
    return () => (
      <div class={styles.trainSettings}>
        <div class={styles.searchGroup}>
          <NButton
            onClick={() => {
              trainForms.selectMusicStatus = true;
              trainForms.type = 'add';
            }}>
            添加作业
          </NButton>

          <div class={styles.datetime}>
            <label>截止时间：</label>
            <NDatePicker
              style={{ width: '200px' }}
              placeholder="请选择截止日期"
              v-model:formatted-value={trainForms.expireDate}
              type="date"
              valueFormat="yyyy-MM-dd"
              isDateDisabled={(ts: number) => {
                return ts < trainForms.currentTime;
              }}
            />
          </div>
        </div>
        <NScrollbar class={styles.trainList}>
          <NSpin show={trainForms.loadingStatus}>
            <div
              class={[
                styles.listSection,
                !trainForms.loadingStatus && trainForms.trainList.length <= 0
                  ? styles.emptySection
                  : ''
              ]}>
              {trainForms.trainList.length > 0 && (
                <div class={styles.list}>
                  {trainForms.trainList.map((item: any, index: number) => (
                    <TrainType
                      item={item}
                      type="homework"
                      onEdit={(child: any) => {
                        const { trainingConfigJson, id, musicId, ...res } =
                          child;
                        trainForms.editItem = {
                          ...res,
                          id: musicId,
                          trainId: id,
                          ...trainingConfigJson
                        };
                        console.log(trainForms.editItem);
                        trainForms.type = 'update';
                        trainForms.editStatus = true;
                      }}
                      onDelete={() => {
                        // 删除
                        // const index = trainForms.trainList.findIndex(
                        //   (c: any) => c.id === item.id
                        // );
                        trainForms.trainList.splice(index, 1);
                      }}
                    />
                  ))}
                </div>
              )}

              {!trainForms.loadingStatus &&
                trainForms.trainList.length <= 0 && (
                  <TheEmpty description="暂无作业" />
                )}
            </div>
          </NSpin>
        </NScrollbar>
        <NSpace class={styles.trainBtnGroup}>
          <NButton strong type="default" round onClick={() => emit('close')}>
            取消布置
          </NButton>
          <NButton
            strong
            type="primary"
            round
            disabled={trainForms.trainList.length <= 0 ? true : false}
            onClick={onSubmit}>
            立即布置
          </NButton>
        </NSpace>

        <NModal
          v-model:show={trainForms.editStatus}
          class={['modalTitle background', styles.trainEditModal]}
          preset="card"
          title="作业设置">
          <TrainUpdate
            item={trainForms.editItem}
            type="homework"
            onClose={() => (trainForms.editStatus = false)}
            onConfirm={(item: any) => {
              console.log(item, 'update', trainForms);
              const tList = typeFormat(
                item.trainingType,
                item.trainingConfigJson
              );
              // 更新
              if (trainForms.type === 'update') {
                trainForms.trainList.forEach((train: any) => {
                  if (train.id === item.id) {
                    train.trainingType = item.trainingType;
                    train.trainingConfigJson = item.trainingConfigJson;
                    train.typeList = tList;
                  }
                });
              } else {
                //
                trainForms.trainList.push({
                  ...item,
                  id: +new Date(),
                  musicName: trainForms.editItem.title,
                  typeList: tList
                });
              }
              trainForms.editItem = {};
            }}
          />
        </NModal>

        <NModal
          v-model:show={trainForms.selectMusicStatus}
          class={['modalTitle', styles.selectMusicModal]}
          preset="card"
          title={'选择曲目'}>
          <SelectMusic
            type="homework"
            onAdd={(item: any) => {
              trainForms.selectMusicStatus = false;
              onAdd(item);
            }}
          />
        </NModal>
      </div>
    );
  }
});
