import { request } from '../utils/fetch';
import { api } from '../constants/config';
import { actionTypes } from '../constants/action-types';
import message from 'components/message';

export function getConstants() {
  return async (dispatch) => {
    dispatch({
      type: actionTypes.TENANT_CONSTANT_GET_LIST_START
    });

    const result = await request(api.tenantConstantList, undefined, { order: '+rank', size: 9999 });
    if (result) {
      dispatch({
        type: actionTypes.TENANT_CONSTANT_GET_LIST_SUCCESS,
        payload: {
          list: result
        }
      });
      return result;
    } else {
      dispatch({
        type: actionTypes.TENANT_CONSTANT_GET_LIST_FAILURE
      });
    }

    return result;
  };
}

export function updateConstant({ id, name, thumb }) {
  return async (dispatch) => {
    const formData = new FormData();
    formData.append('name', name);
    if (typeof thumb === 'object' && thumb !== null) {
      formData.append('thumb', thumb);
    }

    const result = await request(api.tenantConstantUpdate, { id }, undefined, formData);

    if (result) {
      dispatch(getConstants());
    }

    return result;
  };
}

export function sortConstant(order) {
  return async (dispatch) => {
    const result = await request(api.tenantConstantSort, undefined, undefined, JSON.stringify({ order }));

    if (result) {
      dispatch(getConstants());
    }

    return result;
  };
}

// 删除组件
export function deleteConstants(ids) {
  return async (dispatch) => {
    dispatch({
      type: actionTypes.TENANT_CONSTANT_LOADING,
      payload: true
    });
    const result = await request(api.tenantConstantDelete, undefined, { ids: ids.join(',') });

    if (result) {
      dispatch(getConstants());
      message.success('删除成功');
    }

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

const initialState = {
  loading: true,
  list: []
};

export default function reducer(state = initialState, { type, payload }) {
  switch (type) {
    case actionTypes.TENANT_CONSTANT_GET_LIST_START: {
      return { ...state, loading: true };
    }
    case actionTypes.TENANT_CONSTANT_GET_LIST_SUCCESS: {
      return { ...state, loading: false, list: payload.list };
    }
    case actionTypes.TENANT_CONSTANT_GET_LIST_FAILURE: {
      return { ...state, loading: false };
    }
    case actionTypes.TENANT_CONSTANT_LOADING: {
      return { ...state, loading: payload };
    }
    default:
      return state;
  }
}
