import urllib.request as ur
import ssl
import json
import time
import sys


def signIn(token, tpye, context,addr,longitude,latitude):
    data_dict = {
        "device": "Android",
        "address": addr,
        "description": "",
        "longitude": longitude,
        "latitude": latitude,
        "planId": "440e293d026523066219350751883338",
        "type": tpye
    }
    url = 'https://api.moguding.net:9000/attendence/clock/v1/save'
    headers = {
        'Authorization': token,
        'Content-Type': 'application/json; charset=UTF-8',
        'roleKey': 'student'
    }
    data = json.dumps(data_dict)
    requests = ur.Request(url=url, data=data.encode("utf-8"), headers=headers)
    try:
        if json.loads(ur.urlopen(requests, context=context).read().decode())['code'] == 200:
            print("签到成功")
            with open('C:/Users/Administrator/Desktop/signlog.txt', 'a+') as f:
                f.write(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '签到成功\n')
            pass
        else:
            print("签到失败")
            with open('C:/Users/Administrator/Desktop/signlog.txt', 'a+') as f:
                f.write(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '签到失败\n')
    except Exception as e:
        print("签到失败")
        pass


def login(type, context,phone,password):
    login_data = {
        "phone": phone,
        "password": password,
        "uuid": "",
        "loginType": "android"
    }
    request_login = ur.Request(
        url='https://api.moguding.net:9000/session/user/v1/login',
        data=json.dumps(login_data).encode(),
        headers={
            'Content-Type': 'application/json; charset=UTF-8'
        }
    )
    try:
        token = json.loads(ur.urlopen(request_login, context=context).read().decode())['data']['token']
        if token:
            signIn(token, type, context,sys.argv[3],sys.argv[4],sys.argv[5])
    except Exception as e:
        datad = '<urlopen error Remote end closed connection without response>'
        if datad == str(e):
            print('网络连接超时')
        else:
            print('账号或密码输入错误')
        pass


if __name__ == '__main__':
    context = ssl._create_unverified_context()
    
    if(sys.argv[6]=="上班"):
        login("START", context,sys.argv[1],sys.argv[2])
    elif(sys.argv[6]=="下班"):
        login("END", context,sys.argv[1],sys.argv[2])   
    

