import requests
import urllib.parse
import json
import random
import time
import datetime
import sys

import para
import config

TODAY = None
TODAY_SUCCESS = False
TODAY_EXEC_TIME = None

# d_start_time = None
# d_end_time = None

def getHeader():
    return {
        "User-Agent":"Mozilla/5.0 (Linux; Android 10; MI 9 Build/QKQ1.190825.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045511 Mobile Safari/537.36 MMWEBID/1122 MicroMessenger/7.0.20.1781(0x27001439) Process/toolsmp WeChat/arm64 NetType/4G Language/zh_CN ABI/arm64"
    }

def getObj(sxid, xssxglid, lat, lng, title):
    obj = {}
    obj['cnz022'] = sxid
    obj['cnz058'] = xssxglid
    obj['cne640'] = lat
    obj['cne641'] = lng
    obj['cne642'] = title
    return json.dumps(obj,separators=(',',':'), ensure_ascii=False)


def getTime():
    return int(round(time.time()*1000))


def f_login(session):
    p = para.get()
    try:
        r = session.get("https://hrsspub.sz.gov.cn/jgxxfw/jgfw/sooLogin", params = {
            "para": p,
            "type": 1,
            "_": getTime()
        }, headers=getHeader())
        if r.text.find('"status":200') == -1:
            if r.text.find('系统异常'):
                print("[%s] %s" % (TODAY, '登录无效，请检查para'))
            else:
                print("[%s] %s" % (TODAY, '未知错误'))
            return False
    except Exception as e:
        print("[%s] %s" % (TODAY, e))
        return False
    else:
        return True
    
def f_getKq(session):
    try:
        r = session.post("https://hrsspub.sz.gov.cn/jgxxfw/jgfw/ydfw/student/getKqdd", headers=getHeader())
        if r.text.find('"status":200') == -1:
            print("[%s] %s" % (TODAY, r.text))
            return False
        else:
            data = json.loads(r.text)
            if 'result' in data and 'xssxglid' in data['result'] and 'sxid' in data['result'] and 'data' in data['result'] and  len(data['result']['data'])!= 0 and 'cnz080' in data['result']['data'][0] and 'cnz058' in data['result']['data'][0] and 'lat' in data['result']['data'][0] and 'lng' in data['result']['data'][0] and 'title' in data['result']['data'][0]:
                return f_submitKq(session, getObj(data['result']['sxid'], data['result']['xssxglid'], data['result']['data'][0]['lat'], data['result']['data'][0]['lng'], data['result']['data'][0]['title']))
            else:
                print("[%s] %s" % (TODAY, data))
                print("[%s] %s" % (TODAY, '缺少部分信息，无法进行打卡'))
                return False
    except Exception as e:
        print("[%s] %s" % (TODAY, e))
        return False

def f_submitKq(session, data):
    try:
        r = session.get('https://hrsspub.sz.gov.cn/jgxxfw/jgfw/ydfw/student/addKqjl', params = {
            "xskqjlxxDTO": data,
            "_": getTime()
        }, headers=getHeader())
        print("[%s] 服务端数据：%s" % (TODAY, r.text))
        d = json.loads(r.text)
        if 'status' in d:
            if d['status'] == 200 or d['status'] == 300:
                return True

    except Exception as e:
        print("[%s] %s" % (TODAY, e))
        return False
    return False

def getToday():
    return str(datetime.datetime.now().date())

def getRandomTime():
    d_start_time = datetime.datetime.strptime(TODAY+" %d:%d:00" % (config.START_TIME[0], config.START_TIME[1]), '%Y-%m-%d %H:%M:%S')
    d_end_time = datetime.datetime.strptime(TODAY+" %d:%d:59" % (config.END_TIME[0], config.END_TIME[1]), '%Y-%m-%d %H:%M:%S')
    i_start_time = int(time.mktime(d_start_time.timetuple()))
    i_end_time = int(time.mktime(d_end_time.timetuple()))
    return datetime.datetime.fromtimestamp(random.randint(i_start_time, i_end_time))
    

def f_start():
    global TODAY_SUCCESS
    session = requests.session()
    success = f_login(session)
    if not success:
        return False
    TODAY_SUCCESS = f_getKq(session)
    print("[%s] %s %s" % (TODAY, ("成功" if TODAY_SUCCESS else "失败"), datetime.datetime.now()))
    return TODAY_SUCCESS

def f_loop():
    global TODAY, TODAY_SUCCESS, TODAY_EXEC_TIME
    while True:
        if not config.check_rule():
            if not TODAY_SUCCESS or not TODAY == getToday():
                print("[%s] 今日无需打卡" % TODAY)
                TODAY = getToday()
                TODAY_SUCCESS = True
            time.sleep(5)
            continue
        now = datetime.datetime.now()
        if TODAY_EXEC_TIME is None and not TODAY_SUCCESS: # 首次运行
            TODAY_SUCCESS = False
            TODAY_EXEC_TIME = datetime.datetime.strptime(TODAY+" %d:%d:00" % (config.END_TIME[0], config.END_TIME[1]), '%Y-%m-%d %H:%M:%S')
            if TODAY_EXEC_TIME < now:
                print("[%s] 今日超过设置时间，将不打卡" % TODAY)
                TODAY_SUCCESS = True
                time.sleep(5)
                continue
            else:
                print("[%s] 开始打卡时间：现在" % TODAY)
                succ = f_start()
                if not succ: # 失败等待1分钟后重试
                    TODAY_EXEC_TIME = None
                    time.sleep(60)
                else:
                    time.sleep(5)
                continue
        
        if not TODAY == getToday():
            TODAY = getToday()
            TODAY_SUCCESS = False
            TODAY_EXEC_TIME = getRandomTime()
            print("[%s] 开始打卡时间：%s" % (TODAY, TODAY_EXEC_TIME))
        
        end_time = datetime.datetime.strptime(TODAY+" %d:%d:59" % (config.END_TIME[0], config.END_TIME[1]), '%Y-%m-%d %H:%M:%S')
        if now >= end_time and not TODAY_SUCCESS: # 超过考勤时间
            print("[%s] 今日超过设置时间，将不打卡" % TODAY)
            TODAY_SUCCESS = True
            time.sleep(5)
            continue
        
        if now >= TODAY_EXEC_TIME and not TODAY_SUCCESS:
            succ = f_start()
            if not succ: # 失败等待1分钟后重试
                time.sleep(60)
            else:
                time.sleep(5)
            continue
        
        time.sleep(5)


if __name__ == '__main__':
    TODAY = getToday()
    d_start_time = datetime.datetime.strptime(TODAY+" %d:%d:00" % (config.START_TIME[0], config.START_TIME[1]), '%Y-%m-%d %H:%M:%S')
    d_end_time = datetime.datetime.strptime(TODAY+" %d:%d:59" % (config.END_TIME[0], config.END_TIME[1]), '%Y-%m-%d %H:%M:%S')
    if not d_start_time <= d_end_time:
        print("[%s] %s" % (TODAY, 'config.py 时间区间错误'))
        sys.exit()
    f_loop()
    
