import {StaticResponse, RouteHandler} from 'cypress/types/net-stubbing';

function parseUrl(url: string) {
  return `http://*${url.indexOf('/') === 0 ? '' : '/'}${url}${
    url.includes('*') ? '' : '*'
  }`;
}

export function normalIntercept(
  url: string,
  fixture: string,
  options?: Omit<RouteHandler, 'fixture'>,
) {
  return cy.intercept(parseUrl(url), {fixture, ...(options ?? {})});
}

export function successIntercept(urls: string | string[]) {
  if (Array.isArray(urls)) {
    urls.forEach(function (url) {
      normalIntercept(url, 'success', {delay: 100});
    });
    return;
  }

  return normalIntercept(urls, 'success', {delay: 100});
}

export function intercept(
  url: string,
  response: (e: {
    url: string;
    reply: (params: StaticResponse) => void;
    search: URLSearchParams;
  }) => void,
) {
  cy.intercept(parseUrl(url), function (res) {
    function reply(params: StaticResponse) {
      return res.reply({delay: 100, ...params});
    }
    const url = new URL(res.url);
    const search = new URLSearchParams(url.search);

    response({url: res.url, reply, search});
  }).as(url);
}

export function dictionaryIntercept() {
  intercept('/dictionary/getDictionary', function ({search, reply}) {
    const type = search.get('type');

    switch (type) {
      case '部门字典':
        return reply({fixture: 'dictonary/department'});
      case '物料类型':
        return reply({fixture: 'dictonary/materialType'});
      case '仓库':
        return reply({fixture: 'dictonary/warehouse'});
      case '物料字典':
        return reply({fixture: 'dictonary/material'});
      case '供应商/客户':
        return reply({fixture: 'dictonary/customer'});
      case '公司':
        return reply({fixture: 'dictonary/company'});
      case '计量单位':
        return reply({fixture: 'dictonary/unit'});
    }
  });
}

export function loginSetup() {
  cy.visit('/');

  cy.get('input[name="accountName"]').type('admin');
  cy.get('input[name="accountPassword"]').type('tld123');

  cy.getTestId('login_form').submit();
}

export function loginIntercept() {
  normalIntercept('/user/login', 'login').as('loginIntercept');
}

export function menuIntercept() {
  normalIntercept('/menu/getUserMenu', 'menu/basic').as('menuIntercept');
}

export function optionsIntercept() {
  normalIntercept('/role/roleBefore', 'options/role');
  normalIntercept('/storage/getStorageAll', 'options/storage');
  normalIntercept('/userMaterial/getUser', 'options/user');
}

export function exportIntercept(urls: string | string[]) {
  if (Array.isArray(urls)) {
    urls.forEach(function (url) {
      successIntercept(url);
    });
    return;
  }
  successIntercept(urls).as('export');
}

export function beforeSetup(autoLogin = true) {
  indexedDB.deleteDatabase('filterGroup');
  loginIntercept();
  menuIntercept();
  dictionaryIntercept();
  optionsIntercept();
  normalIntercept('/gsAccess/', 'gsSuccess', {delay: 100});
  if (autoLogin) {
    loginSetup();
  }
}
