# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   PythonProject_1
# FileName:      read_excel.py
# Author:       H_M
# Datetime:     2024/9/3 18:10
# Description:
# ---------------------------------------------------------------------------
import logging

from MyApiAutoTest_v3.common.basic_read_ini import BasicReadIni
from MyApiAutoTest_v3.common.user_read_ini import UserReadIni
import openpyxl

from MyApiAutoTest_v3.common.read_json import read_json
from MyApiAutoTest_v3 import log
from MyApiAutoTest_v3.data_config.settings import *


class ReadExcel:
    def __init__(self, username):
        """创建ReadIni对象，获取excel路径，打开工作簿"""
        self.ini = UserReadIni(username)
        excel_path = self.ini.get_file_path(FILE_EXCEL)
        print(excel_path)
        try:
            wb = openpyxl.load_workbook(excel_path)
            self.ws = wb[self.ini.get_table(TABLE_kEY)]
        except Exception as e:
            log.error(f"打开工作簿错误，可能为excel路径错误，路径为{excel_path}, 也可能为工作表错误，工作表为{self.ini.get_table('table_name')}, 错误为{e}")
            raise e
        # json文件的路径
        case_path = self.ini.get_file_path(FILE_CASE)
        expect_path = self.ini.get_file_path(FILE_EXPECT)
        sql_path = self.ini.get_file_path(FILE_SQL)

        # 获取json文件的数据
        self.case_data = read_json(case_path)
        self.expect_data = read_json(expect_path)
        self.sql_data = read_json(sql_path)

    def __get_cell_data(self, column, row):
        """获取excel单元格的数据"""
        try:
            cell_value = self.ws[column + str(row)].value
        except Exception as e:
            log.error(f"获取单元格数据错误，其中列为{column}, 行为{row}, 错误信息为{e}")
            raise e
        else:
            if cell_value is None:
                return None
            elif cell_value.strip():
                return cell_value.strip()

    def get_module(self, row):
        """获取模块名称"""
        return self.__get_cell_data(MODULE, row)

    def get_api(self, row):
        """获取接口名称"""
        return self.__get_cell_data(API, row)

    def get_title(self, row):
        """获取接口名称"""
        return self.__get_cell_data(TITLE, row)

    def get_level(self, row):
        """获取接口名称"""
        return self.__get_cell_data(LEVEL, row)

    def get_url(self, row):
        """获取接口url"""
        case_url = self.__get_cell_data(URL, row)
        if case_url:
            return BasicReadIni().get_host(HOST_KEY) + case_url

    def get_method(self, row):
        """获取请求方法"""
        return self.__get_cell_data(REQ_METHOD, row)

    def get_mediatype(self, row):
        """获取媒体类型"""
        mediatype = self.__get_cell_data(MIME, row)
        if mediatype:
            return mediatype.strip().lower()

    def get_case_data(self, row):
        """获取用例数据"""
        case_data = self.__get_cell_data(CASE_DATA, row)
        if case_data:
            module_name = self.get_module(row)
            api_name = self.get_api(row)
            return self.case_data[module_name][api_name][case_data]

    def get_expect_data(self, row):
        """获取期望数据"""
        expect_data = self.__get_cell_data(EXPECT_DATA, row)
        if expect_data:
            module_name = self.get_module(row)
            api_name = self.get_api(row)
            return self.expect_data[module_name][api_name][expect_data]

    def get_sql_data(self, row):
        """获取sql数据"""
        sql_data = self.__get_cell_data(SQL_DATA, row)
        if sql_data:
            module_name = self.get_module(row)
            api_name = self.get_api(row)
            return self.sql_data[module_name][api_name][sql_data]

    def get_sql_type(self, row):
        """获取sql语句的类型"""
        sql_type = self.__get_cell_data(SQL_TYPE,  row)
        if sql_type:
            return sql_type.lower()

    def get_update_key(self, row):
        """获取需要更新的key"""
        return self.__get_cell_data(UPDATE_KEY,  row)

    def get_data(self):
        """获取需要的数据，并放在列表中返回"""
        list1 = []
        for row in range(2, self.ws.max_row+1):
            module = self.get_module(row)
            api = self.get_api(row)
            title = self.get_title(row)
            level = self.get_level(row)
            url = self.get_url(row)
            method = self.get_method(row)
            mediatype = self.get_mediatype(row)
            case = self.get_case_data(row)
            expect = self.get_expect_data(row)
            sql_type = self.get_sql_type(row)
            sql = self.get_sql_data(row)
            update_key = self.get_update_key(row)
            # 过滤空行
            if url is not None and method is not None and expect is not None:
                list1.append([module, api, title, level, url, method, mediatype, case, expect, sql, sql_type, update_key])
        return list1




