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

describe('角色管理', function() {
  beforeEach(function() {
    loginIntercept();
    menuIntercept();
    loginSetup();
    menuTrigger(1, 1);
  });

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

      if (search.has('roleName') && search.get('roleName').length)
        return reply({fixture: 'role/search'});

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

    successIntercept('/role/addRole');
    successIntercept('/role/updateRole');
    successIntercept('/role/delRole');
    normalIntercept('/menu/getMenu', 'menu/all');
  });

  it('角色列表', function() {
    validateTableList('role_table');
  });

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

    cy.get('#filter_roleName').type('roleName');
    validate();
  });

  const {validateAdd, validateEdit} = validatePut(
    'role_modal',
    '角色',
  );

  it('新增操作', function() {
    validateAdd(function() {
      cy.get('#operation_roleName').type('roleName');
      cy.get('#operation_roleRemarks').type('roleRemarks');
    });
  });

  it('修改操作', function() {
    validateEdit('role_table', function() {
      cy.get('#operation_roleName').should('have.value', '仓库管理员');
      cy.get('#operation_roleRemarks').should('have.value', 'cangk');
    });
  });

  it('删除操作', function() {
    validateDelete('role_table');
  });

  it('设置菜单权限', function() {
    cy.getTestId('role_table').find('table').find('.ant-table-tbody')
      .children('.ant-table-row').first().find('td').last().children().last()
      .trigger('click');

    cy.getTestId('role_tree_modal').find('h3')
      .should('include.html', '菜单权限');
    cy.getTestId('role_tree_modal').should('exist').and('be.visible');

    cy.getTestId('role_tree').find('.ant-tree-list-holder-inner')
      .find('.ant-tree-treenode').each(function(res, idx) {
        idx <= 3
          ? expect(res.hasClass('ant-tree-treenode-checkbox-checked')).to.true
          : expect(res.hasClass('ant-tree-treenode-checkbox-checked')).to.false;
      }).should('have.length', 9);

    cy.getTestId('role_tree_modal').find('form').submit();

    cy.getTestId('modal_btn_group').find('.ant-btn-loading').should('exist');

    cy.get('.ant-message-notice-content').should('include.text', '设置成功');
    cy.getTestId('role_tree_modal').should('not.exist');
  });
});
