import pymysql
import numpy as np
from datetime import datetime
from binascii import b2a_hex
import time

db_config = {
    'host': 'cdb-noc7c8is.bj.tencentcdb.com',
    'user': 'root',
    'password': 'Ubuntu123$',
    'database': 'gateway',
    "port": 10152,
    "charset": "utf8"}
db_con = pymysql.connect(**db_config)

COMMAND_TABLE = "ld_billing_pay_command"
ORDER_TABLE = "ld_billing_pay"
BALANCE_TABLE = "ld_device_prepaid_month"

BUILDING_ID = "PowerKeeper"
GATEWAY_ID = "DigitalCenter"
METER_ID = "01002"
RECHARGE_AMOUNT = 1


def create_bill(t, serial_number, recharge_amount):
    id_ = "cc" + t
    device_code = "cc" + t
    pay_method = "cc"
    type_ = 0
    corp_name = "cc"
    create_by = "cc"
    create_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    update_by = "cc"
    update_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    sql = """
    INSERT INTO %s (`id`, `serial_number`, `device_code`, `recharge_amount`, `pay_method`, `type`, `corp_name`, `create_by`, 
    `create_date`, `update_by`, `update_date`) VALUES ("%s", "%s", "%s", %s, "%s", "%s", "%s", "%s", "%s", "%s", "%s")
    """ % (ORDER_TABLE, id_, serial_number, device_code, recharge_amount, pay_method, type_, corp_name, create_by, create_date,
           update_by, update_date)
    with db_con.cursor() as cursor:
        cursor.execute(sql)
        db_con.commit()


def create_command(t, serial_number, recharge_amount, building_id, gateway_id, meter_id):
    id_ = t[0:14]
    recharge_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    create_by = "cc"
    create_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    update_by = "cc"
    update_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    sql = """
    INSERT INTO %s (`id`, `building_id`, `gateway_id`, `meter_id`, `serial_number`, `recharge_amount`, `recharge_date`, `create_by`, 
    `create_date`, `update_by`, `update_date`) VALUES (%s, "%s", "%s", "%s", "%s", %s, "%s", "%s", "%s", "%s", "%s")
    """ % (COMMAND_TABLE, id_, building_id, gateway_id, meter_id, serial_number, recharge_amount, recharge_date, create_by, create_date,
           update_by, update_date)
    with db_con.cursor() as cursor:
        cursor.execute(sql)
        db_con.commit()


def create_recharge_order():
    t = datetime.now().strftime("%Y%m%d%H%M%S%f")
    serial_number = "cc" + t
    recharge_amount = RECHARGE_AMOUNT

    building_id = BUILDING_ID
    gateway_id = GATEWAY_ID
    meter_id = METER_ID

    print("created order:", building_id, gateway_id, meter_id, recharge_amount)

    create_bill(t, serial_number, recharge_amount)
    create_command(t, serial_number, recharge_amount, building_id, gateway_id, meter_id)


if __name__ == '__main__':
    for i in range(1):
        print(i)
        create_recharge_order()
        time.sleep(1)

