import json
import math


class PositionJsonOperator:
"""
操作 json文件 的 类
ps: 使用时, 需要导入 json、math库
"""


"""
------------------ public part ------------------
"""
@classmethod
def tqz_load_jsonfile(cls, filename=None):
if filename is None:
exception = Exception("Error: filename is None")
raise exception
else:
return cls._writeReadFile_except_operation(filename=filename, operationType="r")

@classmethod
def tqz_write_jsonfile(cls, content=None, filename=None):
if filename is None:
exception = Exception("Error: filename is None")
raise exception
else:
cls._writeReadFile_except_operation(filename=filename, content=content, operationType="w")

@classmethod
def tqz_sum_position_all_jsonfile(cls, *jsonfile_list, target_jsonfile):
"""
加总多个 json文件的 持仓, 并写入新的目json标文件中
:param jsonfile_list: 字符串数组
:param target_jsonfile: 要存入的 json文件名
"""
jsonfile_content_list = []
[jsonfile_content_list.append(cls.tqz_load_jsonfile(jsonfile)) for jsonfile in jsonfile_list]

content_dic = cls._sum_position_all_keyValueNotFound_except_operation(dic_list=jsonfile_content_list)

cls.tqz_write_jsonfile(content=content_dic, filename=target_jsonfile)

@classmethod
def tqz_multi_position_all(cls, *jsonfile_list, multi):
"""
按倍数调整 多个json文件的 持仓
:param jsonfile_list: 需要调整持仓的 json文件数组
:param multi: 倍数
"""
[cls._multi_position(source_jsonfile=jsonfile, multi=multi) for jsonfile in jsonfile_list]

@classmethod
def tqz_empty_position_all(cls, *jsonfile_list):
"""
清空 多个json文件的 持仓
:param jsonfile_list: 需要清空的 json文件数组
"""
cls.tqz_multi_position_all(*jsonfile_list, multi=0)


"""
------------------ private part ------------------
"""
@staticmethod
def _get_newData_with_sumPosition(first_dic=None, second_dic=None):
new_dic = {}
for key, value in first_dic.items():
value['pos'] = first_dic[key]['pos'] + second_dic[key]['pos']
new_dic[key] = value
return new_dic

@classmethod
def _sum_position(cls, source_filename1, source_filename2, target_filename):
# 读取json文件数据
cta_hla_dic = cls.tqz_load_jsonfile(filename=source_filename1)
cta_hsr_dic = cls.tqz_load_jsonfile(filename=source_filename2)

# 获取新的要写入json文件的数据
new_dic = cls._get_newData_with_sumPosition(cta_hla_dic, cta_hsr_dic)

# 写入目标文件夹
cls.tqz_write_jsonfile(content=new_dic, filename=target_filename)

@classmethod
def _multi_position(cls, source_jsonfile, multi):
source_content = cls.tqz_load_jsonfile(filename=source_jsonfile)

source_content = cls._multi_position_keyValueNotFount_except_operation(source_content=source_content, multi=multi)

cls.tqz_write_jsonfile(content=source_content, filename=source_jsonfile)

@classmethod
def _empty_position(cls, source_jsonfile):
cls._multi_position(source_jsonfile=source_jsonfile, multi=0)


"""
------------------ except operation part ------------------
"""
@classmethod
def _writeReadFile_except_operation(cls, filename=None, content=None, operationType="r"):
try:
if "r" == operationType:
with open(filename, operationType, encoding="utf-8") as fp:
return json.load(fp=fp)
elif "w" == operationType:
with open(filename, operationType, encoding="utf-8") as fp:
json.dump(content, fp=fp, ensure_ascii=False, indent=4) # 参数indent: json文件按格式写入, 距行首空4格;
except FileNotFoundError: # filename文件 没找到
print("Error: file %s is not fount" % filename)
except Exception as result:
print("unkown Error: %s" % result)

@classmethod
def _sum_position_all_keyValueNotFound_except_operation(cls, dic_list=[], new_dic={}):
try:
for dic in dic_list:
for key, value in dic.items():
if key not in new_dic:
new_dic[key] = dic[key]
else:
value['pos'] = value['pos'] + new_dic[key]['pos']
new_dic[key] = value
except AttributeError as result:
print("Error: %s" % result)
except Exception as result:
print("unknow Error: %s" % result)
else:
return new_dic

@classmethod
def _multi_position_keyValueNotFount_except_operation(cls, source_content=None, multi=1):
try:
for key, value in source_content.items():
if value['pos'] > 0:
value['pos'] = math.floor(value['pos'] * multi)
else:
value['pos'] = math.floor(-1 * value['pos'] * multi) * -1
source_content[key] = value
except AttributeError as result:
print("Error: %s" % result)
except Exception as result:
print("unknow Error: %s" % result)
else:
return source_content


def _main_engine():
list = []
list.append("symbol_2.json")
list.append("symbol_3.json")
list.append("symbol_4.json")
list.append("symbol_5.json")

target_jsonfile = "test.json"

PositionJsonOperator.tqz_sum_position_all_jsonfile(*list, target_jsonfile=target_jsonfile)

# PositionJsonOperator.tqz_multi_position_all(target_jsonfile, multi=0.5)
# PositionJsonOperator.tqz_empty_position_all(target_jsonfile)


if __name__ == '__main__':
_main_engine()