import { computed, 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,
  materialUpdateAll
} 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';
import { modalClickMask } from '/src/state';
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: '',
        materialTagId: null, // 标签
        bookVersionId: null,
        musicalInstrumentId: null,
        subjectId: null,
        sourceType: 3
      },
      tableList: [] as any,
      uploadStatus: false,
      saveStatus: false,
      show: false,
      item: {} as any,
      editStatus: false, // 是否编辑
      isAdd: false,
      editList: [] as any, // TOD
      editIds: [] as any, // 编辑的
      editOverIds: [] 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,
            refFlag: row.refFlag,
            content: row.content,
            // subjectId: row.subjectIds,
            instrumentIds: row.instrumentIds,
            sourceFrom: row.sourceFrom,
            background: row.background,
            tagIds: row.tagIds, // 资源标签
            audioPlayTypeArray: row.audioPlayTypes
              ? row.audioPlayTypes.split(',')
              : [],
            enableFlag: row.enableFlag ? 1 : 0,
            openFlag: row.openFlag
          });
        });
        state.tableList = temp || [];
        // setTimeout(() => {
        //   showGuide.value = true;
        // }, 500);
      } catch {
        state.loading = false;
      }
    };

    const isEmpty = computed(() => {
      const list = state.tableList || [];
      let num = 0;
      list.forEach((item: any) => {
        if (!item.delFlag) {
          num++;
        }
      });
      return num > 0 ? false : true;
    });

    // 收藏
    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;

      const { subjectId, ...res } = item;
      state.searchGroup = Object.assign(state.searchGroup, {
        ...res,
        musicalInstrumentId: subjectId,
        subjectId: null
      });

      getList();
    };

    // 批量删除
    const onDelete = async () => {
      try {
        if (state.searchGroup.type === 'MUSIC') {
          await materialRemoveMusic(state.editIds);
        } else {
          await materialRemoveAll(state.editIds);
        }
        // message.success('删除成功');
        // state.pagination.page = 1;
        // getList();
        // 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 {
        //
      }
    };
    const searchGroupResourcesRef = ref();
    onMounted(() => {
      // getList();
    });
    return () => (
      <>
        <SearchGroupResources
          ref={searchGroupResourcesRef}
          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 && item.delFlag !== 1) {
                list.push(item);
              }
            });
            state.editList = list || [];
            if (state.editList.length <= 0) {
              message.error('至少选择一条资源进行编辑');
              return;
            }
            state.uploadStatus = true;
            state.isAdd = false;
          }}
          onEditOver={async (status: boolean) => {
            state.editStatus = status;
            try {
              // 修改
              if (state.editOverIds.length > 0) {
                const body = [] as any;
                state.tableList.forEach((item: any) => {
                  if (state.editOverIds.includes(item.id)) {
                    body.push({
                      instrumentIds: item.instrumentIds,
                      openFlag: item.openFlag,
                      coverImg: item.coverImg,
                      name: item.title,
                      type: item.type,
                      enableFlag: 1,
                      content: item.content,
                      tagIds: item.tagIds,
                      id: item.id || null,
                      delFlag: item.delFlag
                    });
                  }
                });
                //
                console.log(body, "body")
                if (body.length > 0) {
                  if (state.searchGroup.type === 'MUSIC') {
                    await materialRemoveMusic(state.editIds);
                  } else {
                    await materialUpdateAll(body);
                  }
                }
              }
              message.success('修改成功');
              state.pagination.page = 1;
              getList();
              state.editIds = [];
              state.editOverIds = [];
            } catch {
              //
            }
          }}
          onCancel={status => {
            state.editStatus = status;
            state.pagination.page = 1;
            state.editIds = [];
            state.editOverIds = [];
            getList();
          }}
          onEdit={async (status: boolean) => {
            // 点击编辑
            state.editStatus = status;

            if (!state.editStatus) {
              state.editIds = [];
              state.editOverIds = [];
            }
          }}
          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) =>
                item.delFlag !== 1 && (
                  <div class={styles.itemWrap}>
                    <div class={styles.itemWrapBox}>
                      <CardType
                        item={item}
                        isDownload
                        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 = {
                            instrumentId:
                              state.searchGroup.musicalInstrumentId || null,
                            ...val
                          };
                          console.log(state.item, 'item');
                        }}
                        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 && isEmpty.value && (
              <TheEmpty style={{ minHeight: '50vh' }} description="暂无资源" />
            )}
          </div>
        </NSpin>

        <Pagination
          disabled={state.editStatus}
          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
          maskClosable={modalClickMask}
          v-model:show={state.uploadStatus}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.attendClassModal]}
          title={state.editStatus ? '修改资源' : '上传资源'}
          blockScroll={false}>
          <UploadModal
            editStatus={state.editStatus}
            onClose={() => {
              state.uploadStatus = false;
            }}
            onConfirm={() => {
              state.editIds = [];
              state.editList = [];
              state.editOverIds = [];
              state.saveStatus = false;
              searchGroupResourcesRef.value?.resetStatus();
              onSearch(state.searchGroup);
            }}
            list={state.editList}
            showDelete={state.isAdd}
            onEditAll={(list: any) => {
              try {
                state.tableList.forEach((table: any) => {
                  const item = list.find((item: any) => item.id === table.id);
                  if (item) {
                    table.openFlag = item.openFlag;
                    table.title = item.name;
                    table.instrumentIds = item.instrumentIds;
                    table.content = item.content;
                    table.coverImg = item.coverImg;
                    table.tagIds = item.tagIds;

                    if (!state.editOverIds.includes(table.id)) {
                      state.editOverIds.push(table.id);
                    }
                  }
                });
                state.uploadStatus = false;
              } catch (e: any) {
                console.log(e);
              }
            }}
          />
        </NModal>

        <NModal
          maskClosable={modalClickMask}
          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({
                  instrumentIds: 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.isAdd = true;
              state.editStatus = false;
            }}
          />
        </NModal>

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

        <NModal
          maskClosable={modalClickMask}
          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 {
                    state.tableList.forEach((item: any) => {
                      if (state.editIds.includes(item.id)) {
                        item.delFlag = 1;

                        if (!state.editOverIds.includes(item.id)) {
                          state.editOverIds.push(item.id);
                        }
                      }
                    });
                  }
                  state.removeVisiable = false;
                }}>
                确定
              </NButton>
              <NButton round onClick={() => (state.removeVisiable = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
        </NModal>
      </>
    );
  }
});
