import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import CardType from '/src/components/card-type';
import Pagination from '/src/components/pagination';
import SearchGroupResources from './search-group-resources';
import {
  favorite,
  materialQueryPage,
  materialRemove,
  materialRemoveAll,
  materialRemoveMusic
} from '../../api';
import {
  NButton,
  NModal,
  NSpace,
  NSpin,
  useDialog,
  useMessage
} from 'naive-ui';
import TheEmpty from '/src/components/TheEmpty';
import UploadModal, { formatUrlType } from './upload-modal';
import CardPreview from '@/components/card-preview';
import resourceDefault from '../../images/resource-default.png';
import resourceChecked from '../../images/resource-checked.png';
import MyResourcesGuide from '@/custom-plugins/guide-page/myResources-guide';
import SaveModal from './save-modal';
export default defineComponent({
  name: 'share-resources',
  setup() {
    const message = useMessage();
    const dialog = useDialog();
    const state = reactive({
      searchWord: '',
      loading: false,
      pageTotal: 0,
      pagination: {
        page: 1,
        rows: 20
      },
      searchGroup: {
        type: 'MUSIC', //
        name: '',
        bookVersionId: null,
        subjectId: null,
        sourceType: 3
      },
      tableList: [] as any,
      uploadStatus: false,
      saveStatus: false,
      show: false,
      item: {} as any,
      editStatus: false, // 是否编辑
      editList: [] as any, // TOD
      editIds: [] as any, // 编辑的
      removeVisiable: false,
      removeContent: '是否删除该资源？',
      type: 'remove',
      removeItem: {} as any
    });
    const showGuide = ref(false);
    const getList = async () => {
      try {
        state.loading = true;
        const { data } = await materialQueryPage({
          ...state.searchGroup,
          ...state.pagination
        });
        state.loading = false;
        state.pageTotal = Number(data.total);
        const tempRows = data.rows || [];
        const temp: any = [];
        tempRows.forEach((row: any) => {
          temp.push({
            id: row.id,
            coverImg: row.coverImg,
            type: row.type,
            title: row.name,
            isCollect: !!row.favoriteFlag,
            isSelected: row.sourceFrom === 'PLATFORM' ? true : false,
            content: row.content,
            subjectId: row.subjectIds,
            sourceFrom: row.sourceFrom,
            enableFlag: row.enableFlag ? 1 : 0,
            openFlag: row.openFlag
          });
        });
        state.tableList = temp || [];
        setTimeout(() => {
          showGuide.value = true;
        }, 500);
      } catch {
        state.loading = false;
      }
    };

    // 收藏
    const onCollect = async (item: any) => {
      try {
        await favorite({
          materialId: item.id,
          favoriteFlag: item.isCollect ? 0 : 1,
          type: item.type
        });
        item.isCollect = !item.isCollect;
      } catch {
        //
      }
    };

    const onSearch = async (item: any) => {
      state.pagination.page = 1;
      state.searchGroup = Object.assign(state.searchGroup, item);
      getList();
    };

    // 批量删除
    const onDelete = async () => {
      try {
        if (state.searchGroup.type === 'MUSIC') {
          await materialRemoveMusic(state.editIds);
        } else {
          await materialRemoveAll(state.editIds);
        }
        message.success('删除成功');
        onSearch(state.searchGroup);
        state.editIds = [];
      } catch {
        //
      }
    };

    // 单个删除
    const onRemove = async () => {
      try {
        // 如果是乐谱类型则使用其它删除接口
        if (state.searchGroup.type === 'MUSIC') {
          await materialRemoveMusic([state.removeItem.id]);
        } else {
          await materialRemove({ ids: state.removeItem.id });
        }

        message.success('删除成功');
        onSearch(state.searchGroup);
      } catch {
        //
      }
    };

    onMounted(() => {
      getList();
    });
    return () => (
      <>
        <SearchGroupResources
          onSearch={(item: any) => onSearch(item)}
          onUpload={() => {
            state.editList = [];
            // state.uploadStatus = true;
            state.saveStatus = true;
          }}
          onUpdate={() => {
            // 修改
            const list: any[] = [];
            state.tableList.forEach((item: any) => {
              if (state.editIds.indexOf(item.id) > -1) {
                list.push(item);
              }
            });
            state.editList = list || [];
            if (state.editList.length <= 0) {
              message.error('至少选择一条资源进行编辑');
              return;
            }
            state.uploadStatus = true;
          }}
          onEdit={(status: boolean) => {
            // 点击编辑
            state.editStatus = status;
            if (!state.editStatus) {
              state.editIds = [];
            }
          }}
          onSelectAll={(status: boolean) => {
            // 全选
            if (status) {
              const tempIds: any[] = [];
              state.tableList.forEach((item: any) => {
                tempIds.push(item.id);
              });
              state.editIds = tempIds;
            } else {
              state.editIds = [];
            }
          }}
          onDelete={() => {
            if (state.editIds.length <= 0) {
              message.error('至少选择一条资源进行删除');
              return;
            }
            state.type = 'delete';
            state.removeContent = '是否删除该资源？';
            state.removeVisiable = true;
          }}
        />

        <NSpin v-model:show={state.loading} style={{ 'min-height': '50vh' }}>
          <div class={styles.list}>
            {state.tableList.map((item: any) => (
              <div class={styles.itemWrap}>
                <div class={styles.itemWrapBox}>
                  <CardType
                    item={item}
                    disabledMouseHover={false}
                    offShelf={item.enableFlag ? false : true}
                    onOffShelf={() => {
                      state.type = 'remove';
                      state.removeContent = '该资源已下架，是否删除？';
                      state.removeVisiable = true;
                      state.removeItem = item;
                    }} // 下架
                    onClick={(val: any) => {
                      if (val.type === 'IMG' || !item.enableFlag) return;
                      state.show = true;
                      state.item = val;
                    }}
                    onCollect={(item: any) => onCollect(item)}
                  />
                  {/* 编辑模式 */}
                  {state.editStatus && (
                    <div
                      class={[
                        styles.itemBg,
                        state.editIds.includes(item.id)
                          ? styles.itemBgChecked
                          : ''
                      ]}
                      onClick={() => {
                        const index = state.editIds.indexOf(item.id);
                        if (index > -1) {
                          state.editIds.splice(index, 1);
                        } else {
                          state.editIds.push(item.id);
                        }
                      }}>
                      <img
                        src={
                          state.editIds.includes(item.id)
                            ? resourceChecked
                            : resourceDefault
                        }
                        class={styles.resourceDefault}
                      />
                    </div>
                  )}
                </div>
              </div>
            ))}

            {!state.loading && state.tableList.length <= 0 && (
              <TheEmpty style={{ minHeight: '50vh' }} description="暂无资源" />
            )}
          </div>
        </NSpin>

        <Pagination
          v-model:page={state.pagination.page}
          v-model:pageSize={state.pagination.rows}
          v-model:pageTotal={state.pageTotal}
          onList={getList}
        />

        {/* 弹窗查看 */}
        <CardPreview v-model:show={state.show} item={state.item} />

        <NModal
          v-model:show={state.uploadStatus}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.attendClassModal]}
          title={state.editStatus ? '修改资源' : '上传资源'}
          blockScroll={false}>
          <UploadModal
            onClose={() => (state.uploadStatus = false)}
            onConfirm={() => {
              state.editIds = [];
              state.editList = [];
              state.saveStatus = false;
              onSearch(state.searchGroup);
            }}
            list={state.editList}
          />
        </NModal>

        <NModal
          v-model:show={state.saveStatus}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.attendClassSaveModal]}
          title={'上传资源'}
          blockScroll={false}>
          <SaveModal
            onClose={() => (state.saveStatus = false)}
            onConfrim={(val: any) => {
              const list = val || [];
              const temp: any = [];
              list.forEach((item: any) => {
                temp.push({
                  subjectIds: null,
                  openFlag: false,
                  coverImg: item.coverImg,
                  title: item.name || '',
                  type: formatUrlType(item.content),
                  enableFlag: 1,
                  content: item.content,
                  id: null
                });
              });
              state.editList = temp;
              state.uploadStatus = true;
              state.editStatus = false;
            }}
          />
        </NModal>
        {showGuide.value ? <MyResourcesGuide></MyResourcesGuide> : null}

        <NModal
          v-model:show={state.removeVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable]}
          title={'提示'}>
          <div class={styles.studentRemove}>
            <p>{state.removeContent}</p>

            <NSpace class={styles.btnGroupModal} justify="center">
              <NButton
                round
                type="primary"
                onClick={() => {
                  if (state.type === 'remove') {
                    onRemove();
                  } else {
                    onDelete();
                  }
                  state.removeVisiable = false;
                }}>
                确定
              </NButton>
              <NButton round onClick={() => (state.removeVisiable = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
        </NModal>
      </>
    );
  }
});
