# -*- encoding=utf8 -*-
import json
import traceback

from air_case.b1_herp3_login.登录内网系统.登录内网系统 import login_system
from air_case.public1.public1.public1 import *

from common.fileUtls import FileUtils
from common.run_cmd_script import execute_command
from common.timeUtils import timeUtils
from airtest.core.api import using

__author__ = "xiaohesheng"

"""
case_tag:api,spd_core,a_a8流程五_中心库入库结算_正结算3_外网开票,id2302,id2302-8,sit,on
主数据平台:a_a8流程五_中心库入库结算_正结算3_外网开票
python runner_test.py tag id2302-8 debug mdm3
"""

from common.common_func import commonFuc
from airtest.core.api import using
import sys
import time

module = "b5_spd3_core_business_flow"


def invoice():
    # # 登录获取用户id等信息，使用创建的用户登录===========开始
    info = FileUtils().r_info8('b5_spd3_core_business_flow', "供货关系申请2", 'message')
    # print(info)
    username = info['e_username']
    password = commonFuc().get_business_data("b2_herp3_bs", "password1")
    token, projectCode, uxid, corpId, info = login(username, password)
    # print(token, projectCode, uxid, corpId, info)
    # 登录获取用户id等信息，使用创建的用户登录============结束
    module = "a6_mdm3_si"
    # 发票录入列表查询=================================================
    url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "listGoodsPage_url")
    # 获取请求头信息
    headers = commonFuc().get_business_data(module, "json_headers2",
                                            commonFuc().get_business_data(module, "json_contentType"), token,
                                            projectCode)

    request_body = commonFuc().get_business_data(module, "payload2_1_1", get_hosid(), get_branch_id())

    # print('request_body',request_body)
    # 发送请求
    while True:
        time.sleep(3)
        result = commonFuc().http_post(url, request_body, headers)
        print('result', result)
        try:
            data = commonFuc().analysis_json('data', result)
            data1 = commonFuc().analysis_json('data', data)
            pid = commonFuc().analysis_json('pid', data1[0])
        except:
            continue
        else:
            break
    # 将发票信息写入文件
    data = commonFuc().analysis_json('data', result)
    data1 = commonFuc().analysis_json('data', data)
    list_a = []
    list_b = []
    list_c = []
    list_a.append(data1[0])
    list_b.append(data1[0])
    list_c.append(data1[0])
    # print('list_a', len(list_a), list_a)
    info = (list_a, list_b, list_c)
    titlename = ('list_a', 'list_b', 'list_c')
    # 将验收单详细信息写入到文件中"a6_mdm3_si"
    FileUtils().w_info8(info, module, '结算开票信息', titlename, 'message')
    # 发票录入列表查询=================================================
    # ===========发票暂存=======================================
    url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "saveCacheBatch_url")
    print(url)
    # 从文件中获取必要信息
    info = FileUtils().r_info8(module, "结算开票信息", 'message')
    # print('info', info)
    list_a = info['list_a']
    print('list_a', list_a,type(list_a),len(list_a))
    pid='pid'
    settleMonth = "settleMonth"
    hosGoodsId = 'hosGoodsId'
    batchCode = 'batchCode'
    distrDetailId = 'distrDetailId'
    distrId='distrId'
    distrOrderNo='distrOrderNo';settlePrice='settlePrice';maxSettleQty='maxSettleQty'
    maxSettleAmount='maxSettleAmount';curSettleQty='curSettleQty';curSettleAmount='curSettleAmount'
    leftSettleQty='leftSettleQty';leftSettleAmount='leftSettleAmount';hosId='hosId';provId='provId'
    branchId='branchId'; balanceDetId='balanceDetId'; purMode='purMode';barCode='barCode';viewId='viewId'
    for i in list_a:
        pid = i['pid']
        settleMonth = i['settleMonth']
        hosGoodsId = i['hosGoodsId']
        detailList = i['detailList']
        for j in detailList:
            batchCode = j['batchCode']
            distrDetailId=j['distrDetailId']
            distrId = j['distrId']
            distrOrderNo = j['distrOrderNo']
            settlePrice = j['settlePrice']
            # maxSettleQty = j['leftSettleQty']
            # maxSettleAmount = j['leftSettleAmount']
            # curSettleQty = j['curSettleQty']
            # curSettleAmount = j['curSettleAmount']
            # leftSettleQty = j['leftSettleQty']
            leftSettleAmount = j['leftSettleAmount']
            hosId = j['hosId']
            provId = j['provId']
            branchId = j['branchId']
            balanceDetId = j['balanceDetId']
            purMode = j['purMode']
            barCode = j['barCode']
            viewId=j['viewId']
            break
    list2=[]
    for i in list_a:
        detailList = i['detailList']
    list2=detailList
    for k in list2:
        maxSettleQty = k['leftSettleQty']
        maxSettleAmount= k['settlePrice']
        curSettleQty= k['curSettleQty']
        curSettleAmount=k['curSettleAmount']
        leftSettleQty=k['leftSettleQty']

    request_body = commonFuc().get_business_data(module, "payload3_1_1_1", pid, settleMonth, hosGoodsId, batchCode,
                                                 distrDetailId, distrId, distrOrderNo, settlePrice, maxSettleQty,
                                                 maxSettleAmount, curSettleQty, curSettleAmount, leftSettleQty,leftSettleAmount, hosId,
                                                 provId,
                                                 branchId, balanceDetId,purMode, barCode,viewId)
    print('request_body', request_body)
    # request_body = "[" + str(request_body) + "]"
    # print('request_body', request_body)
    # # string = "这是一段包含'单引号'的文本"
    # new_request_body = request_body.replace("'", '"')
    # new_request_body1 = new_request_body.replace("\\", '\\\\')
    # new_request_body2=new_request_body1.replace("None", 'null')
    # print(new_request_body2)
    # request_body_json = json.loads(new_request_body2,encoding='utf-8')
    request_body_json=get_process_list(request_body)
    result = commonFuc().http_post(url, request_body_json, headers)
    print('result',result)
    # ===========发票暂存===============================================
    #==============发票提交===========================================
    url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "submitCache_url")
    hosVersion=3
    hosName=commonFuc().get_business_data(module,'hosName')
    invoiceQty=leftSettleQty
    invoiceAmount=leftSettleAmount
    invoiceDate=timeUtils().get_time_hms(5)
    request_body = commonFuc().get_business_data(module, "payload3_2_2_2",hosName,invoiceQty,invoiceAmount,invoiceDate,hosId,hosVersion)
    print('request_body',request_body)
    # 发送请求
    result = commonFuc().http_post(url, request_body, headers)
    print('result', result)
    #==============发票提交===========================================
    #===============发票确认列表查询
    url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "listVoPage_url1")

    request_body = commonFuc().get_business_data(module, "payload3_3")

    # 发送请求
    result = commonFuc().http_post(url, request_body, headers)
    print('result', result)
    data=commonFuc().analysis_json('data', result)
    data1=commonFuc().analysis_json('data', data)
    id1 = commonFuc().analysis_json('id', data1[0])
    print(id1)
    #===============发票确认列表查询
    #===============发票确认
    url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "invoiceUpdateStatus_url")

    request_body = commonFuc().get_business_data(module, "payload3_4", id1)

    # 发送请求
    result = commonFuc().http_post(url, request_body, headers)
    print('result', result)
    #===============发票确认

try:
    invoice()
except Exception as e:
    print('脚本出现异常，请检查脚本或者数据')
    print("发生异常：", str(e))
    traceback.print_exc()
else:
    commonFuc().check_text_exist_result_text('succees', 'succees')
