import pandas as pd
import os
import numpy as np
import random

def to_dict(key,value):
    """
        key : 列名
        value : 二维数组 [[]]
    """
    _df = pd.DataFrame(columns=key,data=value).to_dict(orient='records')
    return _df


def get_product(args, repeat=1):
    """对两个list 进行排列组合"""
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    #     pools = args * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield list(prod)

def create_suiteFile(common,name,date):
    _file_tree =  """{'suite':{'%s':{'%s':['data','detail','report']}}}"""%(name,'-'.join(str(date).replace(':','-').split('.')))

    _file_tree = eval(_file_tree)
    _file_tree_detail = {'path':"",'name':[]}
    _file_path = common.get('suite')

    def get_items(file_path,tree,tree_detail):
        for k ,v in tree.items():
            if isinstance(k,str):
                file_path = os.path.join(file_path,k)
                if not os.path.isdir(file_path):
                    os.mkdir(file_path)
                tree_detail['path'] = os.path.join(tree_detail['path'],k)
            if isinstance(v,list):
                for ii in v:
                    tree_detail['name'].append(ii)
                    os.mkdir(os.path.join(file_path,ii))
            if isinstance(v,dict):
                get_items(file_path,tree[k],tree_detail)
                # yield file_structure[k],file_path
    get_items(_file_path,_file_tree,_file_tree_detail)

    return _file_path,_file_tree,_file_tree_detail

def get_path(common,name,fname):
    path = common.get(name)
    return os.path.join(path,fname)




def lst_Covering(lst,num,istrue=True):
    """"""
    index = 0
    while num>0:
        if istrue:
            lst[index] +=1
        else:
            # print(num,index,lst[index])
            lst[index] -=1
        index+=1
        num = num-1
        if index >= len(lst):
            index = 0
    return lst

def set_allocation_num(gdp,count):
    """分配"""
    res = []
    for i in gdp:
        res.append(round(count*i/100))
    _sum = sum(res)
    if _sum > count:
        _temp = _sum - count
        res = sorted(res,reverse = True)
        res = lst_Covering(res,_temp,False)
    elif _sum < count:
        _temp = count - _sum
        res = sorted(res)
        res = lst_Covering(res,_temp)
    return res

def get_array(name,gdp,type,value,dataType,dataRound):
    """"""
    lst = []
    for i,(g,t,v,dt,dr) in enumerate(zip(gdp,type,value,dataType,dataRound)):
        temp = [name[i]] * int(g)
        for _t,_temp in enumerate(temp):
            _r_choice = np.random.randint(0,2)
            if t=='区间':
                if dt:
                    if v:
                        _v = v.replace('-',',').split(',')
                        if dt == 1:
                            _data = np.random.randint(eval(_v[0]),eval(_v[1])+1)
                        elif dt == 2:
                            _data = round(np.random.uniform(eval(_v[0]),eval(_v[1])),dr)
                    elif dt == 3:
                        # _r = np.random.randint(0,2)
                        if _r_choice == 0:
                            _data = np.random.randint(-1000,1000000)
                        elif _r_choice == 1:
                            _data = round(np.random.uniform(-1000,1000000),6)
                    temp[_t] = _data
            elif t == '正数':
                temp[_t] = int(v)
            elif t == '异常空值':
                temp[_t] = eval(v)
            elif t == '字符串':
                # _r_choice = np.random.randint(0,2)
                if _r_choice == 0:
                    temp[_t] = '!@#$%^&*()><?'
                else:
                    last_names = ['赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '褚', '卫', '蒋', '沈', '韩', '杨', '朱', '秦', '尤', '许',
                                  '姚', '邵', '堪', '汪', '祁', '毛', '禹', '狄', '米', '贝', '明', '臧', '计', '伏', '成', '戴', '谈', '宋', '茅', '庞',
                                  '熊', '纪', '舒', '屈', '项', '祝', '董', '梁']
                    first_names = ['的', '一', '是', '了', '我', '不', '人', '在', '他', '有', '这', '个', '上', '们', '来', '到', '时', '大', '地', '为',
                                   '子', '中', '你', '说', '生', '国', '年', '着', '就', '那', '和', '要', '她', '出', '也', '得', '里', '后', '自', '以',
                                   '乾', '坤', '']
                    temp[_t] = random.choice(last_names) + random.choice(first_names)
        lst.extend(temp)
    random.shuffle(lst)
    return lst

def get_change(x):
    _dict = {
        "code": 200,
        "data": {"features": None}
    }
    _list = {}
    for key ,value in zip(x.keys(),x.values):
        _list = dict(_list, **{key:{'state':200,'value':value}})
    _dict['data']['features'] = _list
    return _dict