# -*- encoding=utf8 -*-
__author__ = "liguangyu"

"""
case_tag:cmdc_api,cmdc植入上报导出功能验证,00,00-34,sit,be
主数据平台:后台运营系统植入上报导出接口
"""

from common.common_func import commonFuc
from air_case.cmdc_login.后台管理系统登录.后台管理系统登录 import CmdcDoLogin
from common.handle_excel import HandleExcel
from common.db.db import mySql
import random
import requests
import json
import os

module = "cmdc_special_version"

# 第一步登录后台运营系统获取token
username = commonFuc().get_business_data(module, "username_do_be")
password = commonFuc().get_business_data(module, "password_do_be")
# 获取登录后Cmdc_access_token
cmdc_access_token = CmdcDoLogin(username, password).get_token()
headers = commonFuc().get_business_data(module, "json_headers", cmdc_access_token)

# 数据库操作
mysql_handle = mySql()
# 获取conf.ini文件中配置的数据库信息
host, port, user, pwd = mysql_handle.getConf(db="cmdc_db_be")

# 在数据库中已存在的植入上报数据对应的产品线信息
sql = "SELECT t.productLineCode, t.companyCode FROM `cmdc-order`.tc_report t where deleteSign = 0"
productLineCode = mysql_handle.selectSql(host, port, user, pwd, "cmdc-order", sql)[0][0]
companyCode = mysql_handle.selectSql(host, port, user, pwd, "cmdc-order", sql)[0][1]

# 第二步获取上报植入列表
url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "url33")
request_body = commonFuc().get_business_data(module, "payload33_1", companyCode, productLineCode)

# 发送请求
result = requests.post(url, json=request_body, headers=headers)
result = json.loads(result.content)
# print(result)
# 生成随机数
report_random = random.randint(0, len(result["data"]["list"]) - 1)
# 获取上报植入信息
batchNumber = result["data"]["list"][report_random]["batchNumber"]


# 第三步进行植入上报信息导出
url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "url34")
request_body = commonFuc().get_business_data(module, "payload34", companyCode, productLineCode, batchNumber)

"""

 场景: 植入上报导出功能验证
 用例名称：植入上报导出功能验证
 输出：{"batchNumber":"%s"}
"""

# 发送请求
result = requests.post(url, json=request_body, headers=headers)
# 获取接口响应时间
api_time = float(result.elapsed.total_seconds())

# 获取文件
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
file_path = BASE_DIR + "/data/cmdc_files/上报植入导出明细.xlsx"

# 获取到导出文件存入cmdc_files文件中
with open(file_path, 'wb') as f:
    f.write(result.content)

# 获取导出文件中生产批次号
excel = HandleExcel(file_path, "Sheet1")
result = {"batchNumber": excel.read_data()[0].get("生产批号")}

# 将接口响应时间添加至result
result["api_time"] = api_time

# 获取预期结果
check_dict = commonFuc().get_business_data(module, "checkDict34", batchNumber)
# print(check_dict)
# 断言实际结果中是否包含预期结果的内容
commonFuc().check_result(check_dict, result)
