# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   test59
# FileName:      read_excel.py
# Author:       laozhao
# Datetime:     2024/3/18 15:32
# Description:
# 
# ---------------------------------------------------------------------------
import openpyxl

from InterfaceAutoTest import log_decorator, log
from InterfaceAutoTest.common.read_ini import ReadIni
from InterfaceAutoTest.common.read_json import read_json


class ReadExcel:
    @log_decorator
    def __init__(self,username, table_name, excel_path=None, case_data_path=None, expect_data_path=None, sql_data_path=None):
        """获取所有的json文件的路径，在使用read_json读取所有的json文件，再获取excel文件路径，加载工作簿，获取工作表"""
        self.read_ini = ReadIni()
        # 判断table_name的值是否为None如果为None使用ini配置文件中的值，如果不为None使用传入的值
        if table_name is None:
            table_name = self.read_ini.get_table_name("name")

        if excel_path is None and case_data_path is None and expect_data_path is None or sql_data_path is None:

            case_data_path = self.read_ini.get_file_path("case", username)
            expect_data_path = self.read_ini.get_file_path("expect", username)
            sql_data_path = self.read_ini.get_file_path("sql", username)

            excel_path = self.read_ini.get_file_path("excel", username)

        self.case_data_dict = read_json(case_data_path)
        self.expect_data_dict = read_json(expect_data_path)
        self.sql_data_dict = read_json(sql_data_path)
        try:
            wb = openpyxl.load_workbook(excel_path)
            self.ws = wb[table_name]
        except:
            raise ValueError("配置文件中的excel名称或工作表名称错误")

    def __get_cell_value(self, column: str, row: int) -> str:
        """获取指定单元格数据"""
        log.info("功能为：获取指定单元格数据"+"方法名称为："+"__get_cell_value")
        try:
            value = self.ws[column+str(row)].value
        except:
            log.error("指定的行和列错误")
            raise KeyError("指定的行和列错误")
        else:
            if value is None:
                return None
            elif value.strip():
                return value.strip()

    @log_decorator
    def module_name(self, row):
        """根据行号获取模块名称"""
        return self.__get_cell_value("b", row)

    @log_decorator
    def api_name(self, row):
        """根据行号获取接口名称"""
        return self.__get_cell_value("c", row)

    @log_decorator
    def case_title(self, row):
        """根据行号获取用例标题"""
        return self.__get_cell_value("d", row)

    @log_decorator
    def case_level(self, row):
        """根据行号获取用例等级"""
        return self.__get_cell_value("e", row)

    @log_decorator
    def case_url(self, row):
        """根据行号，获取用例的url"""
        host = self.read_ini.get_host("bpm_host")
        path = self.__get_cell_value("f", row)
        if path:
            return host+path

    @log_decorator
    def case_req_method(self, row):
        """根据行号，获取用例的请求方法"""
        return self.__get_cell_value("g", row)

    @log_decorator
    def case_mime(self, row):
        """根据行号，获取用例请求的媒体类型"""
        value = self.__get_cell_value("h", row)
        if value:
            return value.lower()

    @log_decorator
    def case_data(self, row):
        """根据行号，获取用例数据"""
        case_data_key = self.__get_cell_value("i", row)
        if case_data_key:
            module_name = self.module_name(row)
            api_name = self.api_name(row)
            try:
                return self.case_data_dict[module_name][api_name][case_data_key]
            except:
                raise KeyError("根据用例的key获取用例数据失败，请察看用例json文件中，是否有配置")

    @log_decorator
    def expect_data(self, row):
        """根据行号，获取期望数据"""
        expect_data_key = self.__get_cell_value("j", row)
        if expect_data_key:
            module_name = self.module_name(row)
            api_name = self.api_name(row)
            try:
                return self.expect_data_dict[module_name][api_name][expect_data_key]
            except:
                raise KeyError("根据期望的key获取期望数据失败，请察看期望json文件中，是否有配置")

    @log_decorator
    def sql_data(self, row):
        """根据行号，获取sql语句"""
        sql_data_key = self.__get_cell_value("l", row)
        if sql_data_key:
            module_name = self.module_name(row)
            api_name = self.api_name(row)
            try:
                return self.sql_data_dict[module_name][api_name][sql_data_key]
            except:
                raise KeyError("根据sql语句的key获取sql语句失败，请察看sql语句json文件中，是否有配置")

    @log_decorator
    def sql_type(self, row):
        """根据行号，获取sql语句类型"""
        value = self.__get_cell_value("k", row)
        if value:
            return value.lower()

    @log_decorator
    def update_key(self, row):
        """根据行号，获取更新的key"""
        return self.__get_cell_value("m", row)

    def get_data(self):
        """获取所有的测试数据，存放在一个二维列表中"""
        log.info("功能：获取所有的测试数据，存放在一个二维列表中"+"方法名称为："+"get_data")
        list_data = []
        for row in range(2, self.ws.max_row+1):
            # url
            url = self.case_url(row)
            # method
            method = self.case_req_method(row)
            if url and method:
                # mime
                mime = self.case_mime(row)
                # case_data
                case_data = self.case_data(row)
                # expect_data
                expect_data = self.expect_data(row)
                # sql_type
                sql_type = self.sql_type(row)
                # sql_data
                sql_data = self.sql_data(row)
                # update_key
                update_key = self.update_key(row)
                # 模块名称
                module_name = self.module_name(row)
                # 接口名称
                api_name = self.api_name(row)
                # 用例标题
                case_title = self.case_title(row)
                # 用例等级
                case_level = self.case_level(row)
                list_data.append([module_name, api_name, case_title, case_level, url, method, mime, case_data, expect_data, sql_type, sql_data, update_key])
        else:
            return list_data


if __name__ == '__main__':
    excel = ReadExcel(username="basic", table_name="登录-维度管理")
    print(excel.get_data())