# -*- 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")
    print('发票录入列表查询url', 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)
    # 发送请求
    i = 1
    while True:
        time.sleep(6)
        result = commonFuc().http_post(url, request_body, headers)
        print('result', result)
        try:
            data = commonFuc().analysis_json('data', result)
            total = commonFuc().analysis_json('total', data)
            if total == 0:
                print('数据暂时未同步过来，或者内网没有生成结算单')
                i = i + 1
                if i >= 100:
                    print('600秒过去了，数据还未查询出来，调用一下内网结算函数')
                    settle()
                    approval_center()
                continue
            else:
                break
        except:
            continue

    # 将发票信息写入文件
    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')
    # 将发票信息写入文件
    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 = []
    detailList = None
    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_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_1", hosName, invoiceQty, invoiceAmount,
                                                 invoiceDate, hosId, provId,hosVersion)
    print('发票缓存提交request_body', request_body)
    # 发送请求
    result = commonFuc().http_post(url, request_body, headers)
    print('发票缓存提交result', result)
    VI_id = commonFuc().analysis_json('billIds',
                                     commonFuc().analysis_json('data', result))
    VI_id= ' '.join(VI_id)
    print('VI_id',VI_id)
    # ==============发票缓存提交===========================================
    # ===============预开票列表查询====================================
    url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "listVoPage_url1")
    request_body = commonFuc().get_business_data(module, "payload3_3_1")
    print('预开票列表查询request_body', request_body)
    # 发送请求
    result = commonFuc().http_post(url, request_body, headers)
    print('预开票列表查询', 'result', result)

    provName= commonFuc().analysis_json('provName',
                                      commonFuc().analysis_json('data', commonFuc().analysis_json('data', result)))
    sumAmount= commonFuc().analysis_json('sumAmount',
                                      commonFuc().analysis_json('data', commonFuc().analysis_json('data', result)))

    # ===============预开票列表查询====================================
    # ===============预开票提交====================================
    url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "mcmsOutBalance_submitInvoice_url")
    lastModified = timeUtils().get_time_hms(1)
    createTime = timeUtils().get_time_hms(1)
    invoiceTitle = hosName
    settleMonths=settleMonth
    request_body = commonFuc().get_business_data(module, "payload3_3_2", VI_id, lastModified, createTime, uxid,
                                                 get_hosid(), provId, provName, invoiceAmount, invoiceDate,
                                                 settleMonths, invoiceQty, hosName, invoiceTitle, sumAmount)
    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)
    # ===============发票确认
    # ==============内网发票核对============
    module = "b5_spd3_core_business_flow"
    # # 登录获取用户id等信息，使用创建的用户登录===========开始
    info = FileUtils().r_info8('b2_herp3_bs', "用户名信息", 'message3')
    username = info['username1']
    password = commonFuc().get_business_data("b2_herp3_bs", "password")
    print('username,password', username, password)
    # # 获取token和projectCode
    token, projectCode, uxid, corpId, info = login(username, password, 2)
    # 登录获取用户id等信息，使用创建的用户登录============结束
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "mcmsInvoice_listVoPage_url")
    print('url', 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, "payload9", timeUtils().get_time_hms(5),
                                                 timeUtils().get_time_hms(5), get_hosid(), get_hosid())
    print('request_body', request_body)
    # 发送请求
    i = 1
    while True:
        time.sleep(6)
        result = commonFuc().http_post(url, request_body, headers)
        print('result', result)
        try:
            data = commonFuc().analysis_json('data', result)
            total = commonFuc().analysis_json('total', data)
            if total == 0:
                print('数据暂时未同步过来')
                i = i + 1
                if i >= 100:
                    print('600秒过去了，数据还未查询出来，检查一下脚本或者被测软件')
                continue
            else:
                break
        except:
            continue

    print('result', '内网发票核对', result)
    data1 = commonFuc().analysis_json('data', commonFuc().analysis_json('data', result))
    VI_id = commonFuc().analysis_json('id', data1[0])
    print('VI_id', VI_id)
    # ==============发票列表查询
    # ==============发票核对提交
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "mcmsInvoice_invoiceUpdateStatusList_url")
    print('url', url)
    request_body = commonFuc().get_business_data(module, "payload10", VI_id, get_hosid())
    print('request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('result', result)
    # ==============发票核对提交
    # ==============内网发票核对============
    # ==============内网发票提交开始
    # 列表查询
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "mcmsInvoice_listVoPage_url")
    print('内网发票提交url', url)
    request_body = commonFuc().get_business_data(module, "payload11", timeUtils().get_time_hms(5),
                                                 timeUtils().get_time_hms(5), get_hosid(), get_hosid())
    print('内网发票提交request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('result', '内网发票提交列表查询结果', result)
    data1 = commonFuc().analysis_json('data', commonFuc().analysis_json('data', result))
    total = commonFuc().analysis_json('total', commonFuc().analysis_json('data', result))
    VI_id2='VI_id2'
    if total == 0:
        print('检查被测程序，发票提交列表查询数据是否正确')
    else:
        for i in range(total):
            VI_id2 = commonFuc().analysis_json('id', data1[i])
            if VI_id2 == VI_id:
                break
    print('VI_id2', VI_id2)
    # ==============发票提交,下一步归档
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "mcmsInvoice_invoiceUpdateStatusList_url")
    print('url', url)
    request_body = commonFuc().get_business_data(module, "payload12", VI_id, get_hosid())
    print('request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('result', '发票提交,下一步归档', result)
    # ==============发票提交，下一步归档
    # ==============发票归档列表查询
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "mcmsInvoice_listVoPage_url")
    print('url', url)
    request_body = commonFuc().get_business_data(module, "payload13", timeUtils().get_time_hms(5),
                                                 timeUtils().get_time_hms(5), get_hosid(), get_hosid())
    print('request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('result', '发票归档列表查询', result)
    data1 = commonFuc().analysis_json('data', commonFuc().analysis_json('data', result))
    total = commonFuc().analysis_json('total', commonFuc().analysis_json('data', result))
    VI_id3='VI_id3'
    if total == 0:
        print('检查被测程序，发票归档列表查询查询数据是否正确')
    else:
        for i in range(total):
            VI_id3 = commonFuc().analysis_json('id', data1[i])
            if VI_id3 == VI_id2:
                break
    print('VI_id3', VI_id3)
    # ==============发票归档列表查询
    # ==================发票归档提交
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "mcmsInvoice_invoiceUpdateStatusList_url")
    print('url', url)
    request_body = commonFuc().get_business_data(module, "payload14", VI_id, get_hosid())
    print('request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('result', '发票归档提交,下一步付款', result)
    # ==================发票归档提交
    # ==================付款单列表查询
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "mcmsInvoice_listVoPage_url")
    print('url', url)
    request_body = commonFuc().get_business_data(module, "payload15", get_hosid(), get_hosid())
    print('request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('result', '付款单列表查询', result)
    data1 = commonFuc().analysis_json('data', commonFuc().analysis_json('data', result))
    total = commonFuc().analysis_json('total', commonFuc().analysis_json('data', result))
    VI_id4='VI_id4'
    if total == 0:
        print('检查被测程序，发票归档列表查询查询数据是否正确')
    else:
        for i in range(total):
            VI_id4 = commonFuc().analysis_json('id', data1[i])
            if VI_id4 == VI_id3:
                break
    print('VI_id4', VI_id4)
    # ==================付款单列表查询
    # ==================付款提交
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "mcmsInvoice_genPaymentBills_url")
    print('url', url)
    request_body = commonFuc().get_business_data(module, "payload16", VI_id, get_hosid())
    print('request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('result', '付款提交', result)
    # 断言
    code = commonFuc().analysis_json('code', result)
    data = commonFuc().analysis_json('data', result)
    if code == 0 and data == 1:
        commonFuc().check_text_exist(0, result)
    else:
        commonFuc().check_text_exist('error', result)
    # ==================付款提交
    # ==============内网发票提交
    # ================发票查询列表页面验证

    # ================发票查询列表页面验证


try:
    OBH_ID = settle()
    # 调用审批结算单
    approval_center(OBH_ID)
    from air_case.public1.public1.public1 import *
    invoice(2,OBH_ID)
except Exception as e:
    print('脚本出现异常，请检查脚本或者数据')
    print("发生异常：", str(e))
    traceback.print_exc()
else:
    commonFuc().check_text_exist_result_text('succees', 'succees')
