/* eslint-disable prefer-destructuring,guard-for-in */
import { NavigationActions } from 'react-navigation';
import { fetchDomains, switchDomain, currentDomain } from '../services/domain';
import { delToken, getDomain, setDomain, delDomain, getUser, delUser } from '../utils/auth';
import { logout } from '../services/login';

const findTarget = (list, dmpath) => {
  // 循环 list，元素el
  // 如果 el.value == dmpath, return el;
  // 否则 findTarget（el.children, dmpath）
  // 如果找到，返回找到的
  // 如果没找到，继续循环
  // 循环结束： return null；
  for (let i = 0; i < list.length; i++) {
    if (list[i].value === dmpath) {
      return list[i];
    } else {
      const data = findTarget(list[i].children, dmpath);
      if (data) {
        return data;
      }
    }
  }
  return null;
};
const createData = async (list, dmpath, payload) => {
  // 根据path用fetchDomains 查出children
  let childrens = [];
  let pathArray;
  if (dmpath !== '/' && dmpath.split('/').length !== 4) {
    childrens = await fetchDomains(dmpath);
    if (childrens.length !== 0) {
      pathArray = [...payload, ''];
    } else {
      pathArray = [...payload];
    }
  } else {
    pathArray = [...payload];
  }


  const childrenData = [];
  if (childrens.length !== 0) {
    childrenData.push({ label: '请选择', value: '', children: [] });
    childrens.map(({ name, path }) => {
      childrenData.push({ label: name, value: path, children: [] });
      return childrenData;
    });
  }
  // 根据path在list查出需要添加children的对象target
  const findData = findTarget(list, dmpath);
  findData.children = childrenData;
  // if (childrens.length !== 0) {
  //   await createData(list, pathArray[pathArray.length - 1], pathArray);
  //   return { data, pathArray, cols: pathArray.length };
  // } else {
  //   console.info('xxxxx');
  return { data: list, pathArray, cols: pathArray.length };
  // }
};

export default {

  namespace: 'domain',

  state: {
    init: undefined,
    list: [],
    listChildren: [],
    arrayPath: [],
    cols: 1,
    userInfo: '',
    currentJiDiName: undefined,
  },

  subscriptions: {
    setup({ dispatch }) {  // eslint-disable-line
    },
  },

  effects: {
    *fetch(ignored, { put, call }) {
      const domain = yield call(getDomain);
      const init = domain ? domain.path : undefined;
      const list = yield call(fetchDomains, '/', true);
      const datas = [];
      list.map(({ name, path }) => {
        datas.push({ label: name, value: path, children: [] });
        return datas;
      });
      yield put({ type: 'setCols', payload: 1 });
      yield put({ type: 'queryInit', payload: init });
      yield put({ type: 'queryArryPath', payload: ['/'] });
      yield put({ type: 'queryList', payload: datas });
    },

    *fetchParam({ payload }, { put, call, select }) {
      let dmpath = '';
      if (payload.length === 1) {
        dmpath = payload[0];
      } else if (payload.length === 2) {
        dmpath = payload[1];
      } else {
        dmpath = payload[2];
      }
      const { list } = yield select(state => state.domain);
      const datas = yield call(createData, list, dmpath, payload);
      console.log(datas);
      yield put({ type: 'queryList', payload: datas.data });
      yield put({ type: 'queryArryPath', payload: datas.pathArray });
      yield put({ type: 'setCols', payload: datas.cols });
    },
    *switch({ payload: domainPath }, { put, call }) {
      yield call(switchDomain, domainPath);
      const { path, name } = yield call(currentDomain);
      yield call(setDomain, name, path);
      yield put({ type: 'queryInit', payload: path });
      const currentJiDiName = name;
      yield put({ type: 'setCurrentJiDiName', payload: currentJiDiName });
    },
    *logout(ignored, { put, call }) {
      yield call(logout);
      yield call(delToken);
      yield call(delUser);
      yield call(delDomain);
      yield put(NavigationActions.navigate({
        routeName: 'Login',
      }));
    },
    *getUserInfo(ignored, { put, call }) {
      const userInfo = yield call(getUser);
      const domain = yield call(getDomain);
      const list = yield call(fetchDomains, domain.path, true);
      const currentJiDiName = list[0].name;
      yield put({ type: 'setCurrentJiDiName', payload: currentJiDiName });
      yield put({ type: 'queryUserInfo', payload: userInfo });
    },
  },

  reducers: {
    queryUserInfo(state, { payload: userInfo }) {
      return {
        ...state,
        userInfo,
      };
    },
    queryInit(state, { payload: init }) {
      return {
        ...state,
        init,
      };
    },
    queryList(state, { payload: list }) {
      return {
        ...state,
        list,
      };
    },
    queryListChildren(state, { payload: listChildren }) {
      return {
        ...state,
        listChildren,
      };
    },
    queryArryPath(state, { payload: arrayPath }) {
      return {
        ...state,
        arrayPath,
      };
    },
    setCols(state, { payload: cols }) {
      return {
        ...state,
        cols,
      };
    },
    setCurrentJiDiName(state, { payload: currentJiDiName }) {
      return {
        ...state,
        currentJiDiName,
      };
    },
  },

};
