import {
  loginIntercept,
  menuIntercept,
  loginSetup,
  menuTrigger,
  validateTableSearch,
  validateTableList,
  validatePut,
  validateDelete,
  successIntercept,
  intercept,
  exportIntercept,
  validateExport,
} from './utils';

describe('部门管理', function() {
  beforeEach(function() {
    loginIntercept();
    menuIntercept();
    loginSetup();
    menuTrigger(1, 2);
  });

  beforeEach(function() {
    intercept(
      '/department/getDepartment',
      function({url: reqUrl, reply}) {
        const url = new URL(reqUrl);
        const search = new URLSearchParams(url.search);

        if (search.has('departmentName') && search.get('departmentName').length)
          return reply({fixture: 'department/nameSearch'});
        if (search.has('code') && search.get('code').length)
          return reply({fixture: 'department/codeSearch'});

        const page = search.get('page');
        reply({fixture: page === '1' ? 'department/list1' : 'department/list2'});
      },
    );

    successIntercept('/department/addDepartment');
    successIntercept('/department/updateDepartment');
    successIntercept('/department/delDepartment');
    exportIntercept('/department/export');
  });

  const TABLE_NAME = 'department_table',
        MODAL_NAME = 'department_modal',
        LABEL = '部门';

  it('部门列表', function() {
    validateTableList(TABLE_NAME);
  });

  it('搜索', function() {
    const validate = validateTableSearch(TABLE_NAME);

    cy.get('#filter_departmentCode').type('TLD0004');
    cy.get('#filter_departmentName').clear();
    validate('searchCode');

    cy.get('#filter_departmentName').type('name');
    cy.get('#filter_departmentCode').clear();
    validate('searchName');
  });

  const {validateAdd, validateEdit} = validatePut(
    MODAL_NAME,
    LABEL,
  );

  it('新增部门', function() {
    function fillField() {
      cy.getTestId('field_departmentName').type('测试部门名称');
    }

    validateAdd(fillField);
  });

  it('修改部门', function() {
    function validateField() {
      cy.getTestId('field_departmentName').should('have.value', '包装部门');
    }

    validateEdit(TABLE_NAME, validateField);
  });

  it('删除部门', function() {
    validateDelete(TABLE_NAME, LABEL);
  });

  it('导出', function() {
    validateExport();
  });
});
