import { defineComponent, onMounted, reactive, ref } 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';
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: '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 showResetClass = ref(false);
    const setClassSubjects = ref<any[]>([]);
    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 || 0}-${configJson.practiceChapterEnd || 0}小节`,
          `速度${configJson.evaluateSpeed || 0}`,
          `${configJson.trainingTimes}分达标`
        ];
      } else {
        tList = [
          `${configJson.practiceChapterBegin}-${configJson.practiceChapterEnd}小节`,
          `速度${configJson.practiceSpeed || 0}`,
          `${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');
        /**
         * 妙极客的曲子，systems中含有part标签，需过滤掉systems标签，xmlParse.querySelectorAll('systems')
         */
        const systems = Array.from(xmlParse?.querySelectorAll('systems')) || [];
        systems.forEach((system: any) => {
          const childs = Array.from(system?.querySelectorAll('system')) || [];
          childs.forEach((child: any) => {
            system?.removeChild(child);
          })
        });
        const parts = xmlParse.getElementsByTagName('part');
        firstMeasures = parts[0]?.getElementsByTagName('measure');
        xmlStatus = 'success';
      } catch (error) {
        xmlStatus = 'error';
      }

      // 判断读取小节数
      if (xmlStatus == 'success') {
        // 标记xml是否是从0小节开始
        item.firstMeasureIsZero = firstMeasures?.[0]?.getAttribute('number') === '0';
        item.practiceChapterMax = item.firstMeasureIsZero ? firstMeasures.length - 1 : firstMeasures.length;
      } else {
        item.practiceChapterMax = 0;
      }
      item.coursewareKnowledgeDetailId = props.detailId;
      item.subjectId = props.subjectId;

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

    const tipDialog = reactive({
      show: false,
      msg:"",
      confirmButtonText:"",
      cancelBtn: false,
      type: "CLASS" as "CLASS"|"PERSON"|"MUSIC"
    })
    function handleLessonAddErr(data:any){
      const { type, errList } = data
      tipDialog.type = type
      // 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("")
      // }
      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.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 () => {
      // 训练内容不能为空
      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
        };
        const lessonRes =  await lessonTrainingAdd(params);
        if (lessonRes.code === 200){
          if (lessonRes.data.status){
            message.success('布置成功');
            emit('close');
            emit('confirm');
          } else {
            handleLessonAddErr(lessonRes.data)
          }
        }
      } 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
          maskClosable={modalClickMask}
          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
          maskClosable={modalClickMask}
          v-model:show={trainForms.selectMusicStatus}
          class={['modalTitle', styles.selectMusicModal]}
          preset="card"
          title={'选择曲目'}>
          <SelectMusic
            type="homework"
            onAdd={(item: any) => {
              trainForms.selectMusicStatus = false;
              onAdd(item);
            }}
          />
        </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}
            onClose={() => (showResetClass.value = false)}
          />
        </NModal>
      </div>
    );
  }
});
