import {
  defineComponent,
  onMounted,
  reactive,
  watch,
  PropType,
  onUnmounted,
  toRef
} from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NInput,
  NModal,
  NScrollbar,
  NSpace,
  NSpin,
  useDialog,
  useMessage
} from 'naive-ui';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import { useCatchStore } from '/src/store/modules/catchData';
import TrainType from '/src/views/attend-class/model/train-type';
import TheEmpty from '/src/components/TheEmpty';
import Draggable from 'vuedraggable';
import {
  lessonPreTrainingDelete,
  lessonPreTrainingV2Detail,
  lessonPreTrainingV2Save
} from '../../../api';
import { evaluateDifficult } from '/src/utils/contants';
import TrainUpdate from '/src/views/attend-class/model/train-update';
import AssignHomework from './assign-homework';
// import Trainguide from '@/custom-plugins/guide-page/train-guide';
import { eventGlobal } from '/src/utils';
// import iconTips from '../../../images/icon-tips.png';
import { typeFormat } from '../../resource-main/components/select-music';
import TheMessageDialog from '/src/components/TheMessageDialog';
import { useResizeObserver } from '@vueuse/core';
import useDrag from '@/hooks/useDrag';
import Dragbom from '@/hooks/useDrag/dragbom';
import { useUserStore } from '@/store/modules/users';
import { modalClickMask } from '/src/state';
export default defineComponent({
  name: 'courseware-modal',
  props: {
    lessonPreTraining: {
      type: Object,
      default: () => ({})
    },
    cardType: {
      type: String as PropType<'' | 'homeworkRecord' | 'prepare'>,
      default: ''
    },
    /** 编辑编号  - 目前从上传传 */
    classGroupId: {
      type: String,
      default: ''
    },
    /** 编辑编号  - 目前从上传传 */
    coursewareKnowledgeDetailId: {
      type: String,
      default: ''
    },
    /** 编辑编号  - 目前从上传传 */
    courseScheduleId: {
      type: String,
      default: ''
    },
    from: {
      // 来自哪里
      type: String,
      default: ''
    }
  },
  emits: ['change'],
  setup(props, { emit }) {
    console.log(props.courseScheduleId, 'courseScheduleId');
    // const catchStore = useCatchStore();
    const prepareStore = usePrepareStore();
    const dialog = useDialog();
    const message = useMessage();
    const forms = reactive({
      title: props.lessonPreTraining?.title,
      preBtnLoading: false,
      showAttendClass: false,
      list: [] as any,
      drag: true,
      loadingStatus: false,
      trainList: [] as any,
      assignHomeworkStatus: false,
      editStatus: false,
      editItem: {} as any,
      removeIds: [] as any, // 临时删除的编号
      removeVisiable1: false,
      preSaveVisiable: false
    });
    // const showGuide = ref(false);
    // 获取列表
    const getList = async () => {
      forms.loadingStatus = true;
      try {
        // 判断是否有选择对应的课件
        // console.log(props.lessonPreTraining, 'props.lessonPreTraining');
        if (!props.lessonPreTraining?.id) return (forms.loadingStatus = false);
        const { data } = await lessonPreTrainingV2Detail({
          id: props.lessonPreTraining?.id
        });
        const tempRows = data.lessonPreTrainingDetails || [];
        const temp: any = [];
        forms.title = data.title;
        tempRows.forEach((row: any) => {
          let tList: string[] = [];
          const configJson = row.trainingConfigJson;
          if (row.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}分钟`
            ];
          }
          temp.push({
            typeList: tList || [],
            audioPlayTypeArray: row.audioPlayTypes
              ? row.audioPlayTypes.split(',')
              : [],
            ...row
          });
        });

        prepareStore.setTrainList(temp || []);
        const tempCourse: any = [];
        temp.forEach((item: any) => {
          if (!forms.removeIds.includes(item.id)) {
            tempCourse.push(item);
          }
        });
        forms.trainList = tempCourse || [];
      } catch {
        //
      }
      forms.loadingStatus = false;
    };

    // 监听选择的key 左侧选择了其它的课
    watch(
      () => prepareStore.getSelectKey,
      () => {
        eventGlobal.emit('teacher-slideshow', false);
        emit('change', { status: false });
        forms.trainList = [];
        getList();
      }
    );
    // 删除
    const onDelete = (item: any) => {
      forms.removeIds.push(item.id);
      const index = forms.trainList.findIndex((c: any) => c.id === item.id);
      forms.trainList.splice(index, 1);
    };

    // 单个删除
    const onRemove = async (item: any) => {
      try {
        dialog.warning({
          title: '提示',
          content: '该训练已下架，是否删除？',
          positiveText: '确定',
          negativeText: '取消',
          maskClosable: false,
          onPositiveClick: async () => {
            forms.removeIds.push(item.id);
            await lessonPreTrainingDelete({ ids: item.id });
            message.success('删除成功');
            getList();
          }
        });
      } catch {
        //
      }
    };

    /** 保存预设 */
    const onPreSave = async () => {
      forms.preBtnLoading = true;
      try {
        const lessonPreTrainingDetails: any = [];
        forms.trainList.forEach((item: any) => {
          lessonPreTrainingDetails.push({
            trainingType: item.trainingType,
            musicId: item.musicId,
            trainingConfigJson: item.trainingConfigJson,
            musicName: item.musicName
          });
        });
        const { data } = await lessonPreTrainingV2Save({
          title: forms.title,
          id: props.lessonPreTraining?.id,
          coursewareKnowledgeDetailId:
            props.coursewareKnowledgeDetailId || prepareStore.getSelectKey,
          lessonPreTrainingDetails,
          courseScheduleId: props.courseScheduleId,
          chapterLessonCoursewareId: props.lessonPreTraining?.chapterId
        });
        message.success('保存成功');
        prepareStore.setIsEditTrain(false);
        forms.removeIds = [];
        // getList();
        emit('change', {
          status: false,
          saveWork: true,
          lessonPreTrainingId: data.id
        });
      } catch {
        //
      }
      forms.preBtnLoading = false;
    };

    const getModalHeight = () => {
      const dom: any = document.querySelector('#model-homework-height');
      if (dom) {
        useResizeObserver(dom as HTMLElement, (entries: any) => {
          const entry = entries[0];
          const { height } = entry.contentRect;
          dom.style.setProperty('--window-page-lesson-height', height + 'px');
        });
      }
    };

    onMounted(async () => {
      getModalHeight();
      await getList();
      // 动态添加数据
      eventGlobal.on('onTrainAddItem', (item: any) => {
        forms.drag = true;
        // 临时储存编号
        item.id = item.id || new Date().getTime() + '__tmp';
        forms.trainList.push(item);
        prepareStore.setTrainList(forms.trainList);
      });
    });

    onUnmounted(() => {
      forms.trainList = [];
      prepareStore.setTrainList([]);
    });
    // 弹窗拖动
    // 作业设置
    let workSetingBoxDragData: any;
    let workSetingBoxClass: string;
    if (props.from === 'class') {
      const users = useUserStore();
      workSetingBoxClass = 'workSetingBoxClass_drag';
      workSetingBoxDragData = useDrag(
        [
          `${workSetingBoxClass}>.n-card-header`,
          `${workSetingBoxClass} .bom_drag`
        ],
        workSetingBoxClass,
        toRef(forms, 'editStatus'),
        users.info.id
      );
    }
    // 清空
    let workClearBoxDragData: any;
    let workClearBoxClass: string;
    if (props.from === 'class') {
      const users = useUserStore();
      workClearBoxClass = 'workClearBoxClass_drag';
      workClearBoxDragData = useDrag(
        [
          `${workClearBoxClass}>.n-card-header`,
          `${workClearBoxClass} .bom_drag`
        ],
        workClearBoxClass,
        toRef(forms, 'removeVisiable1'),
        users.info.id
      );
    }
    // 清空
    let workSaveBoxDragData: any;
    let workSaveBoxClass: string;
    if (props.from === 'class') {
      const users = useUserStore();
      workSaveBoxClass = 'workSaveBoxClass_drag';
      workSaveBoxDragData = useDrag(
        [`${workSaveBoxClass}>.n-card-header`, `${workSaveBoxClass} .bom_drag`],
        workSaveBoxClass,
        toRef(forms, 'preSaveVisiable'),
        users.info.id
      );
    }
    // 立即布置
    let workArrangeImmediatelyBoxDragData: any;
    let workArrangeImmediatelyBoxClass: string;
    if (props.from === 'class') {
      const users = useUserStore();
      workArrangeImmediatelyBoxClass = 'workArrangeImmediatelyBoxClass_drag';
      workArrangeImmediatelyBoxDragData = useDrag(
        [
          `${workArrangeImmediatelyBoxClass}>.n-card-header`,
          `${workArrangeImmediatelyBoxClass} .bom_drag`
        ],
        workArrangeImmediatelyBoxClass,
        toRef(forms, 'assignHomeworkStatus'),
        users.info.id
      );
    }
    return () => (
      <div class={styles.coursewareModal}>
        <div class={styles.btnGroup}>
          <NSpace>
            <div class={styles.btnItem}>
              <span class={styles.btnTitle}>
                <i style={{ color: '#ea4132', fontStyle: 'normal' }}>*</i>标题：
              </span>
              <NInput
                placeholder={'请输入标题'}
                v-model:value={forms.title}
                maxlength={100}
              />
            </div>
          </NSpace>

          <div class={styles.spaceBtnGroup}>
            <NButton
              bordered={false}
              type="error"
              disabled={forms.trainList.length <= 0}
              onClick={() => {
                forms.removeVisiable1 = true;
              }}>
              清空
            </NButton>
            <NButton
              bordered={false}
              type="error"
              onClick={() => {
                // forms.drag = false;
                prepareStore.setIsEditTrain(false);
                forms.removeIds = [];
                // prepareStore.setTrainList([]);
                // getList();
                emit('change', { status: false });
              }}>
              取消
            </NButton>

            {(props.cardType !== 'homeworkRecord' ||
              props.courseScheduleId) && (
              <NButton
                bordered={false}
                type="default"
                onClick={() => {
                  if (!forms.title) {
                    message.error('请输入标题');
                    return;
                  }
                  // let count = 0;
                  // forms.trainList.forEach((item: any) => {
                  //   if (!item.removeFlag) {
                  //     count++;
                  //   }
                  // });
                  // if (count <= 0) {
                  //   message.error('作业内容不能为空');
                  //   return;
                  // }

                  forms.preSaveVisiable = true;
                }}
                // loading={forms.preBtnLoading}
              >
                保存
              </NButton>
            )}
            {(props.cardType === 'homeworkRecord' ||
              props.courseScheduleId) && (
              <NButton
                type="primary"
                disabled={forms.trainList.length <= 0}
                onClick={() => {
                  if (!forms.title) {
                    message.error('请输入标题');
                    return;
                  }
                  let count = 0;
                  forms.trainList.forEach((item: any) => {
                    if (!item.removeFlag) {
                      count++;
                    }
                  });
                  if (count <= 0) {
                    message.error('作业内容不能为空');
                    return;
                  }
                  forms.assignHomeworkStatus = true;
                }}>
                立即布置
              </NButton>
            )}
          </div>
        </div>

        <NScrollbar
          class={[
            styles.listContainer,
            'train-container'
            // forms.drag ? styles.listContainerDrag : ''
          ]}>
          <NSpin show={forms.loadingStatus}>
            <div
              class={[
                styles.listSection,
                'train-listSection',
                !forms.loadingStatus && prepareStore.getTrainList.length <= 0
                  ? styles.emptySection
                  : ''
              ]}
              onDragenter={(e: any) => {
                e.preventDefault();
              }}
              onDragover={(e: any) => {
                e.preventDefault();
              }}
              onDrop={(e: any) => {
                let dropItem = e.dataTransfer.getData('text');
                // console.log(dropItem, 'dropItem', dropItem);
                dropItem = dropItem ? JSON.parse(dropItem) : {};
                // 判断是否有数据
                if (dropItem.id) {
                  eventGlobal.emit('onTrainDragItem', dropItem);
                }
              }}>
              {forms.trainList.length > 0 && (
                <Draggable
                  v-model:modelValue={forms.trainList}
                  itemKey="id"
                  componentData={{
                    itemKey: 'id',
                    tag: 'div',
                    animation: 200,
                    group: 'description',
                    disabled: false
                  }}
                  class={styles.list}>
                  {{
                    item: (element: any) => {
                      const item = element.element;
                      return (
                        <div data-id={item.musicId} class={styles.itemBlock}>
                          <TrainType
                            from={props.from}
                            item={item}
                            isDelete
                            type="prepare"
                            onDelete={(child: any) => onDelete(child)}
                            offShelf={item.removeFlag ? true : false}
                            onOffShelf={() => onRemove(item)}
                            onEdit={(child: any) => {
                              // console.log(forms.trainList);
                              const {
                                trainingConfigJson,
                                id,
                                musicId,
                                ...res
                              } = child;
                              forms.editItem = {
                                ...res,
                                id: musicId,
                                trainId: id,
                                ...trainingConfigJson
                              };
                              forms.editStatus = true;
                            }}
                          />
                        </div>
                      );
                    }
                  }}
                </Draggable>
              )}

              {!forms.loadingStatus &&
                prepareStore.getTrainList.length <= 0 && (
                  <TheEmpty description="暂无作业" />
                )}
            </div>
          </NSpin>
        </NScrollbar>

        {/* 编辑 */}
        <NModal
          maskClosable={modalClickMask}
          style={
            props.from === 'class' ? workSetingBoxDragData.styleDrag.value : {}
          }
          v-model:show={forms.editStatus}
          class={[
            'modalTitle background',
            styles.trainEditModal,
            workSetingBoxClass
          ]}
          preset="card"
          title="作业设置">
          <TrainUpdate
            item={forms.editItem}
            onClose={() => (forms.editStatus = false)}
            onConfirm={(item: any) => {
              forms.editItem = {};
              // prepareStore.setIsAddTrain(true);

              const tList = typeFormat(
                item.trainingType,
                item.trainingConfigJson
              );
              //
              const train = {
                ...item,
                typeList: tList
              };

              forms.trainList.forEach((item: any) => {
                if (item.id === train.id) {
                  // item = train;
                  item.trainingConfigJson = train.trainingConfigJson;
                  item.trainingType = train.trainingType;
                  item.typeList = train.typeList;
                }
              });
              prepareStore.setTrainList(forms.trainList);
            }}
          />
          {props.from === 'class' && <Dragbom></Dragbom>}
        </NModal>

        {/* 添加自定义教材 */}
        <NModal
          maskClosable={modalClickMask}
          style={
            props.from === 'class'
              ? workArrangeImmediatelyBoxDragData.styleDrag.value
              : {}
          }
          v-model:show={forms.assignHomeworkStatus}
          preset="card"
          showIcon={false}
          class={[
            'modalTitle background',
            styles.assignHomework,
            workArrangeImmediatelyBoxClass
          ]}
          title={'布置作业'}
          blockScroll={false}>
          <AssignHomework
            from={props.from}
            classGroupId={props.classGroupId}
            courseScheduleId={props.courseScheduleId}
            chapterLessonCoursewareId={props.lessonPreTraining.chapterId}
            homeworkType={props.courseScheduleId ? 'HOMEWORK' : 'CLASSWORK'}
            item={{
              title: forms.title,
              lessonPreTrainingDetails: forms.trainList
            }}
            // trainList={forms.trainList}
            onClose={() => (forms.assignHomeworkStatus = false)}
            onConfirm={() => {
              if (props.cardType === 'homeworkRecord') {
                forms.trainList = [];
                prepareStore.setTrainList([]);
                emit('change', { state: false });
              }
            }}
          />
          {props.from === 'class' && <Dragbom></Dragbom>}
        </NModal>

        {/* {showGuide.value ? <Trainguide></Trainguide> : null} */}

        <NModal
          maskClosable={modalClickMask}
          style={
            props.from === 'class' ? workClearBoxDragData.styleDrag.value : {}
          }
          v-model:show={forms.removeVisiable1}
          preset="card"
          class={['modalTitle', styles.removeVisiable1, workClearBoxClass]}
          title={'清空资源'}>
          <div class={styles.studentRemove}>
            <p>
              请确认是否要清空作业？
              {/* <span>点击确认后所有的作业内容 将被清空掉。</span> */}
            </p>

            <NSpace class={styles.btnGroupModal} justify="center">
              <NButton
                round
                type="primary"
                onClick={() => {
                  forms.trainList.forEach((item: any) => {
                    forms.removeIds.push(item.id);
                  });
                  forms.trainList = [];
                  prepareStore.setTrainList([]);
                  forms.removeVisiable1 = false;
                }}>
                确定
              </NButton>
              <NButton round onClick={() => (forms.removeVisiable1 = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
          {props.from === 'class' && <Dragbom></Dragbom>}
        </NModal>

        <NModal
          maskClosable={modalClickMask}
          style={
            props.from === 'class' ? workSaveBoxDragData.styleDrag.value : {}
          }
          v-model:show={forms.preSaveVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable1, workSaveBoxClass]}
          title={'保存'}>
          <TheMessageDialog
            content="是否保存当前页面编辑内容？"
            cancelButtonText="取消"
            confirmButtonText="保存"
            onClose={() => (forms.preSaveVisiable = false)}
            onConfirm={() => onPreSave()}
          />
          {props.from === 'class' && <Dragbom></Dragbom>}
        </NModal>
      </div>
    );
  }
});
