import { defineComponent, onMounted, reactive, watch } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NImage,
  NInput,
  NModal,
  NScrollbar,
  NSpace,
  NSpin,
  useMessage
} from 'naive-ui';
import { useUserStore } from '@/store/modules/users';
import add from '@/views/studentList/images/add.png';
import WorkSection from '../../../model/work-section';
import { eventGlobal } from '/src/utils';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import {
  lessonPreTrainingV2Page,
  lessonPreTrainingV2Remove,
  lessonPreTrainingV2Save
} from '../../../api';
import { storeToRefs } from 'pinia';
import AssignHomework from '../train/assign-homework';
import TheEmpty from '/src/components/TheEmpty';
import { modalClickMask } from '/src/state';

export default defineComponent({
  name: 'train-presets',
  emits: ['change'],
  setup(props, { emit }) {
    const prepareStore = usePrepareStore();
    const users = useUserStore();
    const { info } = storeToRefs(users);
    const message = useMessage();
    const forms = reactive({
      assignHomeworkStatus: false,
      editTitleVisiable: false,
      editTitle: '',
      editBtnLoading: false,
      selectItem: {} as any,
      removeVisiable1: false,
      loadingStatus: false,
      tableList: [] as any
    });

    const getList = async () => {
      forms.loadingStatus = true;
      try {
        // 判断是否有选择对应的课件 或声部
        if (!prepareStore.getSelectKey) return (forms.loadingStatus = false);
        const { data } = await lessonPreTrainingV2Page({
          page: 1,
          coursewareKnowledgeDetailId: prepareStore.getSelectKey
        });
        const result = data.rows || [];
        const tempList: any = [];
        result.forEach((item: any) => {
          const { lessonPreTrainingDetails, ...ies } = item;
          const tList: any = {
            ...ies,
            pTitle: '',
            eTitle: '',
            teacherAvatar: info.value?.avatar,
            teacherName: info.value?.nickname,
            lessonPreTrainingDetails
          };
          lessonPreTrainingDetails.forEach((child: any) => {
            if (child.trainingType === 'PRACTICE' && child.musicName) {
              tList.pTitle += tList.pTitle
                ? '、《' + child.musicName + '》'
                : '练习曲目《' + child.musicName + '》';
            }
            if (child.trainingType === 'EVALUATION' && child.musicName) {
              tList.eTitle += tList.eTitle
                ? '、《' + child.musicName + '》'
                : '评测曲目《' + child.musicName + '》';
            }
          });

          tempList.push(tList);
        });

        forms.tableList = tempList;
      } catch {
        //
      }
      forms.loadingStatus = false;
    };
    // 监听选择的key 左侧选择了其它的课
    watch(
      () => prepareStore.getSelectKey,
      () => {
        // forms.drag = false;
        // prepareStore.setIsEditResource(false);
        getList();
      }
    );

    /** 修改标题 */
    const onEditTitleSubmit = async () => {
      if (!forms.editTitle) {
        message.error('请输入作业标题');
        return;
      }
      forms.editBtnLoading = true;
      try {
        await lessonPreTrainingV2Save({
          id: forms.selectItem.id,
          title: forms.editTitle
        });
        message.success('修改成功');
        forms.editTitleVisiable = false;
        forms.tableList.forEach((item: any) => {
          if (item.id === forms.selectItem.id) {
            item.title = forms.editTitle;
          }
        });
      } catch {
        //
      }
      forms.editBtnLoading = false;
    };

    /** 删除 */
    const onRemove = async () => {
      forms.editBtnLoading = true;
      try {
        await lessonPreTrainingV2Remove({ id: forms.selectItem.id });
        message.success('删除成功');
        forms.removeVisiable1 = false;
        getList();
      } catch {
        //
      }
      forms.editBtnLoading = false;
    };

    onMounted(() => {
      getList();
    });
    return () => (
      <div class={styles.trainPresets}>
        <div class={styles.btnGroup}>
          <NSpace>
            <NButton
              type="primary"
              class={styles.addPreset}
              onClick={() => {
                // 设置右侧栏状态
                eventGlobal.emit('teacher-slideshow', true);
                emit('change', { status: true });
              }}
              v-slots={{
                icon: () => (
                  <>
                    <NImage
                      class={styles.addBtnIcon}
                      previewDisabled
                      src={add}></NImage>
                  </>
                )
              }}>
              添加作业预设
            </NButton>
          </NSpace>
        </div>

        <NScrollbar class={[styles.listContainer]}>
          <NSpin show={forms.loadingStatus}>
            <div
              class={[
                styles.listSection,
                !forms.loadingStatus && forms.tableList.length <= 0
                  ? styles.emptySection
                  : ''
              ]}>
              <div class={[styles.list]}>
                {forms.tableList.map((item: any) => (
                  <WorkSection
                    item={item}
                    onEditTitle={() => {
                      forms.selectItem = item;
                      forms.editTitle = item.title;
                      forms.editTitleVisiable = true;
                    }}
                    onEdit={() => {
                      // 设置右侧栏状态
                      eventGlobal.emit('teacher-slideshow', true);
                      emit('change', {
                        status: true,
                        lessonPreTraining: item
                      });
                    }}
                    onConfirm={() => {
                      //
                      if (
                        !item.lessonPreTrainingDetails ||
                        item.lessonPreTrainingDetails.length <= 0
                      ) {
                        message.error('作业预设不能为空');
                        return;
                      }
                      let count = 0;
                      item.lessonPreTrainingDetails?.forEach((item: any) => {
                        if (!item.removeFlag) {
                          count++;
                        }
                      });
                      if (count <= 0) {
                        message.error('作业内容不能为空');
                        return;
                      }
                      forms.assignHomeworkStatus = true;
                      forms.selectItem = item;
                    }}
                    onDelete={() => {
                      forms.removeVisiable1 = true;
                      forms.selectItem = item;
                    }}
                  />
                ))}
              </div>
              {!forms.loadingStatus && forms.tableList.length <= 0 && (
                <TheEmpty description="暂无作业" />
              )}
            </div>
          </NSpin>
        </NScrollbar>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.removeVisiable1}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          title={'删除作业'}>
          <div class={styles.studentRemove}>
            <p>请确认是否删除【{forms.selectItem.title}】，删除后不可恢复</p>

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

        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.editTitleVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          title={'作业重命名'}>
          <div class={styles.studentRemove}>
            <NInput
              placeholder="请输入作业标题"
              v-model:value={forms.editTitle}
              maxlength={100}
            />

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

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