import os
from ruamel import yaml

from common.db.db import dbOP
import datetime
curpath = os.path.dirname(os.path.realpath(__file__))


# 数据读入和写入文件
class Rw:
    def w_token(self, enc_user_id='u779700044448', env='on'):
        result = dbOP().selectSql('select_user_token', [enc_user_id], "meitun_db")
        token = result[0][0]
        dict = {}
        token_value = {}
        token_value["time"] = datetime.datetime.now()
        token_value["token"] = token
        token_value["enc_user_id"] = enc_user_id
        key = enc_user_id + "_" + env
        dict[key] = token_value
        yamlpath = os.path.join(curpath, "data")
        # 写入到yaml文件
        with open(yamlpath, "w", encoding="utf-8") as f:
            yaml.dump(dict, f, Dumper=yaml.RoundTripDumper)
        return token

    def w_info(self, info):
        dict = {}
        value = {}
        value["loginusername"] = info[0]
        value["goodsname"] = info[1]
        key="loginusername1"
        dict[key] = value
        yamlpath = os.path.join(curpath, "data")
        # 写入到yaml文件
        with open(yamlpath, "w", encoding="utf-8") as f:
            yaml.dump(dict, f, Dumper=yaml.RoundTripDumper,allow_unicode=True)

    def r_token(self, enc_user_id='u779700044448', env='on'):
        yamlpath = os.path.join(curpath, "data")
        file_value = open(yamlpath, 'r')
        result = yaml.load(file_value.read(), Loader=yaml.Loader)
        if result is not None:
            key = enc_user_id + "_" + env
            if key in result:
                return result[key]
            else:
                return None
        else:
            return None




    def r_temp_file(self, key):
        """
        读临时文件
        :return:
        """
        yamlPath = os.path.join(curpath, "temp.yaml")
        file_value = open(yamlPath, 'r')
        result = yaml.load(file_value.read(), Loader=yaml.Loader)
        return result[key]


    def w_temp_file(self, dict):
        """
        写临时文件,没有会自动生成
        :param content:
        :return:
        """
        yamlpath = os.path.join(curpath, "temp.yaml")
        # 写入到yaml文件
        with open(yamlpath, "w", encoding="utf-8") as f:
            yaml.dump(dict, f, Dumper=yaml.RoundTripDumper)
















