import React from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import { notification } from 'antd';
import { history, Link, RequestConfig } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import TagView from '@/components/TagView';
import * as Icon from '@ant-design/icons';
import api from '@/services/api';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
/** 获取用户信息比较慢的时候会展示一个 loading */

export const initialStateConfig = {
  loading: <PageLoading />,
};
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

export async function getInitialState() {
  const fetchUserInfo = async () => {
    try {
      const currentUser = await api.queryCurrent();

      if (currentUser.data == null && history.location.pathname !== '/gateAdmin') {
        history.push(loginPath);
      }
      return currentUser;
    } catch (error) {
      const { location } = history; // 如果没有登录，重定向到 login
      if (location.pathname != loginPath && history.location.pathname !== '/gateAdmin') {
        history.push(loginPath);
      }
    }

    return undefined;
  };
  const queryMenuData = async () => {
    try {
      const data = [
        {
          path: '/welcome',
          name: '黑菠萝智慧门店',
          icon: 'smile',
          hideInMenu: true,
          component: './Welcome',
        },
        {
          code: 'sys',
          name: '系统管理',
          icon: 'SettingOutlined',
          path: '/sys',
          routes: [
            {
              code: 'Menus',
              name: '系统菜单',
              icon: 'smile',
              path: '/sys/Menus',
              component: './sys/Menus',
              access: 'k6',
            },
            // {
            //   code: 'dictdata',
            //   name: '字典信息',
            //   icon: 'smile',
            //   path: '/sys/dictionary/dictdata',
            //   component: './sys/dictionary/dictdata',
            //   access: 'k6',
            // },
            {
              code: 'dicttype',
              name: '字典类型',
              icon: 'smile',
              path: '/sys/dictionary/dicttype',
              component: './sys/dictionary/dicttype',
              access: 'k6',
            },
            // {
            //   code: 'Log',
            //   name: '操作日志',
            //   icon: 'smile',
            //   path: '/sys/Log',
            //   component: './sys/Log',
            //   access: 'k3',
            // },
            // {
            //   code: 'Log',
            //   name: '错误日志',
            //   icon: 'smile',
            //   path: '/sys/errLog',
            //   component: './sys/errLog',
            //   access: 'k3',
            // },
          ],
        },
        {
          code: 'company',
          name: '加盟商管理',
          icon: 'TeamOutlined',
          path: '/company',
          routes: [
            {
              code: 'account',
              name: '账号管理',
              icon: 'smile',
              path: '/company/account',
              component: './sys/account',
              access: 'k4',
            },
          ]
        },
        {
          code: 'orgamange',
          name: '组织管理',
          icon: 'ClusterOutlined',
          path: '/org',
          routes: [
            {
              code: 'Org',
              name: '机构管理',
              icon: 'smile',
              path: '/org/orgamange',
              component: './org/orgamange',
              access: 'k2',
            },
            {
              code: 'roles',
              name: '角色管理',
              icon: 'smile',
              path: '/org/Roles',
              component: './org/Roles',
              access: 'k2',
            },
            {
              code: 'users',
              name: '用户账号管理',
              icon: 'smile',
              path: '/org/users',
              component: './org/users',
              access: 'k2',
            },
          ]
        },
        {
          code: 'device',
          name: '设备管理',
          icon: 'PrinterOutlined',
          path: '/device',
          routes: [
            {
              code: 'deviceType',
              name: '产品管理',
              icon: 'smile',
              path: '/device/product',
              component: './device/product',
              access: 'k12',
            },
            {
              code: 'deviceInfo',
              name: '设备信息',
              icon: 'smile',
              path: '/device/deviceInfo',
              component: './device/deviceInfo',
              access: 'k14',
            },
            {
              code: 'deviceVesion',
              name: '版本管理',
              icon: 'smile',
              path: '/device/deviceVesion',
              component: './device/deviceVesion',
              access: 'k14',
            },
            // {
            //   code: 'devicetechnology',
            //   name: '设备工艺信息',
            //   icon: 'smile',
            //   path: '/device/devicetechnology',
            //   component: './device/devicetechnology',
            //   access: 'k7',
            // },
            // {
            //   code: 'deviceFood',
            //   name: '设备商品管理',
            //   icon: 'smile',
            //   path: '/device/deviceFood',
            //   component: './device/deviceFood',
            //   access: 'k14',
            // },
            
          ],
        },
        {

          code: 'database',
          name: '元数据管理',
          icon: 'DatabaseOutlined',
          path: '/database',
          routes:[
            {
              code: 'batching',
              name: '物料管理',
              icon: 'smile',
              path: '/basic',
              routes:[
                {
                  code: 'batching',
                  name: '物料基础信息',
                  icon: 'smile',
                  path: '/database/basic/batching',
                  component: './database/basic/batching',
                  access: 'k7',
                },
              ]
            },
            {
              code: 'goods',
              name: '商品管理',
              icon: 'smile',
              path: '/goods',
              routes:[
                {
                  code: 'goods-type',
                  name: '商品类型',
                  icon: 'smile',
                  path: '/database/goods/goodstypemanage',
                  component: './database/goods/goodstypemanage',
                  access: 'k11',
                },
                {
                  code: 'goodsattribute',
                  name: '商品属性',
                  icon: 'smile',
                  path: '/database/goods/goodsattribute',
                  component: './database/goods/goodsattribute',
                  access: 'k10',
                },
                {
                  code: 'newgoods',
                  name: '商品基础信息',
                  icon: 'smile',
                  path: '/database/goods/newgoods',
                  component: './database/goods/newgoods',
                  access: 'k10',
                },
              ]
            },
          ]
        },
        {
          path: '/shop',
          icon: 'SettingOutlined',
          name: '门店信息',
          component: './shop',
        },
        {
          name: '门店小程序管理',
          icon: 'BankFilled',
          path: '/applet',
          routes: [
            {
              name: '页面管理',
              icon: 'smile',
              path: '/applet/paytemplate',
              component: './applet/paytemplate',
            },
            {
              name: '素材管理',
              icon: 'smile',
              path: '/applet/basicconfiguration',
              component: './applet/basicconfiguration',
            },
            {
              name: '小程序基础配置',
              icon: 'smile',
              path: '/applet/appidmanager',
              routes: [
                {
                  name: '支付配置',
                  icon: 'smile',
                  path: '/applet/appidmanager/payment',
                  component: './applet/appidmanager/payment',
                },
                {
                  name: 'APPID',
                  icon: 'smile',
                  path: '/applet/appidmanager/appid',
                  component: './applet/appidmanager/appid',
                },
              ],
            },
          ],
        },
        {
          name: '门店管理',
          icon: 'BankFilled',
          path: '/shopmanage',
          routes: [
            {
              name: '员工管理',
              icon: 'smile',
              path: '/shopmanage/storeStaff',
              component: './shopmanage/storeStaff',
            },
            {
              name: '打印机模板',
              icon: 'smile',
              path: '/shopmanage/printerTemplate',
              component: './shopmanage/printerTemplate',
            },
            {
              name: '店铺小票打印机',
              icon: 'smile',
              path: '/shopmanage/Printer',
              component: './shopmanage/Printer',
            },
            {
              name: '店铺桌面码',
              icon: 'smile',
              path: '/shopmanage/storeDesktopNumber',
              component: './shopmanage/storeDesktopNumber',
            },
            {
              name: '店铺广告',
              icon: 'smile',
              path: '/shopmanage/storeAdvertisement',
              component: './shopmanage/storeAdvertisement',
            },
            {
              name: '店铺菜谱',
              icon: 'smile',
              path: '/shopmanage/storeGoodsInfo',
              component: './shopmanage/storeGoodsInfo',
            },
            {
              name: '加购商品',
              icon: 'smile',
              hideInMenu: true,
              path: '/shopmanage/storeAddGoodsInfo',
              component: './shopmanage/storeAddGoodsInfo',
            },
          ],
        },
        {
           name: '门店订单管理',
            icon: 'BankFilled',
            path: '/shopmanageorder',
            routes: [
             {
              name: '订单流水',
              icon: 'smile',
              path: '/shopmanageorder/orderflow',
              component: './shopmanageorder/orderflow',
             },
             {
              name: '第三方订单',
              icon: 'smile',
              path: '/shopmanageorder/thirdOrder',
              component: './shopmanageorder/thirdOrder',
             },
             {
              name: '授权管理',
              icon: 'smile',
              path: '/shopmanageorder/thirdAuthorize',
              component: './shopmanageorder/thirdAuthorize',
             },
            ],
           },
      ];
      // api.queryMenus();
      return data;
    } catch (error) {
      history.push(loginPath);
    }
    return [];
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    //var tempMenu = await queryMenuData();
    //创建菜单
    //await syncMenus(tempMenu);
    // if (isDev) {
      var data = await dymicMenus(currentUser.data.id);
      var tempMenu = data.data;
    //}

    return {
      fetchUserInfo,
      currentUser,
      menuData: tempMenu,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

/**
 * 同步菜单
 * @param {*} args
 * @returns
 */
const syncMenus = async (args) => {
  return await api.queryAndSyncMenu({ json: JSON.stringify(args) });
};

/**
 * 动态菜单
 * @param {*} userid
 * @returns
 */

const dymicMenus = async (userid) => {
  return await api.DymicMenus(userid);
};

/**
 *
 * 动态路由
 *
 */
const loopMenuItem = (menus) =>
  menus?.map(({ icon, children, ...item }) => {
    if (typeof icon != 'undefined' && Icon[icon] != undefined) {
      return {
        ...item,
        icon: icon && React.createElement(Icon[icon]),
        children: children && loopMenuItem(children),
      };
    } else {
      return {
        ...item,
        children: children && loopMenuItem(children),
      };
    }
  });
/**
 * 异常处理程序
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '一个请求已经进入后台排队（异步任务）。',
    204: '删除数据成功。',
    400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
    401: '用户没有权限（令牌、用户名、密码错误）。',
    403: '用户得到授权，但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    405: '请求方法不被允许。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除，且不会再得到的。',
    422: '当创建一个对象时，发生一个验证错误。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。',
 //-----English
    200: The server successfully returned the requested data. ',
    201: New or modified data is successful. ',
    202: A request has entered the background queue (asynchronous task). ',
    204: Data deleted successfully. ',
    400: 'There was an error in the request sent, and the server did not create or modify data. ',
    401: The user does not have permission (token, username, password error). ',
    403: The user is authorized, but access is forbidden. ',
    404: The request sent was for a record that did not exist. ',
    405: The request method is not allowed. ',
    406: The requested format is not available. ',
    410':
        'The requested resource is permanently deleted and will no longer be available. ',
    422: When creating an object, a validation error occurred. ',
    500: An error occurred on the server, please check the server. ',
    502: Gateway error. ',
    503: The service is unavailable. ',
    504: The gateway timed out. ',
 * @see https://beta-pro.ant.design/docs/request-cn
 */
const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  405: '请求方法不被允许。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

export const request = {

  errorHandler: (error) => {
    const { response } = error;
    console.log('response', response);
    if (response && response.status !== 200 && response.status !== 422) {
      const errorText = codeMessage[response.status] || response.statusText;
      const { status, url } = response;
      if (response.status === 401 || response.status === 403) {
        notification.error({
          description: '请先登录。',
          message: '未登录',
        });
        // history.push('/user/login');
        const { location } = history; // 如果没有登录，重定向到 login
        if (!location.pathname.includes(loginPath) && history.location.pathname !== '/gateAdmin') {
          history.push(loginPath);
        }
      } else {
        notification.error({
          description: '网络发生异常，无法连接服务器',
          message: '网络异常',
        });
      }
    }
    if (!response) {
      notification.error({
        description: '网络发生异常，无法连接服务器',
        message: '网络异常',
      });
    }

    throw error;
  },
  //prefix: `${DOMAIN}`,
  requestInterceptors: [
    (url, options) => {
      url = decodeURI(encodeURI(url).replace(/%E2%80%8B/g, ''));
      const newOptions = { ...options };
      const auttoken = localStorage.getItem('token');
      const userid = localStorage.getItem('userid');
      newOptions.headers = {
        ...newOptions.headers,
        userid: userid,
        Authorization: 'Bearer  ' + auttoken,
        LoginType: 1,
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
      };
      return { url, options: newOptions };
    },
  ],
};
// ProLayout 支持的api https://procomponents.ant.design/components/layout

export const layout = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: '黑菠萝技术部',
    },

    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history; // 如果没有登录，重定向到 login
      // console.log(process.env.UMI_ENV)
      // console.log('location.pathname', location.pathname);
      if (!initialState?.currentUser && (!location.pathname.includes(loginPath) || !location.pathname.includes('/gateAdmin'))) {
        history.push(loginPath);
      }
    },
    menuDataRender: () => loopMenuItem(initialState?.menuData),
    // childrenRender: (children) => {
    //   return (
    //     <>
    //       {initialState?.currentUser && location.pathname !== loginPath && location.pathname!='/' ? (
    //     <TagView  home="/welcome" current={history.location.pathname}>
    //       {children}
    //     </TagView>
    //       ) : children}
    //     </>
    //   );
    // },
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};
