import { routerRedux } from 'dva/router';
import { sldCommonService } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
import { getPageQuery, failTip,sldComLanguage } from '@/utils/utils';

export default {
  namespace: 'common',

  state: {
    notice: [],
  },

  effects: {
    //slodon_获取图形验证码
    * get_captcha({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', 'v3/captcha/common/getCaptcha');
      if (callback) callback(response);
    },
    //slodon_获取短信验证码
    * get_sms_code({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'post', 'v3/msg/seller/commons/smsCode');
      if (callback) callback(response);
    },
    //slodon_获取店铺运费模板列表
    * get_transport_lists({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', 'v3/goods/seller/goodsFreightTemplate/list');
      if (callback) callback(response);
    },
    //slodon_获取系统设置信息
    * getSetting({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, {...payload, isAll: true }, 'get', 'v3/system/seller/setting/getSettingList');
      if (callback) callback(response);
    },
    //slodon_批量保存设置信息
    * saveSetting({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'post', 'v3/system/seller/setting/updateSettingList');
      if (callback) callback(response);
    },
    //slodon_获取商品销售排行TOP10
    * get_goods_sales_rank({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', 'v3/statistics/seller/trade/analysis/goodsSalesRank');
      if (callback) callback(response);
    },
    //slodon_获取支付/下单金额趋势数据
    * get_pay_order_trend({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', 'v3/statistics/seller/overview/analysis/payOrderTrend');
      if (callback) callback(response);
    },
    //slodon_获取询盘趋势数据
    * get_enquiry_trend({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', 'v3/statistics/seller/overview/analysis/enquiryTrend');
      if (callback) callback(response);
    },
    //slodon_获取流量趋势数据
    * get_flow_trend({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', 'v3/statistics/seller/overview/analysis/flowTrend');
      if (callback) callback(response);
    },
    //slodon_获取会员偏好商品排行-TOP10数据
    * get_goods_prefer_rank({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', 'v3/statistics/seller/member/analysis/preferGoodsRank');
      if (callback) callback(response);
    },
    //slodon_获取商品销售变化趋势-TOP10数据
    * get_goods_sales_trend_top({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', 'v3/statistics/seller/goods/analysis/goodsSalesRank');
      if (callback) callback(response);
    },
    //slodon_获取所有秒杀活动列表
    * get_all_seckill_list({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', 'v3/promotion/seller/seckill/list');
      callback && callback(response);
    },
    //单点登录
    * sso_seller({ payload, callback }, { call, put }) {
      const response = yield call(sldCommonService, payload, 'post', 'v3/open/api/sso/login/seller');
      // Login successfully
      if (response.state == 267) {
        let cur_top_nav = ['apply'];//顶部菜单
        let cur_top_nav_info = [{
          top_nav: 'apply',
          name: `${sldComLanguage('商户入驻')}`,
          left_icon: require('../assets/nav/store.png'),
          path: '/apply/settled_protocol',
        }];//顶部菜单详细信息
        if (response.data.resourceList.length > 0) {
          localStorage.setItem('sld_menu_data', JSON.stringify(response.data.resourceList));
          let sld_all_routes = [];//所有页面的路由
          response.data.resourceList.map(item => {
            item.children.map(child => {
              sld_all_routes.push(child.frontPath);
            });
          });
          localStorage.setItem('sld_all_routes', JSON.stringify(sld_all_routes));
        }
        localStorage.setItem('cur_top_nav', JSON.stringify(cur_top_nav));
        localStorage.setItem('cur_top_nav_info', JSON.stringify(cur_top_nav_info));
      }
      if (callback) callback(response);
      let cur_top_nav = [];//顶部菜单
      let cur_top_nav_info = [];//顶部菜单详细信息
      if (response.state === 200) {
        localStorage.setItem('storeId', response.data.storeId);
        localStorage.setItem('vendorId', response.data.vendorId);
        localStorage.setItem('isStoreAdmin', response.data.isStoreAdmin);
        if (response.data.resourceList.length > 0) {
          localStorage.setItem('sld_menu_data', JSON.stringify(response.data.resourceList));
          let sld_all_routes = [];//所有页面的路由
          response.data.resourceList.map(item => {
            item.children.map(child => {
              sld_all_routes.push(child.frontPath);
            });
          });
          localStorage.setItem('sld_all_routes', JSON.stringify(sld_all_routes));
          let tmp_data = response.data.resourceList;
          for (let i in tmp_data) {
            let split_first = tmp_data[i].frontPath.split('/');
            let target = split_first[1];
            if (cur_top_nav.indexOf(target) == -1) {
              let target_data = {};
              target_data.top_nav = target;
              target_data.path = tmp_data[i].children[0].frontPath;
              if (target == 'basic') {
                target_data.name = '概况';
                target_data.left_icon = require('../assets/nav/basic.png');
              } else if (target == 'goods') {
                target_data.name = '商品';
                target_data.left_icon = require('../assets/nav/goods.png');
              } else if (target == 'order') {
                target_data.name = '询盘';
                target_data.left_icon = require('../assets/nav/order.png');
              } else if (target == 'store') {
                target_data.name = '店铺';
                target_data.left_icon = require('../assets/nav/store.png');
              }
              // else if (target == 'bill') {
              //   target_data.name = '结算';
              //   target_data.left_icon = require('../assets/nav/bill.png');
              // } else if (target == 'point') {
              //   target_data.name = '积分商城';
              //   target_data.left_icon = require('../assets/nav/point.png');
              // } else if (target == 'im') {
              //   target_data.name = '客服';
              //   target_data.left_icon = require('../assets/nav/point.png');
              // } else if (target == 'spreader') {
              //   target_data.name = '推手';
              //   target_data.left_icon = require('../assets/nav/spreader.png');
              // }
              else if (target == 'statistics') {
                target_data.name = '统计';
                target_data.left_icon = require('../assets/nav/statistics.png');
              }
              // else if (target == 'marketing') {
              //   target_data.name = '应用';
              //   target_data.left_icon = require('../assets/nav/marketing.png');
              // }
              cur_top_nav.push(target);
              cur_top_nav_info.push(target_data);
            }
          }

          localStorage.setItem('cur_top_nav', JSON.stringify(cur_top_nav));
          localStorage.setItem('cur_top_nav_info', JSON.stringify(cur_top_nav_info));

        } else {
          failTip(`${sldComLanguage('抱歉，该账号未授予权限，请先授予权限～')}`);
          return false;
        }
        if (callback) callback(response);
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        let all_routes = JSON.parse(localStorage.sld_all_routes);
        //如果只有客服得权限，则直接跳转到客服页面
        if (cur_top_nav_info.length == 1 && cur_top_nav_info[0].top_nav == 'im') {
          window.location.href = apiUrl + 'im/';
          return false;
        }

        if (redirect) {
          //如果上次路由是入驻的话，需要进入已有路由的第一个页面
          if (redirect.indexOf('/apply') > -1) {
            window.location.href = JSON.parse(localStorage.sld_all_routes)[0];
            return false;
          }
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        } else {
          yield put(routerRedux.replace(all_routes[0]));
          return;
        }
        //如果redirect在用户拥有的路由内，则跳转，否则跳转第一个页面
        let contain_redirect_flag = false;
        for (let i = 0; i < all_routes.length; i++) {
          if (redirect.indexOf(all_routes[i]) > -1) {
            contain_redirect_flag = true;
            break;
          }
        }
        if (!contain_redirect_flag) {
          redirect = all_routes[0];
        }
        yield put(routerRedux.replace(redirect));
      }
    },
    //slodon_帮助文档列表
    * get_help_article_list({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', `v3/cms/doc/seller/list`);
      if (callback) callback(response);
    },
    //slodon_帮助文档详情
    * get_help_article_detail({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', `v3/cms/doc/detail`);
      if (callback) callback(response);
    },
    //slodon_协议详情
    * get_agree_detail({ payload, callback }, { call }) {
      const response = yield call(sldCommonService, payload, 'get', `v3/system/front/agreement/detail`);
      if (callback) callback(response);
    },
  },

  reducers: {
    saveNotice(state, action) {
      return {
        ...state,
        notice: action.payload,
      };
    },
  },
};
