import sys
import json
import datetime
import requests
import time

def send_msg_tip(msg_tip):
    # get the datetime, which is using at a failed situation
    alert_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    # Enterprise WeChat Bot API and the format of body to send
    hook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ddea3f5f-fbfc-4c21-994a-71e9fc50e4ef'
    body = {
        "msgtype": "text",
        "text": {
            "content": msg_tip
        }
    }

    # get the result of API call
    res = requests.post(hook_url, data=json.dumps(body, ensure_ascii=False).encode('utf-8'))

    # when failed, log it in /opt/logs/alert.log file
    if res.status_code != 200:
        with open('/opt/logs/alert.log', 'a', encoding='utf-8') as alert_log:
            alert_log.write(alert_datetime + ' >>>> ')
            alert_log.write('Failed sending message: ')
            alert_log.write(msg_tip + '\n')


def weather_forcast(app_id, app_secret, city):
    api_url = f"https://www.mxnzp.com/api/weather/forecast/{city}?app_id={app_id}&app_secret={app_secret}"
    res = requests.get(api_url)
    res_http_code = res.status_code
    res_text = json.loads(res.text)
    res_code = res_text['code']
    res_msg = res_text['msg']
    # print(res.text)
    if res_http_code != 200 or res_code == 0:
        print(f"接口查询失败：{res_msg}")
    else:
        # print(res_text['data']['forecasts'])
        today = datetime.date.today()
        hour = datetime.datetime.now().hour
        msg_tip = f"{today} {hour}时，查询到{city}最近四天的天气情况如下：\n"
        msg_tip += ('*' * 30 + '\n')
        when = {1: '今天', 2: '明天', 3: '后天', 4: '大后天', }
        week_index = {1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '天', }
        count = 1
        for item in res_text['data']['forecasts']:
            item_date = item['date']
            item_dayofweek = week_index[int(item['dayOfWeek'])]
            if item['dayWeather'] == item['nightWeather']:
                msg_tip += f"{when[count]}({item_date} 星期{item_dayofweek})全天天气是{item['dayWeather']}，"
            else:
                msg_tip += f"{when[count]}({item_date} 星期{item_dayofweek})白天天气是{item['dayWeather']}，夜间会转为{item['nightWeather']}，"

            msg_tip += f"最高温{item['dayTemp']}，最低温{item['nightTemp']}，"

            difftemp = int(item['dayTemp'].removesuffix('℃')) - int(item['nightTemp'].removesuffix('℃'))
            if difftemp > 10:
                msg_tip += f"昼夜温差{difftemp}℃，请注意增减衣物，切勿感冒；"

            if item['dayWindDirection'] == item['nightWindDirection']:
                msg_tip += f"{when[count]}全天是{item['dayWindDirection']}风，"
                if item['dayWindPower'] == item['nightWindPower']:
                    msg_tip += f"风力为{item['dayWindPower']}。\n"
                else:
                    msg_tip += f"白天风力为{item['dayWindPower']}，夜间风力为{item['nightWindPower']}。\n"
            else:
                msg_tip += f"{when[count]}白天是{item['dayWeather']}风，夜间会转为{item['nightWeather']}风，"
                if item['dayWindPower'] == item['nightWindPower']:
                    msg_tip += f"风力为{item['dayWindPower']}。\n"
                else:
                    msg_tip += f"白天风力为{item['dayWindPower']}，夜间风力为{item['nightWindPower']}。\n"
            count += 1
            msg_tip += ('*' * 30 + '\n')

        # print(msg_tip)
        send_msg_tip(msg_tip)


def main():
    app_id = "nrsngdkvknqkrwko"
    app_secret = "SFFmQWo2dnNBRjdNYkVSclZxa2ZvUT09"
    # holiday_today(app_id, app_secret)
    # ip_self(app_id, app_secret)
    try:
        city = sys.argv[1]
    except Exception as Err:
        print(f"Error Desc: {Err}. Maybe you need to supply correct city next time.")
        exit(2)

    weather_forcast(app_id, app_secret, city)


if __name__ == '__main__':
    main()

