#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@File    :   login_page.py
@Time    :   2024/11/06 20:47:19
@Author  :   dulip3ng
@Version :   1.0
@Desc    :   None
'''

from pages.base_page import BasePage
from pages.locator.login_page_locator import LoginPageLocator
from playwright.sync_api import Page, expect

class LoginPage(BasePage):

    def _choice_db(self, db:str):
        """
        设置账套
        :param db: 账套名
        :return: None
        """
        try:
            self.page.locator(LoginPageLocator.DATA_CENTER_ARROW_DOWN_LOC).click()
            # 偶发页面加载后直接点击账套下拉列表，下拉选项闪现点击无反应。判断点击后1s内下拉选项是否显示，如不显示重新点击
            expect(self.page.locator(LoginPageLocator.DB_SELECT_ITEM_ARGS_LOC % db)).to_be_visible(timeout=1000)
        except AssertionError:
            self._choice_db(db)
            return
        self.page.locator(LoginPageLocator.DB_SELECT_ITEM_ARGS_LOC % db).click()

    def _set_username(self, username:str):
        """
        设置用户名
        :param username: 用户名
        :return: None
        """
        self.page.locator(LoginPageLocator.USERNAME_LOC).fill(username)

    def _set_password(self, password:str):
        """
        设置密码
        :param password: 密码
        :return: None
        """
        self.page.locator(LoginPageLocator.PASSWORD_LOC).fill(password)

    def _click_login(self):
        """
        点击登录按钮
        :return: None
        """
        self.page.locator(LoginPageLocator.LOGIN_BUTTON_LOC).click()

    def _click_online_alter_if_needed(self):
        """
        2s内如出现账号已登录是否继续登录确认框，点击确认
        :return: None
        """
        try:
            locator = self.page.locator(LoginPageLocator.USER_ONLINE_ALTER_OK_LOC)
            expect(locator).to_be_enabled(timeout=2000)
            locator.click()
        except AssertionError:
            pass

    def login(self, db:str, username:str, password:str):
        """
        系统登录
        :param db: 账套名
        :param username: 用户名
        :param password: 密码
        :return: None
        """
        self._choice_db(db)
        self._set_username(username)
        self._set_password(password)
        self._click_login()
        self._click_online_alter_if_needed()
