import { Model, routerRedux } from "dva";
import _ from 'lodash';
import { TabItemModels } from '@/components/Tab';
import homeIcon from '@/assets/home.svg';
import homeIconS from '@/assets/home_s.svg';
import estateIcon from '@/assets/estate.svg';
import estateIconS from '@/assets/estate_s.svg';
import marketIcon from '@/assets/market.svg';
import marketIconS from '@/assets/market_s.svg';
import fundIcon from '@/assets/fund.svg';
import fundIconS from '@/assets/fund_s.svg';
import profileIcon from '@/assets/profile.svg';
import profileIconS from '@/assets/profile_s.svg';

export interface HomeModelState {
  tabItems: TabItemModels;
  selectedTab: string;
}

const tabItems: TabItemModels = [
  // {
  //   key: '/home/home',
  //   name: 'home.tabHome',
  //   icon: homeIcon,
  //   iconSelected: homeIconS,
  // },
  {
    key: '/home/estate',
    name: 'home.tabEstate',
    icon: estateIcon,
    iconSelected: estateIconS,
  },
  {
    key: '/home/market',
    name: 'home.tabMarket',
    icon: marketIcon,
    iconSelected: marketIconS,
  },
  {
    key: '/home/fund',
    name: 'home.tabFund',
    icon: fundIcon,
    iconSelected: fundIconS,
  },
  {
    key: '/home/profile',
    name: 'home.tabProfile',
    icon: profileIcon,
    iconSelected: profileIconS,
  },
];

const initState: HomeModelState = {
  tabItems,
  selectedTab: tabItems[0].key,
};

const model: Model = {
  namespace: 'home',

  state: initState,

  effects: {
    *changeTab({ payload: selectedTab }, { put, select, all }) {
      const {
        router: { location: { pathname } },
        home: { selectedTab: oldSelectedTab },
      } = yield select();

      const tasks = [];
      if (oldSelectedTab !== selectedTab) {
        tasks.push(put({ type: 'onUpdateState', payload: { selectedTab } }));
      }
      if (pathname !== selectedTab) {
        tasks.push(put(routerRedux.replace(selectedTab)));
      }

      if (tasks.length) {
        yield all(tasks);
      }
    },

    *clear(_, { put }) {
      yield put({ type: 'onUpdateState', payload: initState })
    },
  },

  reducers: {
    onUpdateState(state, { payload }: any) {
      return {
        ...state,
        ...payload,
      };
    },
  },

  subscriptions: {
    onRouteChange({ dispatch, history }) {
      const { pathname } = history.location;
      if (_.some(tabItems, it => it.key === pathname)) {
        dispatch({ type: 'changeTab', payload: pathname });
      }
    }
  },
};

export default model;
