import http from '../../../utils/fetch';
import { api } from '../../../constants/config';
import { getScreen } from 'models/screen';
import { getFilters } from 'models/filter';
import { getScreenPermission } from 'models/screen-detail';

export const constants = {
  INTERACTION_DETAIL_APP_GET_BEGIN: 'INTERACTION_DETAIL_APP_GET_BEGIN',
  INTERACTION_DETAIL_APP_GET_SUCCESS: 'INTERACTION_DETAIL_APP_GET_SUCCESS',
  INTERACTION_DETAIL_APP_GET_FAILURE: 'INTERACTION_DETAIL_APP_GET_FAILURE',
  INTERACTION_DETAIL_APP_CHECK_STATUS: 'INTERACTION_DETAIL_APP_CHECK_STATUS'
};

export const actions = {
  getApp(id, { byControlCode } = { byControlCode: '' }) {
    return async (dispatch) => {
      dispatch({
        type: constants.INTERACTION_DETAIL_APP_GET_BEGIN,
        payload: {
          id
        }
      });
      let data;
      if (/\/app\/preview\/[0-9]+/.test(window.location.href) || /checkMode=login/.test(window.location.href)) {
        data = await http.get(api.interactionGet, { id });
      } else if (/\/app\/detail\/[0-9]+/.test(window.location.href)) {
        // 在detail页面，用户没有登录，则在detail页面
        const query = window.location.search.substring(1);
        const queryControlCode = query.split('&').filter((item) => item.includes('controlCode'));
        const controlCode = queryControlCode.length ? queryControlCode[0].substring(12) : '';
        data = await http.get(
          api.interactionAppByCode,
          { id, controlCode: controlCode || byControlCode || '' },
          {
            error: () => {}
          }
        );
      }
      // 后端校验是否真正需要控制码
      dispatch({
        type: constants.INTERACTION_DETAIL_APP_CHECK_STATUS,
        payload: {
          renderCheck: !data ? 1 : 0
        }
      });

      if (data) {
        await dispatch(getFilters(id, 'mobile', { byControlCode }));
        await dispatch({
          type: constants.INTERACTION_DETAIL_APP_GET_SUCCESS,
          payload: {
            id,
            name: data.name,
            config: data.config,
            pages: data.pages,
            activePage: data.pages[0].uniqueTag,
            mobileURL: data.mobileURL,
            published: data.published,
            limitNetwork: data.limitNetwork,
            controlCode: data.controlCode
          }
        });
        data.pages?.length && (await dispatch(getScreenPermission(data.pages[0].id)));
        data.pages.map((d) => dispatch(getScreen(d.id, undefined, { byControlCode })));
        return data;
      } else {
        dispatch({
          type: constants.INTERACTION_DETAIL_APP_GET_FAILURE
        });
      }
    };
  },
  // 更新发布配置
  updatePublishSetting({ key, value }) {
    return async (dispatch, getState) => {
      try {
        const { interactionDetail } = getState();
        const data = { ...interactionDetail };
        data[key] = value;
        // 第一次发布没有controlCode字段
        if (data.published && !data.controlCode && data.controlCode !== '') {
          data.controlCode = Math.random().toString().slice(2, 8);
          data.limitNetwork = true;
        }
        dispatch({
          type: constants.INTERACTION_DETAIL_APP_GET_SUCCESS,
          payload: {
            published: data.published,
            controlCode: data.controlCode,
            limitNetwork: data.limitNetwork
          }
        });
        await http.post(api.interactionUpdate, {
          id: interactionDetail.id,
          updateList: [
            { key: 'published', value: data.published },
            { key: 'controlCode', value: data.controlCode },
            { key: 'limitNetwork', value: data.limitNetwork }
          ]
        });
        return data;
      } catch (error) {
        console.error(error.message);
      }
    };
  }
};

export function reducers(state, { type, payload }) {
  switch (type) {
    case constants.INTERACTION_DETAIL_APP_GET_BEGIN: {
      return {
        ...state,
        loading: true
      };
    }
    case constants.INTERACTION_DETAIL_APP_GET_SUCCESS: {
      return {
        ...state,
        loading: false,
        ...payload
      };
    }
    case constants.INTERACTION_DETAIL_APP_GET_FAILURE: {
      return {
        ...state,
        loading: false
      };
    }
    case constants.INTERACTION_DETAIL_APP_CHECK_STATUS: {
      return {
        ...state,
        ...payload
      };
    }
    default:
      return state;
  }
}
