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 = [
        {
          name: '快速开始',
          icon: 'PlayCircleOutlined',
          path: '/quickStart',
          component: './quickStart',
        },
        {
          path: '/welcome',
          name: '连锁经营平台',
          icon: 'smile',
          hideInMenu: true,
          component: './Welcome',
        },
        {
          code: 'device',
          name: '设备管理',
          icon: 'BankFilled',
          path: '/device',
          routes: [
            {
              code: 'deviceType',
              name: '设备分类',
              icon: 'smile',
              path: '/device/deviceType',
              component: './device/deviceType',
              access: 'k12',
            },
            {
              code: 'deviceInfo',
              name: '设备信息',
              icon: 'smile',
              path: '/device/deviceInfo',
              component: './device/deviceInfo',
              access: 'k14',
            },
            {
              code: 'deviceFood',
              name: '设备商品管理',
              icon: 'smile',
              path: '/device/deviceFood',
              component: './device/deviceFood',
              access: 'k14',
            },
            {
              code: 'deviceStirFryTime',
              name: '小炒设备管理',
              icon: 'smile',
              path: '/device/deviceStirFryTime',
              component: './device/deviceStirFryTime',
              access: 'k14',
            },
            {
              code: 'deviceBOM',
              name: '设备配方管理',
              icon: 'smile',
              path: '/device/deviceBom',
              component: './device/deviceBom',
              access: 'k14',
            }, {
              name: '调酒设备',
              icon: 'smile',
              path: '/device/devicemorkmwpush',
              component: './device/devicemorkmwpush',
              access: 'k14',
            },
          ],
        },
        // {
        //   code: 'integral',
        //   name: '积分管理',
        //   icon: 'BankFilled',
        //   path: '/integral',
        //   routes: [
        //     {
        //       code: 'integralConfigure',
        //       name: '积分规则',
        //       icon: 'smile',
        //       path: '/integral/integralConfigure',
        //       component: './integral/integralConfigure',
        //       access: 'k12',
        //     },
        //     {
        //       name: '规则分发',
        //       icon: 'smile',
        //       path: '/integral/integralDistribute',
        //       component: './integral/integralDistribute',
        //       access: 'k12',
        //     },
        //   ]

        // },
        {
          code: 'foodMenu',
          name: '菜谱管理',
          icon: 'BankFilled',
          path: '/foodMenu',
          routes: [
            {
              code: 'foodMenuInfo',
              name: '菜谱设置',
              icon: 'smile',
              path: '/foodMenu/foodMenuInfo',
              component: './foodMenu/foodMenuInfo',
              access: 'k12',
            },
            {
              code: 'storeFoodMenu',
              name: '菜谱关联门店',
              icon: 'smile',
              path: '/foodMenu/storeFoodMenu',
              component: './foodMenu/storeFoodMenu',
              access: 'k14',
            },
            {
              code: 'foodMenu',
              name: '菜谱关联菜品',
              icon: 'smile',
              path: '/foodMenu/foodMenu',
              component: './foodMenu/foodMenu',
              access: 'k14',
            }
          ]
        },
        {
          code: 'sys',
          name: '系统管理',
          icon: 'SettingOutlined',
          path: '/sys',
          routes: [
            {
              code: 'company',
              name: '加盟商管理',
              icon: 'smile',
              path: '/sys/company',
              component: './sys/company',
              access: 'k2',
            },
            {
              code: 'Org',
              name: '组织管理',
              icon: 'smile',
              path: '/sys/Org',
              component: './sys/Org',
              access: 'k2',
            },
            {
              code: 'Log',
              name: '操作日志',
              icon: 'smile',
              path: '/sys/Log',
              component: './sys/Log',
              access: 'k3',
            },
            {
              code: 'User',
              name: '系统用户',
              icon: 'smile',
              path: '/sys/User',
              component: './sys/User',
              access: 'k4',
            },
            {
              code: 'Roles',
              name: '角色权限',
              icon: 'smile',
              path: '/sys/Roles',
              component: './sys/Roles',
              access: 'k5',
            },
            {
              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: 'deviceTypeConfig',
              name: '设备系列配置',
              icon: 'smile',
              path: '/sys/deviceTypeConfig',
              component: './sys/deviceTypeConfig',
              access: 'k6',
            },
            {
              code: 'dicttype',
              name: '字典类型',
              icon: 'smile',
              path: '/sys/dictionary/dicttype',
              component: './sys/dictionary/dicttype',
              access: 'k6',
            },
            {
              code: 'sysSettings',
              name: '系统配置',
              icon: 'smile',
              path: '/sys/sysSettings',
              component: './sys/sysSettings',
              access: 'k6',
            },
          ],
        },
        {
          name: '小程序管理',
          icon: 'BankFilled',
          path: '/applet',
          routes: [
            {
              name: '页面管理',
              icon: 'smile',
              path: '/applet/pageManage',
              component: './applet/pageManage',
              access: 'k2',
            },
            {
              name: '素材管理',
              icon: 'smile',
              path: '/applet/material',
              component: './applet/material',
              access: 'k2',
            },
          ]
        },
        {
          name: '一卡通管理',
          icon: 'BankFilled',
          path: '/card',
          routes: [
            {
              name: '账户管理',
              icon: 'smile',
              path: '/card/memberAccount',
              component: './card/memberAccount',
              access: 'k2',
            },
            {
              name: '储值卡管理',
              icon: 'smile',
              path: '/card/storedValueCard',
              component: './card/storedValueCard',
              access: 'k2',
            },
            {
              name: '档口管理',
              icon: 'smile',
              path: '/card/gate',
              component: './card/gate',
              access: 'k2',
            },
            {
              name: '刷卡机管理',
              icon: 'smile',
              path: '/card/machine',
              component: './card/machine',
              access: 'k2',
            },
            {
              name: '预定商品',
              icon: 'smile',
              path: '/card/checkgoods',
              component: './card/checkgoods',
              access: 'k10',
            },
            {
              name: '预定报表',
              icon: 'smile',
              path: '/card/reservation',
              component: './card/reservation',
              access: 'k10',
            },
          ]
        },
        {
          code: 'bom',
          name: '配方管理',
          icon: 'DropboxSquareFilled',
          path: '/bom',
          routes: [
            {
              code: 'bommanage',
              name: '配方列表',
              icon: 'smile',
              path: '/bom/manage',
              component: './bom/manage',
              access: 'k7',
            },
            {
              code: 'bomtype',
              name: '配方分类',
              icon: 'smile',
              path: '/bom/bomtype',
              component: './bom/bomtype',
              access: 'k7',
            },
          ],
        },
        {
          code: 'erp',
          name: '物料管理',
          icon: 'DropboxSquareFilled',
          path: '/erp',
          routes: [
            {
              code: 'product',
              name: '物料信息',
              icon: 'smile',
              path: '/erp/basic/product',
              component: './erp/basic/product',
              access: 'k7',
            },
            {
              code: 'unit',
              name: '物料单位',
              icon: 'smile',
              path: '/erp/basic/unit',
              component: './erp/basic/unit',
              access: 'k8',
            },
            {
              code: 'productType',
              name: '物料分类',
              icon: 'smile',
              path: '/erp/basic/productType',
              component: './erp/basic/productType',
              access: 'k9',
            },

          ],
        },
        {
          code: 'goods',
          name: '商品管理',
          icon: 'ProjectFilled',
          path: '/goods',
          routes: [
            {
              code: 'newgoods',
              name: '商品管理',
              icon: 'smile',
              path: '/goods/newgoods',
              component: './goods/newgoods',
              access: 'k10',
            },
            {
              code: 'goods-type',
              name: '商品小类',
              icon: 'smile',
              path: '/goods/goods-type-manage',
              component: './goods/goods-type-manage',
              access: 'k11',
            },
            {
              code: 'goodsbigtype',
              name: '商品大类',
              icon: 'smile',
              path: '/goods/goodsParentTypemanage',
              component: './goods/goodsParentTypemanage',
              access: 'k11',
            },
            {
              code: 'unit',
              name: '商品单位',
              icon: 'smile',
              path: '/goods/unit',
              component: './goods/unit',
              access: 'k11',
            },
            {
              code: 'goodsPractice',
              name: '做法关联设置',
              icon: 'smile',
              path: '/goods/goodsPractice',
              component: './goods/goodsPractice',
              access: 'k9',
            },
            {
              code: 'goodsPracticeType',
              name: '商品做法类别',
              icon: 'smile',
              path: '/goods/goodsPracticeType',
              component: './goods/goodsPracticeType',
              access: 'k9',
            },
            {
              code: 'goodsPracticeInfo',
              name: '商品做法基础信息',
              icon: 'smile',
              path: '/goods/goodsPracticeInfo',
              component: './goods/goodsPracticeInfo',
              access: 'k9',
            },
          ],
        },
        {
          code: 'store',
          name: '店铺管理',
          icon: 'BankFilled',
          path: '/store',
          routes: [
            {
              code: 'storeDesktopNumber',
              name: '店铺桌面码',
              icon: 'smile',
              path: '/store/storeDesktopNumber',
              component: './store/storeDesktopNumber',
              access: 'k12',
            },
            {
              name: '店铺员工',
              icon: 'smile',
              path: '/store/storeStaff',
              component: './store/storeStaff',
              access: 'k12',
            },
            {
              code: 'Printer',
              name: '店铺小票打印机',
              icon: 'smile',
              path: '/store/printer/Printer',
              component: './store/printer/Printer',
              access: 'k12',
            },
            {
              code: 'printerTemplate',
              name: '打印机模板',
              icon: 'smile',
              path: '/store/printer/printerTemplate',
              component: './store/printer/printerTemplate',
              access: 'k12',
            },
            {
              code: 'storeGoodsInfo',
              name: '店铺商品',
              icon: 'smile',
              path: '/store/storeGoodsInfo',
              component: './store/storeGoodsInfo',
              access: 'k14',
            },
            {
              code: 'storeAdvertisement',
              name: '店铺广告',
              icon: 'smile',
              path: '/store/storeAdvertisement',
              component: './store/storeAdvertisement',
              access: 'k39',
            },
          ],
        },
        {
          code: 'member',
          name: '会员管理',
          icon: 'UserSwitchOutlined',
          path: '/member',
          routes: [
            {
              code: 'memberInfo',
              name: '会员信息',
              icon: 'smile',
              path: '/member/memberInfo',
              component: './member/memberInfo',
              access: 'k17',
            },
            {
              code: 'membertag',
              name: '会员标签信息',
              icon: 'smile',
              path: '/member/membertag',
              component: './member/membertag',
              access: 'k18',
            },
            {
              code: 'memberAnalysis',
              name: '会员数据分析',
              icon: 'smile',
              path: '/member/memberAnalysis',
              component: './member/memberAnalysis',
              access: 'k19',
            },
          ],
        },
        {
          code: 'activity',
          name: '活动管理',
          icon: 'CarryOutOutlined',
          path: '/activity',
          routes: [
            {
              code: 'activityInfo',
              name: '活动信息',
              icon: 'smile',
              path: '/activity/activityInfo',
              component: './crm/activity/activityInfo',
              access: 'k20',
            },
            {
              code: 'activityRecord',
              name: '活动记录信息',
              icon: 'smile',
              path: '/activity/activityRecord',
              component: './activity/activityRecord',
              access: 'k21',
            },
            {
              code: 'activityStart',
              name: '快速开始',
              icon: 'smile',
              path: '/activity/activityStart',
              component: './activity/activityStart',
              access: 'k21',
            },
          ],
        },
        {
          code: 'Coupon',
          name: '优惠券管理',
          icon: 'WalletOutlined',
          path: '/crm',
          routes: [
            {
              code: 'couponInfo',
              name: '优惠卷管理',
              icon: 'smile',
              path: '/crm/Coupon/couponInfo',
              component: './crm/Coupon/couponInfo',
              access: 'k22',
            },
            {
              code: 'coupon-Batch',
              name: '优惠卷批次信息',
              icon: 'smile',
              path: '/crm/Coupon/coupon-Batch',
              component: './crm/Coupon/coupon-Batch',
              access: 'k23',
            },
            {
              code: 'customerCoupon',
              name: '优惠卷领取信息',
              icon: 'smile',
              path: '/crm/Coupon/customerCoupon',
              component: './crm/Coupon/customerCoupon',
              access: 'k24',
            },
          ],
        },
        {
          code: 'split',
          name: '分账管理',
          icon: 'RedEnvelopeOutlined',
          path: '/split',
          routes: [
            {
              code: 'account',
              name: '分账账户管理',
              icon: 'smile',
              path: '/split/account',
              component: './split/account',
              access: 'k25',
            },
            {
              code: 'FranchiseePlan',
              name: '加盟商分账方案',
              icon: 'smile',
              path: '/split/FranchiseePlan',
              component: './split/FranchiseePlan',
              access: 'k25',
            },
            {
              code: 'plan',
              name: '分账方案管理',
              icon: 'smile',
              path: '/split/plan',
              component: './split/plan',
              access: 'k26',
            },
            {
              code: 'splitOrders',
              name: '分账订单管理',
              icon: 'smile',
              path: '/split/splitOrders',
              component: './split/splitOrders',
              access: 'k27',
            },
          ],
        },
        {
          code: 'refundment',
          name: '退款操作',
          icon: 'AccountBookOutlined',
          path: '/refundment',
          routes: [
            {
              code: 'OrderAfterSales',
              name: '售后申请',
              icon: 'smile',
              path: '/refundment/OrderAfterSales',
              component: './refundment/OrderAfterSales',
              access: 'k28',
            },
          ],
        },
        {
          code: 'order',
          name: '报表统计',
          icon: 'SmileOutlined',
          path: '/order',
          routes: [
            {
              code: 'ordersummarymanage',
              name: '订单汇总',
              path: '/order/order-summary-manage',
              component: './order/order-summary-manage',
              access: 'k29',
            },
            {
              code: 'orderflowmanage',
              name: '订单流水',
              path: '/order/order-flow-manage',
              component: './order/order-flow-manage',
              access: 'k30',
            },
            {
              code: 'orderDetail',
              name: '订单明细',
              path: '/order/orderDetail',
              component: './order/orderDetail',
              access: 'k31',
            },
            {
              code: 'ordersalescountbyday',
              name: '营业日报',
              path: '/order/ordersalescountbyday',
              component: './order/ordersalescountbyday',
              access: 'k32',
            },
            {
              code: 'ExOrder',
              name: '异常订单',
              path: '/order/ExOrder',
              component: './order/ExOrder',
              access: 'k32',
            },
            {
              name: '营收报表',
              path: '/order/order-market-report',
              component: './order/order-market-report',
              access: 'k31',
            },
            {
              name: '订单报表',
              path: '/order/order-report',
              component: './order/order-report',
              access: 'k31',
            },
            {
              name: '营销报表',
              path: '/order/order-revenue-statement',
              component: './order/order-revenue-statement',
              access: 'k31',
            },
            {
              name: '产品报表',
              path: '/order/order-product-report',
              component: './order/order-product-report',
              access: 'k31',
            },
            {
              name: '会员报表',
              path: '/order/order-member-statement',
              component: './order/order-member-statement',
              access: 'k31',
            },
            {
              name: '销售成本分析',
              path: '/order/cost-of-sales',
              component: './order/cost-of-sales',
              access: 'k31',
            },
            {
              name: '销售毛利分析',
              path: '/order/sales-gross-profit',
              component: './order/sales-gross-profit',
              access: 'k31',
            },
            {
              name: '门店销售毛利分析',
              path: '/order/gross-profit-store-sales',
              component: './order/gross-profit-store-sales',
              access: 'k31',
            },
          ],
        },
        {
          code: 'stockManager',
          name: '库存管理',
          icon: 'HddOutlined',
          path: '/stockManager',
          routes: [
            {
              code: 'stockItem',
              name: '其它物料入库',
              path: '/stockManager/stockItem',
              component: './stockManager/stockItem',
              access: 'k36',
            },
            {
              code: 'stockInventory',
              name: '库存盘点',
              path: '/stockManager/stockInventory',
              component: './stockManager/stockInventory',
              access: 'k37',
            },
            {
              code: 'stockReports',
              name: '库存报表',
              path: '/stockManager/stockReports',
              component: './stockManager/stockReports',
              access: 'k38',
            },
          ],
        },
        {
          code: 'financereport',
          name: '财务报表',
          icon: 'HddOutlined',
          path: '/financereport',
          routes: [
            {
              code: 'finance',
              name: '财务账单',
              path: '/financereport/finance',
              component: './financereport/finance',
              access: 'k37',
            },
          ],
        },
      ];
      // 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);
      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('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,
  };
};
