import time
from model.DateUtils import DateUtils
from model.ComUtils import md5
import requests
from app.api_data.platform_order.order_util import save_order

ut = DateUtils()


def get_youshuge_order_task(st, et, account):
    et = ut.add_days(et, 1)
    url = 'https://novel.youshuge.com/v2/open/orders'
    host_name = account[0]
    channel_id = int(account[1])
    secert_key = account[2]
    channel = account[3]
    stage = account[4]
    page = 1

    li = []
    while True:

        timestamp = int(time.time())
        sign = md5('channel_id=' + str(channel_id) + '&end_date=' + et + '&host_name=' + host_name + '&page='
                   + str(page) + '&start_date=' + st + '&time=' + str(
            timestamp) + '&key=' + secert_key).upper()
        params = {
            'sign': sign,
            'host_name': host_name,
            'time': timestamp,
            'channel_id': channel_id,
            'page': page,
            'start_date': st,
            'end_date': et
        }
        r = requests.post(url, params).json()
        # print(r)

        order_item_list = r['data']
        if len(order_item_list) == 0:
            break

        for i in order_item_list:
            li.append((i["create_time"][:10],
                       stage,
                       '悠书阁',
                       channel,
                       channel_id,
                       i['openid'],
                       i["create_time"],
                       i['reg_time'],
                       int(i['price']) / 100,
                       i['book_name'],
                       i['order_num'],
                       2 if i['pay_status'] == '1' else 1
                       ))

        page += 1

    if len(li) > 0:
        print(f"{channel} 有订单{len(li)}")
        save_order(li)


if __name__ == '__main__':
    a = "趣程15期,10696,8OC7SNCL46ZEI7JBACXFDM8CP5JM1FSL,盛德文苑,趣程15期"
    a = '趣程清勇6,10675,B6FK1HFW1V9ZPD6WX0FGBX3WP73E6M5V,璃月文楼,清勇7月'
    get_youshuge_order_task('2021-01-06', '2021-08-06', a.split(','))