import { actionTypes } from 'constants/action-types';
import { request } from 'utils/fetch';
import { api } from 'constants/config';
import { generateId } from 'utils/utils';
const controller: any = {};

export enum designResourceType {
  'IMAGE' = 1, // 图片
  'VIDEO', // 视频
  'MODEL', // 模型
}

// 资源新增
export function addUserStaticMaterical( //添加（我的）静态资源
  body: { type: designResourceType } = {
    type: designResourceType.IMAGE,
  },
) {
  // 同步到数据集
  return async (dispatch) => {
    const name = generateId();
    const result = await request(
      api.resourceUserStaticMatericalAdd,
      undefined,
      undefined,
      JSON.stringify({
        name,
        ...body,
      }),
    );
    if (result) {
      result && dispatch(updateMaterial(result));
    }
    return result;
  };
}

function updateMaterial(result) {
  // 我的收藏，同步素材
  return async (dispatch, getState) => {
    if ([3].includes(result.type)) {
      // 非图片/组件 资源不同步
      return;
    }
    const { materialLib } = getState();
    const { myFavorite } = materialLib;
    const { themeResource, designMaterial } = myFavorite;
    const isStatic = result.type && ![designResourceType.MODEL].includes(result.type); // 图片 视频
    const isComponent = !result.type; //组件
    const _data = isStatic ? designMaterial : themeResource;

    if (result) {
      const temporary = {
        ..._data,
        list: [result, ..._data.list],
      };
      const payload = {
        ...myFavorite,
      };
      isStatic
        ? (payload['designMaterial'] = temporary)
        : isComponent
        ? (payload['themeResource'] = temporary)
        : null;
      dispatch({
        type: actionTypes.MATERIAL_LIB_SET_COLLECT_LIST,
        payload,
      });
    }
  };
}

export function favoriteCreate(body = {}) {
  // 添加（我的）主题资源
  return async (dispatch) => {
    const result = await request(api.favoriteCreate, undefined, undefined, JSON.stringify(body));
    result && dispatch(updateMaterial(result));
    return result;
  };
}

export function addOfficialResources(body) {
  // 官方资源添加 - 有个上架的动作（默认下架），因此不做redux缓存同步
  const isOfficial = !!body?.platformCategoryId;
  // 官方资源 => api.layerMatericalCreate ;
  // 素材广场 => api.resourceCreate
  return async () => {
    const result = await request(
      isOfficial ? api.layerMatericalCreate : api.resourceCreate,
      undefined,
      undefined,
      JSON.stringify(body),
    );
    return result;
  };
}

export function getMaterialCenter(type: designResourceType = designResourceType.IMAGE) {
  // 素材中心
  return async (dispatch, getState) => {
    const { materialLib } = getState();
    const { themeResource, designMaterial } = materialLib;
    if (designMaterial.list?.length && themeResource.list?.length) {
      return;
    }
    await dispatch({
      type: actionTypes.MATERIAL_LIB_LOADING,
      payload: true,
    });
    const isModule = type === 2; // 组件信息
    const staticMaterical = isModule ? await getThemeResource() : await getDesignMaterial();
    const officialCategory = await dispatch(getPlatformCategory(type));
    await dispatch({
      type: actionTypes.MATERIAL_LIB_LOADING,
      payload: false,
    });
    const data = {
      // 倒序
      category: officialCategory ? officialCategory.sort((a, b) => b.updatedAt - a.updatedAt) : [],
      list: staticMaterical ? staticMaterical.sort((a, b) => b.id - a.id) : [],
    };
    const payload = {};
    if (isModule) {
      payload['themeResource'] = data;
    } else {
      payload['designMaterial'] = data;
    }
    await dispatch({
      type: actionTypes.MATERIAL_LIB_SET_LIST,
      payload,
    });
  };
}

export function getOfficialCategory(type: designResourceType = designResourceType.IMAGE) {
  return async () => {
    const { signal } = autoAbort('officialCategory');
    const result = await request(api.officialCategory, undefined, { type }, undefined, {
      signal,
    });
    return result;
  };
}

export function getPlatformCategory(type: designResourceType = designResourceType.IMAGE) {
  return async (dispatch) => {
    const result = await request(api.platformCategory, undefined, { type }, undefined);
    if (result && type === designResourceType.VIDEO) {
      dispatch({
        type: actionTypes.MATERIAL_LIB_SET_CATEGORYS,
        payload: result,
      });
    }
    return result;
  };
}

export async function getDesignMaterial(
  type = `${designResourceType.IMAGE},${designResourceType.VIDEO}`,
) {
  // 获取设计素材
  const { signal } = autoAbort('resourceStaticMaterical');
  return await request(api.resourceStaticMaterical, undefined, { type }, undefined, {
    signal,
  });
}

function autoAbort(code: string) {
  controller[code] && controller[code].abort();
  const _controller = new AbortController();
  const { signal } = _controller;
  controller[code] = _controller;
  return { signal };
}

export function setCurrent(current) {
  return async (dispatch) => {
    await dispatch({
      type: actionTypes.MATERIAL_LIB_SET_CURRENT,
      payload: current,
    });
  };
}

export async function getThemeResource() {
  // 获取主题资源
  const { signal } = autoAbort('resourceLayerMaterical');
  return await request(api.resourceLayerMaterical, undefined, undefined, undefined, { signal });
}

export function createResourceCount(id: number, source: 'platform' | 'official') {
  return async () => {
    id &&
      request(
        api.resourceCount,
        { id },
        undefined,
        JSON.stringify({
          source,
        }),
        {
          hideError: true,
        },
      );
  };
}

// 我的收藏查询
export function getUserCategory() {
  return async (dispatch, getState) => {
    const { materialLib } = getState();
    const { myFavorite } = materialLib;
    const { designMaterial, themeResource } = myFavorite;
    if (designMaterial.list?.length && themeResource.list?.length) {
      return;
    }
    await dispatch({
      type: actionTypes.MATERIAL_LIB_LOADING,
      payload: true,
    });
    const { signal } = autoAbort('resourceCategory');
    const { signal: signal1 } = autoAbort('resourceUserStaticMaterical');
    const { signal: signal2 } = autoAbort('resourceUserLayerMaterial');
    const userCategory = await request(
      api.resourceCategory,
      undefined,
      { type: `${designResourceType.IMAGE},${designResourceType.VIDEO}` },
      undefined,
      {
        signal,
      },
    );
    const userStaticMaterical = await request(
      api.resourceUserStaticMaterical,
      undefined,
      undefined,
      undefined,
      {
        signal1,
      },
    );
    const userLayerMaterial = await request(
      api.resourceUserLayerMaterial,
      undefined,
      undefined,
      undefined,
      {
        signal2,
      },
    );
    if (userCategory && (userStaticMaterical || userLayerMaterial)) {
      await dispatch({
        type: actionTypes.MATERIAL_LIB_SET_COLLECT_LIST,
        payload: {
          designMaterial: {
            category: userCategory.filter((d) => d.type === designResourceType.IMAGE),
            list: userStaticMaterical,
          },
          themeResource: {
            category: userCategory.filter((d) => d.type === designResourceType.VIDEO),
            list: userLayerMaterial,
          },
        },
      });
    }

    await dispatch({
      type: actionTypes.MATERIAL_LIB_LOADING,
      payload: false,
    });
  };
}

export function resetMaterial() {
  return async (dispatch) => {
    await dispatch({
      type: actionTypes.MATERIAL_CLEAR,
    });
  };
}

export function getResourceUserCategory(type = designResourceType.IMAGE) {
  return async () => {
    return request(api.resourceCategory, undefined, { type });
  };
}

export function getResourceUserMaterical(type = designResourceType.IMAGE) {
  return async () => {
    return request(api.resourceUserStaticMaterical, undefined, { type }, undefined);
  };
}

export interface ResourceTs {
  category: any[];
  list: any[];
}

const initialState = {
  designMaterial: {
    category: [],
    list: [],
  },
  themeResource: {
    category: [],
    list: [],
  },
  myFavorite: {
    designMaterial: {
      category: [],
      list: [],
    },
    themeResource: {
      category: [],
      list: [],
    },
  },

  theFirstColumn: [
    {
      id: 1,
      type: 'designMaterial',
      name: '设计素材',
    },
    {
      id: 2,
      type: 'themeResource',
      name: '主题资源',
    },
    {
      id: 3,
      type: 'myFavorite',
      name: '我的收藏',
    },
  ],
  loading: false,
  current: 1,
  platformCategory: [], // 官方素材
};

export const defaultState = {};

export default function introReducer(state = initialState, { type, payload }) {
  switch (type) {
    case actionTypes.MATERIAL_LIB_SET_UPDATE: {
      return {
        ...state,
      };
    }
    case actionTypes.MATERIAL_LIB_SET_LIST: {
      return {
        ...state,
        ...payload,
      };
    }
    case actionTypes.MATERIAL_LIB_SET_COLLECT_LIST: {
      return {
        ...state,
        myFavorite: {
          ...payload,
        },
      };
    }
    case actionTypes.MATERIAL_LIB_SET_CURRENT: {
      return {
        ...state,
        current: payload,
      };
    }
    case actionTypes.MATERIAL_LIB_LOADING: {
      return {
        ...state,
        loading: payload,
      };
    }
    case actionTypes.MATERIAL_LIB_SET_CATEGORYS: {
      return {
        ...state,
        platformCategory: payload,
      };
    }
    case actionTypes.MATERIAL_CLEAR: {
      return {
        ...initialState,
      };
    }
    default:
      return state;
  }
}
