import json
import math
import operator
import os
import random
import string
import time
from functools import reduce

import requests
from PIL import Image


def year_to_minute():
    return time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))


def now_time():
    return int(time.time()*1000)


def year_to_day():
    return time.strftime('%Y-%m-%d', time.localtime(time.time()))


def file_abspath():
    return os.path.abspath(__file__).split('src')[0]


def screenshot_path():
    screenshot_file = file_abspath() + "/screenshots/" + year_to_day()
    if not os.path.exists(screenshot_file):
        os.mkdir(screenshot_file)
    return screenshot_file


# 比较图片差异度，result越大，差异度越大，result=0，图片相同
def compare_pictures(pic1, pic2):
    image1 = Image.open(pic1)
    image2 = Image.open(pic2)
    h1 = image1.histogram()
    h2 = image2.histogram()
    result = math.sqrt(reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2))) / len(h1))
    return result


# 获取登录token
def get_token():
    headers = {"Content-Type": "application/json; charset=UTF-8",
               "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                             "Chrome/91.0.4472.77 Safari/537.36"}
    params = {"phone": "13777867342", "authCode": "0000", "appTermEnum": "XIAOMAI_CLOUD_CLASS_PC_WEB_ADMIN"}
    data = json.dumps(params)
    url = "https://gateway.xiaomai5.com/hades/anon/hades/login?storeId=null&token=null&storeUserId=null&userId=null"
    r = requests.post(url=url, data=data, headers=headers)
    try:
        xmtoken = r.json()["result"]["xmToken"]
    except Exception as e:
        return r.json()["message"]
    return xmtoken


# 创建一个直播课，返回课程id和课程名称
def create_a_live(start_time, start_time2=None):
    xmtoken = get_token()
    while xmtoken == "登录过频繁":
        # 休息5s是因为可能会登录频繁
        time.sleep(5)
        xmtoken = get_token()
        print(xmtoken)
    dt = year_to_day() + ' 00:00:00'
    calendarTime = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))*1000
    startTime = now_time() + start_time*60*1000
    endTime = calendarTime + 23*60*60*1000
    # endTime = startTime + 5*60*1000
    courseName = ''.join(random.sample(string.ascii_letters + string.digits, 8))
    courseName2 = ''.join(random.sample(string.ascii_letters + string.digits, 8))
    url = "https://gateway.xiaomai5.com/hades/public/courseCloud/createLiveCloudCourse?storeId=1211601438838495999" \
          "&token={}&storeUserId=1394257952460828673&userId=1394908740376522754".format(xmtoken)
    params = {"adminIds": [], "calendarTime": [calendarTime], "categoryId": "1386892090935164929",
              "endTime": endTime, "needRecord": "YES", "startTime": startTime,
              "courseName": courseName, "storeId": "1211601438838495999", "teacherId": "1394908740376522754",
              "whetherVisitorsJoin": "NO", "scheduleMediaRequests": [], "operatorId": "1394908740376522754"}
    data = json.dumps(params)
    headers = {"Content-Type": "application/json; charset=UTF-8",
               "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                             "Chrome/91.0.4472.77 Safari/537.36",
               "storeId": "1211601438838495999",
               "storeUserId": "1394257952460828673",
               "xmtoken": xmtoken,
               "userId": "1394908740376522754",
               "product": "xmCloudClass"}
    r = requests.post(url=url, data=data, headers=headers)
    if start_time2 is not None:
        time.sleep(2)
        startTime2 = now_time() + start_time2*60*1000
        params2 = {"adminIds": [], "calendarTime": [calendarTime], "categoryId": "1386892090935164929",
                  "endTime": endTime, "needRecord": "YES", "startTime": startTime2,
                  "courseName": courseName2, "storeId": "1211601438838495999", "teacherId": "1394908740376522754",
                  "whetherVisitorsJoin": "NO", "scheduleMediaRequests": [], "operatorId": "1394908740376522754"}
        data2 = json.dumps(params2)
        r2 = requests.post(url=url, data=data2, headers=headers)
        try:
            # 校验result中是否会返回课程id
            assert r.json()["result"] != ''
            assert r2.json()["result"] != ''
            list1 = [courseName, courseName2]
            return list1
        except Exception as e:
            print(e.args)
    else:
        try:
            # 校验result中是否会返回课程id
            assert r.json()["result"] != ''
            return courseName
        except Exception as e:
            print(e.args)
