# -*- encoding=utf8 -*-
from air_case.public1.public1.public1 import *
from common.dateUtils import dateUtils
from common.db.sql.sql_del_branch_info import delData
from common.fileUtls import FileUtils
from common.run_cmd_script import execute_command

__author__ = "xiaohesheng"

"""
case_tag:api,spd_core,a_a4_流程四_基础模块设置,id2302,id2302-4,sit,on
主数据平台:a_a4_流程四_基础模块设置
python runner_test.py tag id2302-4 debug mdm3

"""

from common.common_func import commonFuc
from air_case.b1_herp3_login.登录内网系统.登录内网系统 import login_system
from airtest.core.api import using
import sys
import time

module = "b5_spd3_core_business_flow"

def add_dept():
    # 内网登录
    username = commonFuc().get_business_data(module, "username")
    # print('医院名称',username)
    password = commonFuc().get_business_data(module, "password")
    # print(username, password,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    # 获取token和projectCode
    token, projectCode, uxid, corpId, info = login_system(username, password).get_token()
    # print( token,projectCode,uxid,corpId,info)
    # c0_新增科室_特殊科室_设备科_中心库房
    branch_id = FileUtils().r_info8(module, '院区新增type2','message')["院区id"]
    url = commonFuc().get_api_url() + commonFuc().get_business_data(module, "dept_insert_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"))

    # #请求体
    request_body = commonFuc().get_business_data(module, "payload14", branch_id)
    print(request_body)
    # # # 发送请求
    result = commonFuc().http_post(url, request_body, headers)
    print('result', result)
    # #断言
    checkDict = commonFuc().get_business_data(module, 'checkDict2')
    commonFuc().check_result(checkDict, result)
def test1(type=1):

    if type==1:
        # 院区新增
        execute_command("python runner_test.py tag id2263-4 debug sit")
        # 新增科室
        execute_command(
            "python runner_test.py tag id2263-19,id2263-20,id2263-21,id2263-22,id2263-23,id2263-24,id2263-25,id2263-26 debug sit")
    else:
        branch_add()
        # 新增科室
        execute_command(
            "python runner_test.py tag id2263-19,id2263-20,id2263-21,id2263-22,id2263-23,id2263-24,id2263-25,id2263-26 debug sit")
    # 一键导入所有产品
    execute_command("python runner_test.py tag id2263-48 debug sit")
    #导入同步过来的新产品，防止因同步时间差导致新建的产品没有导入过来
    for i in range(1, 6):
        info = FileUtils().r_info8('b5_spd3_core_business_flow', "产品审核信息", 'message%s' % i)
        hosGoodsId = info['hosGoodsId']
        import_goods(hosGoodsId)

    # r_b8库房管理_库区设置_同步库房信息
    execute_command("python runner_test.py tag id2263-221 debug sit")
    # 新增用户
    execute_command("python runner_test.py tag id2263-253 debug sit")
    # 根据院区名称查询中心库房id
    execute_command("python runner_test.py tag id2263-222 debug sit")
    # 新增库区
    execute_command("python runner_test.py tag id2263-226 debug sit")
    # 查询库区
    execute_command("python runner_test.py tag id2263-228 debug sit")

    # r_d0库房管理_库区设置_人员管理_添加人员_查询人员
    execute_command("python runner_test.py tag id2263-233 debug sit")
    # r_d2库房管理_库区设置_人员管理_添加人员
    execute_command("python runner_test.py tag id2263-235 debug sit")
    # r_d4库房管理_库区设置_货位管理_添加货位
    execute_command("python runner_test.py tag id2263-237 debug sit")
    # 科室管理-科室人员查询 设置科室负责人
    execute_command("python runner_test.py tag id2263-219 debug sit")

def  import_goods(hosGoodsId):
    module = "b2_herp3_bs"
    # 内网登录
    username = commonFuc().get_business_data(module, "username")
    # print('医院名称',username)
    password = commonFuc().get_business_data(module, "password")
    # print(username, password,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    # 获取token和projectCode
    token, projectCode, uxid, corpId, info = login_system(username, password).get_token()
    # 院区产品设置_查询院区产品
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "mcmsDeptGoodsInfo_url")
    print('院区产品设置_查询院区产品',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"))
    # 获取院区id
    branch_id = FileUtils().r_info(module, '院区新增')["branch_id"]
    # hosGoodsId = FileUtils().r_info8('b5_spd3_core_business_flow', '产品审核信息', 'message2')["hosGoodsId"]
    goodsId=hosGoodsId.replace(get_hosid(), "")
    # #请求体
    request_body = commonFuc().get_business_data(module, "payload32_1",get_hosid(), goodsId,branch_id)
    print('import_goods',request_body)
    # # # 发送请求
    result='result'
    # j=1
    while True:
        # if j==600:
        #     print('600秒过去了，导入产品需要停止')
        #     break
        result = commonFuc().http_post(url, request_body, headers)
        total=commonFuc().analysis_json('total',commonFuc().analysis_json('data',result))
        print('import_goods', total)
        if total==0:
            print('产品暂时没有同步到内网,等待6秒')
            # j=j+6
            time.sleep(6)
            # 再次调用一键导入产品
            execute_command("python runner_test.py tag id2263-48 debug sit")
        else:
            break
    print('result', result)


def test2():  # 科室添加产品信息(产品是从外网同步过来的)
    module = "b2_herp3_bs"
    # 内网登录
    username = commonFuc().get_business_data(module, "username")
    # print('医院名称',username)
    password = commonFuc().get_business_data(module, "password")
    # print(username, password,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    # 获取token和projectCode
    token, projectCode, uxid, corpId, info = login_system(username, password).get_token()

    #
    url = commonFuc().get_api_add_port_url()+commonFuc().get_business_data(module, "basic_mcmsGoodsInfo_insert")
    print('basic_mcmsGoodsInfo_insert',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"))
    list2 = []
    i = 1
    while True:
        if i == 1000:
            print('6000秒过去了，产品还没过来，检查同步是否正常')
            break
        try:
            for i in range(1, 6):
                info = FileUtils().r_info8('b5_spd3_core_business_flow', "产品审核信息", 'message%s' % i)
                hosGoodsId = info['hosGoodsId']
                list2.append(hosGoodsId)
        except:
            print('产品没有同步过来，等待6秒')
            time.sleep(6)
            i = i + 1
            continue
        else:
            break

    dept2_id = FileUtils().r_info(module, '科室信息')["dept2_id"]
    j=1
    for i in list2:
        # 请求体
        if j==1:
            request_body = commonFuc().get_business_data(module, "payload58_6_3", dept2_id, i,20)
        elif j==2:
            request_body = commonFuc().get_business_data(module, "payload58_6_3", dept2_id, i, 10)
        elif j==3:
            request_body = commonFuc().get_business_data(module, "payload58_6_3", dept2_id, i, 60)
        else:
            request_body = commonFuc().get_business_data(module, "payload58_6_3", dept2_id, i,20)
        j=j+1
        request_body = '[' + str(request_body) + ']'
        new_request_body = request_body.replace("'", '"')
        print(new_request_body)
        import json
        request_body_json = json.loads(new_request_body)
        # # # 发送请求
        result = commonFuc().http_post(url, request_body_json, headers)
        print('resultaaaaaaaaaaaaaaaaaaaaaaaaaaa', result)
        # 断言
        # checkDict=commonFuc().get_business_data(module,'checkDict10')
        # commonFuc().check_result(checkDict,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)



def grants_user(orgName='d69a68df361a4289b2262e4ef75b55a5', mgrRangeId='feb0cc16618c437fb4d033cd339a0377'):
    module = "b2_herp3_bs"
    # 登录获取用户id等信息，使用创建的用户登录===========开始
    info = FileUtils().r_info8(module, "用户名信息", 'message3')
    print(info)
    username1 = info['username1']

    username = username1
    ## print('医院名称',username)
    password = commonFuc().get_business_data(module, "password")
    # print(username, password,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    # 获取token和projectCode
    token1, projectCode1, uxid1, corpId1, info1 = login_system(username, password).get_token()
    # 登录获取用户id等信息，使用创建的用户登录============结束
    # 内网登录
    username = commonFuc().get_business_data(module, "username")
    ## print('医院名称',username)
    password = commonFuc().get_business_data(module, "password")
    # print(username, password,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    # 获取token和projectCode
    token, projectCode, uxid, corpId, info = login_system(username, password).get_token()
    # print( token,projectCode,uxid,corpId,info)

    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "sys_user_grants_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"))
    userId = uxid1
    mgrBranchId = FileUtils().r_info(module, '院区新增')["branch_id"]
    mgrBranchName = FileUtils().r_info(module, '院区新增')["branch_name"]
    deptid1 = FileUtils().r_info8(module, '所有科室id','message6')["deptid1"]
    deptid2 = FileUtils().r_info8(module, '所有科室id','message6')["deptid2"]
    deptid3 = FileUtils().r_info8(module, '所有科室id','message6')["deptid3"]
    deptid4 = FileUtils().r_info8(module, '所有科室id','message6')["deptid4"]

    # # 请求体
    request_body = commonFuc().get_business_data(module, "payload63_12_2", userId, mgrBranchId, mgrBranchName, deptid1,
                                                 mgrBranchId, mgrBranchName, deptid2, mgrBranchId, mgrBranchName,
                                                 deptid3, mgrBranchId, mgrBranchName, deptid4
                                                 )
    print('request_body', request_body)
    # # # # 发送请求
    result = commonFuc().http_post(url, request_body, headers)
    print('resultaaaaaaaaaaaaaaaaaaa', result)
    # 断言
    code = commonFuc().analysis_json('code', result)
    data = commonFuc().analysis_json('data', result)
    if code == 0 and data == 4:
        commonFuc().check_text_exist(0, result)
    else:
        commonFuc().check_text_exist('error', result)

def add_StockArea():#添加货位
    module='b2_herp3_bs'
    # 登录获取用户id等信息，使用创建的用户登录===========开始
    info = FileUtils().r_info8(module, "用户名信息", 'message3')
    print(info)
    username1 = info['username1']

    username = username1
    ## print('医院名称',username)
    password = commonFuc().get_business_data(module, "password")
    # print(username, password,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    # 获取token和projectCode
    token, projectCode, uxid, corpId, info = login_system(username, password).get_token()
    # 登录获取用户id等信息，使用创建的用户登录============结束

    # 获取库区id
    deptid1 = FileUtils().r_info8(module, '所有科室id','message6')["deptid1"]
    branch_name = FileUtils().r_info(module, '院区新增')["branch_name"]
    stockId = get_stockId(branch_name + '中心库房')


    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "basic_stockShelf_page_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"))
    request_body = commonFuc().get_business_data(module, "payload62_6", deptid1, stockId)
    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)
    id1 = commonFuc().analysis_json('id', data1)
    shelfCode = commonFuc().analysis_json('shelfCode', data1)
    createTime = commonFuc().analysis_json('createTime', data1)
    stockId = commonFuc().analysis_json('stockId', data1)
    shelfName = commonFuc().analysis_json('shelfName', data1)
    address = commonFuc().analysis_json('address', data1)
    recPhone = commonFuc().analysis_json('recPhone', data1)
    lastModified = commonFuc().analysis_json('lastModified', data1)
    shelfNo = commonFuc().analysis_json('shelfNo', data1)
    print(id1, lastModified, shelfCode, createTime, stockId, shelfName, address, recPhone, shelfNo)
    print('resultaaaaaaaaaaaaaaaaaaaaaaaaaaa', result)

    # r_d4库房管理_库区设置_货位管理_添加货位
    url = commonFuc().get_api_add_port_url() + commonFuc().get_business_data(module, "basic_stockUser_insertShelf_url")
    print('添加货位url',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"))

    # # 请求体
    request_body = commonFuc().get_business_data(module, "payload62_12", id1, shelfCode, stockId, id1)

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

    code = commonFuc().analysis_json('code', result)
    data = commonFuc().analysis_json('data', result)

    # pageSize = commonFuc().analysis_json('pageSize', data)
    # print(pageSize, type(pageSize))

    if code == 0 and data == 4:
        commonFuc().check_text_exist(0, result)
    else:
        commonFuc().check_text_exist('error', result)

def recover_dataFile():
    delData().Delete_branch_by_id(2)
    pro_path = commonFuc().get_pro_path2()
    src = pro_path + r'/data'
    dst=FileUtils().r_info8('b5_spd3_core_business_flow', '备份路径','message29')['备份目录']
    # 恢复目录
    # 先删除文件夹
    import shutil, os
    if os.path.exists(src):
        shutil.rmtree(src)
    FileUtils().copy_folder_backup(dst, src)
def branch_add(token):
    module='b2_herp3_bs'
    # 内网登录
    username = commonFuc().get_business_data(module, "username")
    # print('医院名称',username)
    password = commonFuc().get_business_data(module, "password")
    # print(username, password,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    # 获取token和projectCode
    token, projectCode, uxid, corpId, info = login_system(username, password).get_token()
    url=commonFuc().get_api_add_port_url()+commonFuc().get_business_data(module, "insert_url")
    print('a4_院区新增',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"))
    name=commonFuc().randomString(6)#核心业务流的长度后缀设置为6位
    #请求体
    request_body=commonFuc().get_business_data(module, "payload",name,name)

    # 发送请求
    result = commonFuc().http_post(url, request_body,headers)
    print('result', result)
    #断言
    code=commonFuc().analysis_json('code',result)
    commonFuc().check_text_exist(0,result)
    id1=commonFuc().analysis_json('id',commonFuc().analysis_json('data',result))
    name=commonFuc().analysis_json('name',commonFuc().analysis_json('data',result))

    #备份当前data目录
    pro_path = commonFuc().get_pro_path2()
    src=pro_path+r'/data'
    dst=pro_path+r'/data'+ timeUtils().get_time_hms(5)
    #将备份的目录路径写入到文件中
    info = (src, dst)
    titlename = ('源目录', '备份目录')
    FileUtils().w_info8(info, 'b5_spd3_core_business_flow', '院区新增',titlename,'message29')
    #备份data文件
    FileUtils().copy_folder_backup(src,dst)

    info = (id1, name)
    titlename = ('院区id', '院区name')
    FileUtils().w_info2(info,module,'院区新增')

def main():
    try:
        # ==============删除业务数据和报表数据
        # delData().Delete_business_Data()#删除业务数据
        # delData().Del_reporter_data() # 删除报表数据
        #==============删除业务数据和报表数据
        test1()#参数2是新增院区后缀为6位数的参数1是老模式
        test2()# 科室添加产品信息(产品是从外网同步过来的)
        dept_query_all()# 科室查询，将科室id写入文件中
        grants_user()#给用户授权
        set_dept_lead1() #设置一级科室负责人
        add_StockArea()#添加库区
        commonFuc().check_text_exist_result_text('succees', 'succees')
        print('=================流程四结束=================')
    except Exception as e:
        commonFuc().check_text_exist_result_text('succees','error')
        print("发生异常：", str(e))
# main()