import { defineComponent, onMounted, reactive, watch, ref } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NModal,
  NScrollbar,
  NSelect,
  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 {
  lessonPreTrainingBatchSave,
  lessonPreTrainingPage,
  lessonPreTrainingDelete
} 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';
export default defineComponent({
  name: 'courseware-modal',
  setup() {
    const catchStore = useCatchStore();
    const prepareStore = usePrepareStore();
    const dialog = useDialog();
    const message = useMessage();
    const forms = reactive({
      showAttendClass: false,
      list: [] as any,
      drag: false,
      loadingStatus: false,
      trainList: [] as any,
      assignHomeworkStatus: false,
      editStatus: false,
      editItem: {} as any,
      removeIds: [] as any, // 临时删除的编号
      removeVisiable: false,
      removeVisiable1: false
    });
    const showGuide = ref(false);
    // 完成编辑
    const onOverEdit = async () => {
      // dialog.warning({
      //   title: '提示',
      //   content: `是否完成编辑？`,
      //   positiveText: '确定',
      //   negativeText: '取消',
      //   onPositiveClick: async () => {
      try {
        // 保存课件
        await lessonPreTrainingBatchSave({
          coursewareKnowledgeDetailId: prepareStore.getSelectKey,
          subjectId: prepareStore.getSubjectId,
          lessonPreTrainingDetails: forms.trainList
        });

        forms.drag = false;
        message.success('编辑成功');
        forms.removeVisiable = false;
        prepareStore.setCoursewareList(forms.trainList);
        prepareStore.setIsEditTrain(false);
        // 重置临时删除编号
        forms.removeIds = [];
      } catch {
        //
      }
      // }
      // });
    };

    // 获取列表
    const getList = async () => {
      forms.loadingStatus = true;
      try {
        // 判断是否有选择对应的课件
        if (!prepareStore.getSelectKey) return;
        const { data } = await lessonPreTrainingPage({
          coursewareKnowledgeDetailId: prepareStore.getSelectKey,
          subjectId: prepareStore.getSubjectId,
          page: 1,
          rows: 99
        });
        const tempRows = data.rows || [];
        const temp: any = [];

        tempRows.forEach((row: any) => {
          let tList: string[] = [];
          const configJson = row.trainingConfigJson;
          if (row.trainingType === 'EVALUATION') {
            tList = [
              `${evaluateDifficult[configJson.evaluateDifficult]}`,
              '全部小节',
              // `速度${configJson.evaluateSpeed}`,
              `${configJson.trainingTimes}分合格`
            ];
          } else {
            tList = [
              `${configJson.practiceChapterBegin}-${configJson.practiceChapterEnd}小节`,
              `速度${configJson.practiceSpeed}`,
              `${configJson.trainingTimes}分钟`
            ];
          }
          temp.push({
            typeList: tList || [],
            ...row
          });
        });

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

    // 声部变化时
    watch(
      () => prepareStore.getSubjectId,
      () => {
        getList();
      }
    );
    // 监听选择的key 左侧选择了其它的课
    watch(
      () => prepareStore.getSelectKey,
      () => {
        forms.trainList = [];
        getList();
      }
    );
    watch(
      () => prepareStore.getIsAddTrain,
      (val: boolean) => {
        if (val) {
          forms.trainList = [];
          getList();
          prepareStore.setIsAddTrain(false);
        }
      }
    );

    // 删除
    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);
      // prepareStore.setCoursewareList(forms.trainList);
    };

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

    // const checkSubjectIds = () => {
    //   const subjectList = prepareStore.getSubjectList;

    //   // 并且没有声部时才会更新
    //   if (subjectList.length > 0) {
    //     // 判断浏览器上面是否有
    //     const index = subjectList.findIndex(
    //       (subject: any) => subject.id == forms.subjectId
    //     );

    //     // 并且声部在列表中
    //     if (forms.subjectId && index >= 0) {
    //       prepareStore.setSubjectId(forms.subjectId);
    //     } else {
    //       // 判断是否有缓存
    //       prepareStore.setSubjectId(subjectList[0].id);
    //     }
    //   }
    // };

    onMounted(async () => {
      // 获取教材分类列表
      // await catchStore.getSubjects();

      // const subjectList = catchStore.getSubjectList;
      // if (subjectList.length > 0 && !prepareStore.getSubjectId) {
      //   prepareStore.setSubjectId(subjectList[0].id);
      // }
      // 获取教材分类列表
      // checkSubjectIds();

      await getList();
    });
    return () => (
      <div class={styles.coursewareModal}>
        <div class={styles.btnGroup}>
          {forms.drag ? (
            <NSpace>
              <NButton
                type="default"
                onClick={() => {
                  forms.removeVisiable = true;
                }}>
                完成编辑
              </NButton>
              <NButton
                type="error"
                onClick={() => {
                  forms.drag = false;
                  prepareStore.setIsEditTrain(false);
                  forms.removeIds = [];
                  getList();
                }}>
                取消编辑
              </NButton>
              <NButton
                type="error"
                onClick={() => {
                  // forms.trainList = [];
                  // prepareStore.setTrainList([]);
                  forms.removeVisiable1 = true;
                }}>
                清空资源
              </NButton>
              <span class={styles.tips}>拖动可将资源进行排序</span>
            </NSpace>
          ) : (
            <NSpace>
              {/* <NSelect
                placeholder="选择声部"
                options={catchStore.getSubjectList}
                labelField="name"
                valueField="id"
                value={prepareStore.getSubjectId}
                onUpdate:value={(val: any) => {
                  prepareStore.setSubjectId(val);
                }}
              /> */}
              <div class={styles.btnItem}>
                <span class={styles.btnTitle}>声部：</span>
                <NSelect
                  placeholder="选择声部"
                  class={styles.btnSubjectList}
                  options={prepareStore.getSubjectList}
                  labelField="name"
                  valueField="id"
                  value={prepareStore.getSubjectId}
                  onUpdate:value={(val: any) => {
                    prepareStore.setSubjectId(val);
                  }}
                />
              </div>
              <NButton
                type="default"
                onClick={() => {
                  forms.drag = true;
                  prepareStore.setIsEditTrain(true);
                }}>
                编辑
              </NButton>
            </NSpace>
          )}

          <NSpace>
            <NButton
              type="primary"
              {...{ id: 'train-0' }}
              disabled={forms.drag}
              onClick={() => {
                let count = 0;
                forms.trainList.forEach((item: any) => {
                  if (!item.removeFlag) {
                    count++;
                  }
                });
                if (count <= 0) {
                  message.error('作业内容不能为空');
                  return;
                }
                forms.assignHomeworkStatus = true;
              }}>
              布置作业
            </NButton>
          </NSpace>
        </div>

        <NScrollbar class={styles.listContainer}>
          <NSpin show={forms.loadingStatus}>
            <div
              class={[
                styles.listSection,
                !forms.loadingStatus && prepareStore.getTrainList.length <= 0
                  ? styles.emptySection
                  : ''
              ]}>
              {forms.trainList.length > 0 && (
                <>
                  {forms.drag ? (
                    <Draggable
                      v-model:modelValue={forms.trainList}
                      itemKey="id"
                      // tag="transition-group"
                      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.id} class={styles.itemBlock}>
                              <TrainType
                                item={item}
                                isDelete
                                type="prepare"
                                onDelete={(child: any) => onDelete(child)}
                                offShelf={item.removeFlag ? true : false}
                                onOffShelf={() => onRemove(item)}
                              />
                            </div>
                          );
                        }
                      }}
                    </Draggable>
                  ) : (
                    <div class={styles.list}>
                      {forms.trainList.map((item: any) => (
                        <TrainType
                          item={item}
                          type="prepare"
                          offShelf={item.removeFlag ? true : false}
                          onOffShelf={() => onRemove(item)}
                          onEdit={(child: any) => {
                            console.log('edit', child);
                            const { trainingConfigJson, id, musicId, ...res } =
                              child;
                            forms.editItem = {
                              ...res,
                              id: musicId,
                              trainId: id,
                              ...trainingConfigJson
                            };
                            forms.editStatus = true;
                          }}
                        />
                      ))}
                    </div>
                  )}
                </>
              )}

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

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

        {/* 添加自定义教材 */}
        <NModal
          v-model:show={forms.assignHomeworkStatus}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.assignHomework]}
          title={'布置作业'}
          blockScroll={false}>
          <AssignHomework
            trainList={forms.trainList}
            onClose={() => (forms.assignHomeworkStatus = false)}
          />
        </NModal>
        {showGuide.value ? <Trainguide></Trainguide> : null}

        <NModal
          v-model:show={forms.removeVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable]}
          title={'提示'}>
          <div class={styles.studentRemove}>
            <p>是否完成编辑？</p>

            <NSpace class={styles.btnGroupModal} justify="center">
              <NButton round type="primary" onClick={onOverEdit}>
                确定
              </NButton>
              <NButton round onClick={() => (forms.removeVisiable = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
        </NModal>

        <NModal
          v-model:show={forms.removeVisiable1}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          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 = [];
                  forms.removeVisiable1 = false;
                  // prepareStore.setCoursewareList([]);

                  console.log(prepareStore.getTrainList, 'getCourseware1');
                }}>
                确定
              </NButton>
              <NButton round onClick={() => (forms.removeVisiable1 = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
        </NModal>
      </div>
    );
  }
});
