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
} from '../../api';
import { NModal, NSpin, useDialog, useMessage } from 'naive-ui';
import TheEmpty from '/src/components/TheEmpty';
import UploadModal from './upload-modal';
import CardPreview from '@/components/card-preview';
import resourceDefault from '../../images/resource-default.svg';
import resourceChecked from '../../images/resource-checked.svg';
import MyResourcesGuide from '@/custom-plugins/guide-page/myResources-guide';
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: '', //
        name: '',
        bookVersionId: null,
        subjectId: null,
        sourceType: 3
      },
      tableList: [] as any,
      uploadStatus: false,
      show: false,
      item: {} as any,
      editStatus: false, // 是否编辑
      editList: [] as any, // TOD
      editIds: [] 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,
            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.editIds.length <= 0) {
          message.error('至少选择一条资源进行删除');
          return;
        }
        dialog.warning({
          title: '提示',
          content: '你确定删除该资源？',
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: async () => {
            await materialRemoveAll(state.editIds);
            message.success('删除成功');
            onSearch(state.searchGroup);
            state.editIds = [];
          }
        });
      } catch {
        //
      }
    };

    // 单个删除
    const onRemove = async (item: any) => {
      try {
        dialog.warning({
          title: '提示',
          content: '该资源已下架，是否删除？',
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: async () => {
            await materialRemove({ id: item.id });
            message.success('删除成功');
            onSearch(state.searchGroup);
          }
        });
      } catch {
        //
      }
    };

    onMounted(() => {
      getList();
    });
    return () => (
      <>
        <SearchGroupResources
          onSearch={(item: any) => onSearch(item)}
          onUpload={() => {
            state.editList = [];
            state.uploadStatus = 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={onDelete}
        />

        <NSpin v-model:show={state.loading} style={{ 'min-height': '50vh' }}>
          <div class={styles.list}>
            {state.tableList.map((item: any) => (
              <div class={styles.itemSection}>
                <CardType
                  item={item}
                  disabledMouseHover={false}
                  offShelf={item.enableFlag ? false : true}
                  onOffShelf={() => onRemove(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>
            ))}

            {!state.loading && state.tableList.length <= 0 && (
              <TheEmpty 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 = [];
              onSearch(state.searchGroup);
            }}
            list={state.editList}
          />
        </NModal>
        {showGuide.value ? <MyResourcesGuide></MyResourcesGuide> : null}
      </>
    );
  }
});
