# -*- encoding=utf8 -*-
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_a7流程五_中心库入库结算_正结算3_内网验收入库结算,id2302,id2302-7,sit,on
主数据平台:a_a7流程五_中心库入库结算_正结算3_内网验收入库结算
python runner_test.py tag id2302-7 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 check_accept_order(type=1):
    # execute_command("python runner_test.py tag id2302-6 debug mdm3")
    # # 登录获取用户id等信息，使用创建的用户登录===========开始
    info = FileUtils().r_info8('b2_herp3_bs', "用户名信息", 'message3')
    # print(info)
    username = info['username1']

    password = commonFuc().get_business_data("b2_herp3_bs", "password")
    # username = '001f90380'
    # password='1qaz!QAZ'
    print('username,password', username, password)
    # # print(username, password,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    # # 获取token和projectCode
    token, projectCode, uxid, corpId, info = login_system(username, password).get_token()
    # 登录获取用户id等信息，使用创建的用户登录============结束

    # =========================查询待验收订单======================
    module = "b5_spd3_core_business_flow"
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "check_wait_page_url")
    print('url', url)
    # 获取请求头信息
    headers = commonFuc().get_business_data(module, "json_headers2",
                                            commonFuc().get_business_data(module, "json_contentType"), token,
                                            projectCode)
    branch_id = FileUtils().r_info('b2_herp3_bs', '院区新增')["branch_id"]
    hos_id = branch_id[0:5]
    if type == 1:
        sourceOrderNo = FileUtils().r_info8(module, '低值配送单号', 'message10')["distrBillId1"]
    elif type == 2:
        sourceOrderNo = FileUtils().r_info8(module, '高值配送单号', 'message10')["distrBillId1"]
    elif type == 3:
        sourceOrderNo = FileUtils().r_info8(module, '试剂配送单号', 'message10')["distrBillId1"]
    else:
        sourceOrderNo = FileUtils().r_info8(module, '低值配送单号', 'message10')["distrBillId1"]
    request_body = commonFuc().get_business_data(module, "payload", hos_id, branch_id, sourceOrderNo)
    print('request_body', request_body)
    # 发送请求
    while True:
        result = commonFuc().http_post(url, request_body, headers)
        print('result', result)
        # 断言
        code = commonFuc().analysis_json('code', result)
        data = commonFuc().analysis_json('data', result)
        total = commonFuc().analysis_json('total', data)
        if total == 1:
            break
        else:
            time.sleep(6)

    data = commonFuc().analysis_json('data', result)
    data1 = commonFuc().analysis_json('data', data)
    list_a = []
    list_b = []
    list_c = []
    list_a.append(data1)
    list_b.append(data1)
    list_c.append(data1)
    # 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, 'b5_spd3_core_business_flow', '验收单信息', titlename, 'message13')
    # 从message13文件中获取信息
    info = FileUtils().r_info8('b5_spd3_core_business_flow', "验收单信息", 'message13')
    # print('info', info)
    list_a = info['list_a']
    print('list_a', list_a)
    sourceType = "sourceType"
    billMode = 'billMode'
    recOrgId = 'recOrgId'
    recOrgName = 'recOrgName'
    sourceOrgId = 'sourceOrgId'
    sourceOrgName = 'sourceOrgName'
    sourceVersion = 'sourceVersion'
    tbStatus = 'tbStatus'
    for i in list_a:
        print('i', i)
        for j in i:
            sourceType = j["sourceType"]
            billMode = j["billMode"]
            recOrgId = j['recOrgId']
            recOrgName = j['recOrgName']
            sourceOrgId = j['sourceOrgId']
            sourceOrgName = j['sourceOrgName']
            sourceVersion = j['sourceVersion']
            tbStatus = j['tbStatus']
            break

    # =========================查询待验收订单======================
    # ==============================查看订单详情==================

    sourceId = sourceOrderNo
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "check_wait_detail_url")
    print('url', url)
    request_body = commonFuc().get_business_data(module, "payload1", sourceId, sourceType, billMode, branch_id)

    # print('request_body',request_body)
    # 发送请求
    while True:
        time.sleep(6)
        result = commonFuc().http_post(url, request_body, headers)
        code = commonFuc().analysis_json('code', result)
        if code == 0:
            break
        else:
            print('验收单数据未同步完成，等待6秒')
    print('result', result)
    # 断言
    data = commonFuc().analysis_json('data', result)
    list_a = []
    list_b = []
    list_c = []
    list_a.append(data)
    list_b.append(data)
    list_c.append(data)
    # 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, 'b5_spd3_core_business_flow', '验收单详情信息', titlename, 'message14')
    # 读取viewId
    info = FileUtils().r_info8('b5_spd3_core_business_flow', "验收单详情信息", 'message14')
    # print('info', info)
    list_a = info['list_a']
    print('list_a', list_a)
    viewId = "viewId"
    settlement = 'settlement'
    recTemperature = 'recTemperature'
    recHumidity = 'recHumidity'
    hosGoodsId='hosGoodsId'
    distrQty='distrQty'
    distrPkgQty='distrPkgQty'
    for i in list_a:
        for j in i:
            viewId = j["viewId"]
            settlement = j["settlement"]
            recTemperature = j['recTemperature']
            recHumidity = j['recHumidity']
            hosGoodsId= j['hosGoodsId']
            distrQty= j['distrQty']
            distrPkgQty=j['distrPkgQty']

        break
    # ==============================查看订单详情==================
    # ========设置验收全部合格
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "check_barcode_save_url")
    print('check_barcode_save_url', url)
    sourceBillId = sourceId
    request_body = commonFuc().get_business_data(module, "payload2", sourceBillId, viewId)

    print('设置验收全部合格request_body',request_body)
    # 发送请求
    time.sleep(6)

    while True:
        result = commonFuc().http_post(url, request_body, headers)
        print('result', result)
        data = commonFuc().analysis_json('data', result)
        code= commonFuc().analysis_json('code', result)
        print(code)
        if code ==0 and len(data)>=100:
            break
        else:
            print('设置产品合格出现问题')
            time.sleep(6)
            continue

    # ========设置验收全部合格
    # =============提交验收单========================
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "check_submit_url")
    deptId = recOrgId
    deptName = recOrgName
    provId = sourceOrgId
    provName = sourceOrgName
    createUser = uxid
    sourceNo = sourceId
    checkQty=distrQty
    checkPkgQty=distrPkgQty
    time.sleep(6)
    request_body = commonFuc().get_business_data(module, "payload3", billMode, branch_id, deptId, deptName, hos_id,
                                                 provId, provName, recOrgId, recOrgName, sourceId, sourceVersion,
                                                 sourceType, tbStatus, createUser, sourceNo, viewId, hosGoodsId,viewId, settlement,
                                                 checkQty,distrPkgQty,checkPkgQty,recTemperature, recHumidity)

    print('request_body', '提交验收单', request_body)
    # 发送请求
    while True:
        time.sleep(3)
        result = commonFuc().http_post(url, request_body, headers)
        print('result', result)
        CHECK_NO = commonFuc().analysis_json('data', result)
        code = commonFuc().analysis_json('code', result)
        if code == 0:
            break

    info = (CHECK_NO, CHECK_NO)
    titlename = ('CHECK_NO1', 'CHECK_NO2')
    FileUtils().w_info8(info, 'b5_spd3_core_business_flow', '验收单号', titlename, 'message15')


# 入库上架
def putaway():
    # # 登录获取用户id等信息，使用创建的用户登录===========开始
    info = FileUtils().r_info8('b2_herp3_bs', "用户名信息", 'message3')
    # print(info)
    username = info['username1']

    password = commonFuc().get_business_data("b2_herp3_bs", "password")
    # username = '001f90380'
    # password='1qaz!QAZ'
    print('username,password', username, password)
    # # print(username, password,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    # # 获取token和projectCode
    token, projectCode, uxid, corpId, info = login_system(username, password).get_token()
    # 登录获取用户id等信息，使用创建的用户登录============结束
    # =====================上架入库列表查询==========================
    headers = commonFuc().get_business_data(module, "json_headers2",
                                            commonFuc().get_business_data(module, "json_contentType"), token,
                                            projectCode)
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "stock_in_page_url")
    print(url)
    branch_id = FileUtils().r_info('b2_herp3_bs', '院区新增')["branch_id"]
    hosId = branch_id[0:5]
    request_body = commonFuc().get_business_data(module, "payload6", branch_id, hosId)
    result = commonFuc().http_post(url, request_body, headers)
    print('result', result)
    data = commonFuc().analysis_json('data', result)
    total = commonFuc().analysis_json('total', data)
    if total >= 1:
        # 将上架入库列表数据写入文件
        data = commonFuc().analysis_json('data', result)
        data1 = commonFuc().analysis_json('data', data)
        list_a = []
        list_b = []
        list_c = []
        list_a.append(data1)
        list_b.append(data1)
        list_c.append(data1)
        # 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, 'b5_spd3_core_business_flow', '上架入库列表数据', titlename, 'message16')
    # =====================上架入库列表查询==========================
    # =============查看验收单详情========================
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "stock_detail_url")
    print('查看验收单详情',url)
    deptid1 = FileUtils().r_info8('b2_herp3_bs', '所有科室id', 'message6')["deptid1"]
    areaCode = FileUtils().r_info8('b2_herp3_bs', 'shelfinfo', 'message7')["shelfCode"]
    branch_id = FileUtils().r_info('b2_herp3_bs', '院区新增')["branch_id"]
    hosId = branch_id[0:5]
    # 从message16文件中获取信息
    info = FileUtils().r_info8('b5_spd3_core_business_flow', "上架入库列表数据", 'message16')
    list_a = info['list_a']
    print('list_a', list_a)
    sourceId = 'sourceId'
    for i in list_a:
        for j in i:
            sourceId = j['sourceId']
            break
    # 从message13文件中获取信息
    info = FileUtils().r_info8('b5_spd3_core_business_flow', "验收单信息", 'message13')
    # print('info', info)
    list_a = info['list_a']
    print('list_a', list_a)
    sourceType = "sourceType"
    for i in list_a:
        print('i', i)
        for j in i:
            sourceType = j["sourceType"]
            break

    request_body = commonFuc().get_business_data(module, "payload4", deptid1, areaCode, hosId, sourceId, sourceType)

    print('request_body', 'd', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('result', result)
    # 将验收单详情写入文件
    data = commonFuc().analysis_json('data', result)
    list_a = []
    list_b = []
    list_c = []
    list_a.append(data)
    list_b.append(data)
    list_c.append(data)
    # 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, 'b5_spd3_core_business_flow', '验收单库存详情信息', titlename, 'message17')
    time.sleep(6)
    # =============    # =============查看验收单详情================================================
    # ================================入库上架===================
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "stock_detail_submit_url")
    print(url)
    viewId = 'viewId'
    shelfCode = 'shelfCode'
    sourceId = 'sourceId'
    sourceType = 'PSD'
    sourceVersion = '0'
    targetDeptId = deptid1
    targetDeptName = 'targetDeptName'
    targetAreaCode = 'targetAreaCode'
    targetAreaName = 'targetAreaName'
    # 从message17文件中获取信息
    info = FileUtils().r_info8('b5_spd3_core_business_flow', "验收单库存详情信息", 'message17')
    # print('info', info)
    list_a = info['list_a']
    print('list_a', list_a)
    for i in list_a:
        print('i', i)
        for j in i:
            viewId = j["viewId"]
            shelfCode = j['shelfCode']
            sourceId = j['id']
            break
    # 从message16文件中获取信息
    info = FileUtils().r_info8('b5_spd3_core_business_flow', "上架入库列表数据", 'message16')
    list_a = info['list_a']
    print('list_a', list_a)
    for i in list_a:
        for j in i:
            sourceId = j['sourceId']
            targetAreaName = j['areaName']
            targetAreaCode = j['areaCode']
            break
    request_body = commonFuc().get_business_data(module, "payload5", viewId, shelfCode, sourceId, sourceType,
                                                 sourceVersion, targetDeptId,
                                                 targetDeptName, targetAreaCode, targetAreaName)
    print('request_body', request_body)
    time.sleep(3)
    result = commonFuc().http_post(url, request_body, headers)
    print('result', result)
    # ================================入库上架================================


# def settle():  # 结算相关
#     # # 登录获取用户id等信息，使用创建的用户登录===========开始
#     info = FileUtils().r_info8('b2_herp3_bs', "用户名信息", 'message3')
#     # print(info)
#     username = info['username1']
#     password = commonFuc().get_business_data("b2_herp3_bs", "password")
#
#     print('username,password', username, password)
#     # # print(username, password,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
#     # # 获取token和projectCode
#     token, projectCode, uxid, corpId, info = login_system(username, password).get_token()
#     # 登录获取用户id等信息，使用创建的用户登录============结束
#     headers = commonFuc().get_business_data(module, "json_headers2",
#                                             commonFuc().get_business_data(module, "json_contentType"), token,
#                                             projectCode)
#     # ================生成结算单列表查询===================
#     url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "mcmsOutUnBalance_listVoPage_url")
#     print(url)
#     branch_id = FileUtils().r_info('b2_herp3_bs', '院区新增')["branch_id"]
#     hosId = branch_id[0:5]
#     request_body = commonFuc().get_business_data(module, "payload7", hosId, hosId)
#     result = commonFuc().http_post(url, request_body, headers)
#     print('result', result)
#     data = commonFuc().analysis_json('data', result)
#     data1 = commonFuc().analysis_json('data', data)
#     # 取结算单id
#     list_a = []
#     for i in data1:
#         id = commonFuc().analysis_json('id', i)
#         list_a.append(id)
#     print(list_a)
#     print(list_a[0], list_a[1], type(list_a[0]))
#     # ===================生成结算单列表查询======================
#     # ================== 生成结算单==============================
#     url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
#                                                                              "mcmsOutUnBalance_genBalanceBill_url")
#     print(url)
#     request_body = commonFuc().get_business_data(module, "payload8", hosId, list_a[0], list_a[1], hosId)
#     print('request_body', request_body)
#     result = commonFuc().http_post(url, request_body, headers)
#     print('result', result)
#     # ================== 生成结算单==============================


def main():
    try:
        # 验收
        check_accept_order(1)  # 低值
        check_accept_order(2)  # 高值
        check_accept_order(3)  # 试剂
        # 入库上架
        putaway()
        putaway()
        putaway()
        OBD_ID = settle()# 生成结算单
        # 调用审批结算单
        approval_center(OBD_ID)
    except Exception as e:
        print('脚本出现异常，请检查脚本或者数据')
        print("发生异常：", str(e))
        traceback.print_exc()
    else:
        commonFuc().check_text_exist_result_text('succees', 'succees')
# main()