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

from air_case.b1_herp3_login.登录内网系统.登录内网系统 import login_system
from air_case.public1.public1.public1 import *
from common.db.sql.sql_del_branch_info import delData
from common.db.sql.sql_tools import process_tuple, get_id

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_b3流程十请领业务流_二级库向边仓,id2302,id2302-13,sit,on
核心业务流:a_b3流程十请领业务流_二级库向边仓
python runner_test.py tag id2302-13 debug mdm3
"""


def SERACH_goods_id(GoodsId):
    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等信息，使用创建的用户登录============结束\
    # 获取请求头信息
    headers = commonFuc().get_business_data(module, "json_headers2",
                                            commonFuc().get_business_data(module, "json_contentType"), token,
                                            commonFuc().get_business_data(module, "X-APP-CODE"))
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "herpService_mcmsBranchGoodsInfo_page_url")
    dept1 = FileUtils().r_info8("b2_herp3_bs", "所有科室id", 'message6')['deptid1']
    # hosGoodsId = FileUtils().r_info8("b5_spd3_core_business_flow", "产品审核信息", 'message2')['hosGoodsId']
    # GoodsId = hosGoodsId.replace(get_hosid(), '')
    request_body = commonFuc().get_business_data(module, "payload53", GoodsId, get_hosid(), get_branch_id(), dept1)
    result = commonFuc().http_post(url, request_body, headers)
    branchGoodsId = commonFuc().analysis_json('id', commonFuc().analysis_json('data', commonFuc().analysis_json('data',
                                                                                                                result)))
    return branchGoodsId


def goods_move():
    # # 登录获取用户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等信息，使用创建的用户登录============结束
    module = "b2_herp3_bs"
    # g0_请领出库渠道设置_转移产品到边仓
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "updateSettleType_url")

    # 获取请求头信息
    headers = commonFuc().get_business_data(module, "json_headers2",
                                            commonFuc().get_business_data(module, "json_contentType"), token,
                                            commonFuc().get_business_data(module, "X-APP-CODE"))
    for i in range(1, 4):
        info = FileUtils().r_info8('b5_spd3_core_business_flow', "产品审核信息", 'message%s' % i)
        hosGoodsId = info['hosGoodsId']
        GoodsId = hosGoodsId.replace(get_hosid(), '')
        branchGoodsId = SERACH_goods_id(GoodsId)
        # #请求体
        request_body = commonFuc().get_business_data(module, "payload47", branchGoodsId, hosGoodsId, get_branch_id())
        print(request_body)
        # # # 发送请求
        result = commonFuc().http_post(url, request_body, headers)
        print('goods_move,result', result)


def second_dept_Request(hosGoodsId, type):
    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等信息，使用创建的用户登录============结束
    # 我要请领_手工请领_列表查询===========================
    headers = commonFuc().get_business_data(module, "json_headers2",
                                            commonFuc().get_business_data(module, "json_contentType"), token,
                                            commonFuc().get_business_data(module, "X-APP-CODE"))

    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "herpService_buy_queryGoodsInfoPage_url")
    print('我要请领_手工请领_列表查询=================', url)
    deptid2 = FileUtils().r_info8("b2_herp3_bs", "所有科室id", 'message6')['deptid2']
    deptname2 = FileUtils().r_info8("b2_herp3_bs", "所有科室name", 'message6')['deptid2']
    # 高值
    # hosGoodsId = FileUtils().r_info8("b5_spd3_core_business_flow", "产品审核信息", 'message1')['hosGoodsId']
    GoodsId = hosGoodsId.replace(get_hosid(), '')
    # areaCode = get_stockAreaId_new(deptid2, deptname2, 2)
    areaCode =process_tuple(get_id("select shelf_code from mcms_stock_shelf where address='二级检验科002'and shelf_name='默认库区'order by create_time desc LIMIT 1;"))

    request_body = commonFuc().get_business_data(module, "payload39", GoodsId, get_hosid(), deptid2, areaCode)
    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))
    goodsName = commonFuc().analysis_json('goodsName', data1)
    goodsSpec = commonFuc().analysis_json('goodsSpec', data1)
    mdmGoodsCode = commonFuc().analysis_json('mdmGoodsCode', data1)
    goodsCode = commonFuc().analysis_json('goodsCode', data1)
    unit = commonFuc().analysis_json('unit', data1)
    purMode = commonFuc().analysis_json('purMode', data1)
    goodsMfrsName = commonFuc().analysis_json('goodsMfrsName', data1)
    unitName = commonFuc().analysis_json('unitName', data1)
    price = commonFuc().analysis_json('price', data1)
    deptId = commonFuc().analysis_json('deptId', data1)
    # areaCode=commonFuc().analysis_json('areaCode',data1)
    areaName = '默认库区'
    targetDeptId = commonFuc().analysis_json('targetDeptId', data1)
    targetDeptName = commonFuc().analysis_json('targetDeptName', data1)
    targetStockId = commonFuc().analysis_json('targetStockId', data1)
    targetStockName = commonFuc().analysis_json('targetStockName', data1)
    purModeText = commonFuc().analysis_json('purModeText', data1)
    goodsGeneralName = commonFuc().analysis_json('goodsGeneralName', data1)
    provName = commonFuc().analysis_json('provName', data1)
    pkgDefId = commonFuc().analysis_json('pkgDefId', data1)
    pkgDefName= commonFuc().analysis_json('pkgDefName', data1)
    # 信息写入文件
    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, module, '二级库请领产品信息', titlename, 'message21')
    # 我要请领_手工请领_列表查询===========================
    # 添加到请领车=============================================
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "herpService_buy_createBuyCar_url")
    print('添加到请领车=================', url)
    if type == 1:
        request_body = commonFuc().get_business_data(module, "payload40", hosGoodsId, purMode, goodsName, goodsSpec,
                                                     mdmGoodsCode,
                                                     goodsCode, unit, goodsMfrsName, pkgDefName, pkgDefId, unitName,
                                                     price,
                                                     deptId,
                                                     areaCode, areaName, targetDeptId, targetDeptName, targetStockId,
                                                     targetStockName, purModeText, goodsGeneralName, provName)
    elif type == 2:
        request_body = commonFuc().get_business_data(module, "payload41", hosGoodsId, purMode, goodsName, goodsSpec,
                                                     mdmGoodsCode,
                                                     goodsCode, unit, goodsMfrsName, unitName, price, deptId,
                                                     areaCode, areaName, targetDeptId, targetDeptName, targetStockId,
                                                     targetStockName, purModeText, goodsGeneralName, provName)
    elif type == 3:
        request_body = commonFuc().get_business_data(module, "payload42", hosGoodsId, purMode, goodsName, goodsSpec,
                                                     mdmGoodsCode,
                                                     goodsCode, unit, goodsMfrsName, pkgDefName, pkgDefId, unitName,
                                                     price,
                                                     deptId,
                                                     areaCode, areaName, targetDeptId, targetDeptName, targetStockId,
                                                     targetStockName, purModeText, goodsGeneralName, provName)
    request_body = get_process_list(request_body)
    print('添加到请领车', 'request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('添加到请领车,result', result)
    # 添加到请领车=============================================


def BuyCarSubmit():
    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等信息，使用创建的用户登录============结束
    # 我要请领_手工请领_列表查询===========================
    headers = commonFuc().get_business_data(module, "json_headers2",
                                            commonFuc().get_business_data(module, "json_contentType"), token,
                                            commonFuc().get_business_data(module, "X-APP-CODE"))
    # 请领车查询===============================================
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "herpService_buy_queryBuyCarPage_url")
    print('请领车查询=================', url)
    deptid2 = FileUtils().r_info8("b2_herp3_bs", "所有科室id", 'message6')['deptid2']
    deptname2 = FileUtils().r_info8("b2_herp3_bs", "所有科室name", 'message6')['deptid2']
    # areaCode = get_stockAreaId_new(deptid2, deptname2, 2)
    areaCode = get_stockAreaId_new_fromDb(deptname2, 2)
    request_body = commonFuc().get_business_data(module, "payload43", areaCode, get_hosid(), deptid2)

    print('请领车查询', 'request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('请领车查询,result', result)
    data = commonFuc().analysis_json('data', result)
    list_id = []
    for i in data:
        id = commonFuc().analysis_json('id', i)
        list_id.append(id)
    # 请领车查询===============================================
    # 请领车提交===============================================
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "herpService_buy_validBuyCarSubmit_url")
    print('请领车提交=================', url)

    billExpdtDate = timeUtils().get_time_add(30, 2)
    print('billExpdtDate', billExpdtDate)
    request_body = commonFuc().get_business_data(module, "payload44", billExpdtDate, get_branch_id(), list_id[0],
                                                 list_id[1], list_id[2])

    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,
                                                                             "herpService_buy_createBuyBill_url")
    print('创建请领车交易=================', url)

    billExpdtDate = timeUtils().get_time_add(30, 2)
    request_body = commonFuc().get_business_data(module, "payload44", billExpdtDate, get_branch_id(), list_id[0],
                                                 list_id[1], list_id[2])

    print('创建请领车交易', 'request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('创建领车交易,result', result)
    currentTaskList = commonFuc().analysis_json('currentTaskList', commonFuc().analysis_json('data', result))


def add_logic_stock():
    delData().Delete_yb_logic_stock()
    module = "b5_spd3_core_business_flow"
    # 登录集中管控平台
    token, projectCode, uxid, corpId, info = login_platform()
    headers = commonFuc().get_business_data(module, "json_headers2",
                                            commonFuc().get_business_data(module, "json_contentType"), token,
                                            commonFuc().get_business_data(module, "X-APP-CODE"))
    # #添加云仓===============================================
    url = commonFuc().get_api_url() + commonFuc().get_business_data(module,
                                                                    "platformService_basic_logic_save_url")
    print('添加云仓=================', url)

    request_body = commonFuc().get_business_data(module, "payload54", get_hosid(), get_branch_id(), get_branch_id(),
                                                 uxid, uxid, get_in_userid(), get_hosid(), uxid, uxid)

    print('添加云仓', 'request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('添加云仓,result', result)


def cloud_stock_opeartion():
    print('云仓处理')
    # 云仓登录
    token, projectCode, uxid, corpId, info =login_logic_stock()
    module = "b5_spd3_core_business_flow"
    headers = commonFuc().get_business_data(module, "json_headers2",
                                            commonFuc().get_business_data(module, "json_contentType"), token,
                                            commonFuc().get_business_data(module, "X-APP-CODE"))
    # #云仓处理查看单据===============================================
    url = commonFuc().get_api_url() + commonFuc().get_business_data(module,
                                                                    "platformService_basic_logic_save_url")
    print('云仓处理查看单据=================', url)

    request_body = commonFuc().get_business_data(module, "payload54x", get_hosid(), get_branch_id(), get_branch_id(),
                                                 uxid, uxid, get_in_userid(), get_hosid(), uxid, uxid)

    print('云仓处理查看单据', 'request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('云仓处理查看单据,result', result)

def check_buyWayText():
    updateUserLoginDefaultRange(get_listUserMgrRangePage(2))  # 设置登录账号默认权限是二级库
    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等信息，使用创建的用户登录============结束
    # 我要请领_手工请领_列表查询===========================
    headers = commonFuc().get_business_data(module, "json_headers2",
                                            commonFuc().get_business_data(module, "json_contentType"), token,
                                            commonFuc().get_business_data(module, "X-APP-CODE"))
    # 请领单列表查询===============================================
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module,
                                                                             "herpService_queryBuyPage_url")
    print('请领单列表查询=================', url)
    request_body = commonFuc().get_business_data(module, "payload55",  get_branch_id())

    print('请领单列表查询', 'request_body', request_body)
    result = commonFuc().http_post(url, request_body, headers)
    print('请领单列表查询,result', result)
    data=commonFuc().analysis_json('data',result)
    data1=commonFuc().analysis_json('data',data)
    j=0
    for i in data1:
        buyWayText=commonFuc().analysis_json('buyWayText',i)
        if buyWayText=='边仓':
            j=j+1
    if j>=3:
        commonFuc().check_text_exist_result_text('succees', 'succees')
    else:
        commonFuc().check_text_exist_result_text('error', 'succees')



def main():
    try:
        set_dept_lead()  # 设置二级科室负责人
        # 科室必须同步到外网，集中管控平台创建边仓才能选择到用户,"deptType":"0"
        add_logic_stock()

        # 设置产品出库渠道为边仓
        goods_move()
        updateUserLoginDefaultRange(get_listUserMgrRangePage(2))  # 设置登录账号默认权限是二级库

        # # # 低值
        second_dept_Request(FileUtils().r_info8("b5_spd3_core_business_flow", "产品审核信息", 'message2')['hosGoodsId'], 1)
        # # 高值
        second_dept_Request(FileUtils().r_info8("b5_spd3_core_business_flow", "产品审核信息", 'message1')['hosGoodsId'], 2)
        # # 试剂
        second_dept_Request(FileUtils().r_info8("b5_spd3_core_business_flow", "产品审核信息", 'message3')['hosGoodsId'], 3)
        BuyCarSubmit()  # 请领车提交
        for i in range(6):  # 三个单据共审批6次
            approval_center()
        check_buyWayText()#验证出库渠道是否为边仓
        commonFuc().check_text_exist_result_text('succees', 'succees')
        print('==========================流程十结束==============================')
    except:
        commonFuc().check_text_exist_result_text('error', 'succees')

# main()