# -*- coding: utf-8 -*-
import json
import numbers
import os
import re
import time
import shutil
from datetime import datetime

import requests
from requests import session
from .qqmail import QQEmail
from .captchasolver import CaptchaSolver

from . import exceptions, helpers, webtrader
from .log import log

class ZSZQTrader(webtrader.WebTrader):
    """
    招商证券 web方式登录与交易
    """
    @property
    def broker_type(self):
        return "zszq"

    config_path = os.path.dirname(__file__) + "/config/zszq.json"

    captcha_file = "/tmp/zszq.jpg"

    _HEADERS = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) "
                      "AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/64.0.3282.167 Safari/537.36",
        "Host": "xtrade.newone.com.cn",
        "Pragma": "no-cache",
        "Connection": "keep-alive",
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Cache-Control": "no-cache",
        "Referer": "https://xtrade.newone.com.cn/ssologin?t=jykstd",
        "X-Requested-With": "XMLHttpRequest",
    }

    def __init__(self, **kwargs):
        super(ZSZQTrader, self).__init__()

        # 资金换算倍数
        self.multiple = (
            kwargs["initial_assets"] if "initial_assets" in kwargs else 1000000
        )
        if not isinstance(self.multiple, numbers.Number):
            raise TypeError("initial assets must be number(int, float)")
        if self.multiple < 1e3:
            raise ValueError("招商证券初始资产不能小于1000元，当前预设值 {}".format(self.multiple))

        self.s = requests.Session()
        self.s.verify = False
        self.s.headers.update(self._HEADERS)
        self.account_config = None

    def autologin(self, limit=10):
        """实现自动登录
        :param limit: 登录次数限制
        """
        for _ in range(limit):
            if self.login():
                break
        else:
            raise exceptions.NotLoginError(
                "登录失败次数过多, 请检查密码是否正确 / 券商服务器是否处于维护中 / 网络连接是否正常"
            )
        self.keepalive()

    def login(self):
        ts = int(time.time()*1000)
        res = self.s.get(self.config['captcha_url'].format(ts))
        if res.status_code == 200:
            cookies = res.cookies.get_dict()

            with open(self.config['captcha_file'], 'wb') as f:
                res.raw.decode_content = True
                shutil.copyfileobj(res.raw, f)
            captcha = CaptchaSolver('')
            captcha_value = captcha.solve(self.config['captcha_file'])
            self.s.post(self.config['sendsms_url'], data={"mobileNo":self.config['mobile']})
            sms_code = self.__get_sms_code(self.config['exqqmail'],self.config['qqmail_pass'])

    def __get_sms_code(self, mail_address, mail_pwd):

        M = QQEmail(mail_address, mail_pwd)
        ms = M.get_mails_header_by_folder("inbox")
        now = int(datetime.now().timestamp())
        for item in ms:
            mailtime = email.utils.mktime_tz(email.utils.parsedate_tz(item['Date']))
            if (item["Subject"]=="Message from 95565") and (now - mailtime < 120):
                msg = M.get_mail_body_by_id(id).decode("gbk")
                
                return matchobj.group(1)


# -*- coding: utf-8 -*-
import json
import numbers
import os
import re
import time
import shutil
from datetime import datetime

import requests
from requests import session
from .qqmail import QQEmail
from .captchasolver import CaptchaSolver

from . import exceptions, helpers, webtrader
from .log import log

class ZSZQTrader(webtrader.WebTrader):
    """
    招商证券 web方式登录与交易
    """
    @property
    def broker_type(self):
        return "zszq"

    config_path = os.path.dirname(__file__) + "/config/zszq.json"

    captcha_file = "/tmp/zszq.jpg"

    _HEADERS = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) "
                      "AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/64.0.3282.167 Safari/537.36",
        "Host": "xtrade.newone.com.cn",
        "Pragma": "no-cache",
        "Connection": "keep-alive",
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Cache-Control": "no-cache",
        "Referer": "https://xtrade.newone.com.cn/ssologin?t=jykstd",
        "X-Requested-With": "XMLHttpRequest",
    }

    def __init__(self, **kwargs):
        super(ZSZQTrader, self).__init__()

        # 资金换算倍数
        self.multiple = (
            kwargs["initial_assets"] if "initial_assets" in kwargs else 1000000
        )
        if not isinstance(self.multiple, numbers.Number):
            raise TypeError("initial assets must be number(int, float)")
        if self.multiple < 1e3:
            raise ValueError("招商证券初始资产不能小于1000元，当前预设值 {}".format(self.multiple))

        self.s = requests.Session()
        self.s.verify = False
        self.s.headers.update(self._HEADERS)
        self.account_config = None

    def autologin(self, limit=10):
        """实现自动登录
        :param limit: 登录次数限制
        """
        for _ in range(limit):
            if self.login():
                break
        else:
            raise exceptions.NotLoginError(
                "登录失败次数过多, 请检查密码是否正确 / 券商服务器是否处于维护中 / 网络连接是否正常"
            )
        self.keepalive()

    def login(self):
        ts = int(time.time()*1000)
        res = self.s.get(self.config['captcha_url'].format(ts))
        if res.status_code == 200:
            cookies = res.cookies.get_dict()

            with open(self.config['captcha_file'], 'wb') as f:
                res.raw.decode_content = True
                shutil.copyfileobj(res.raw, f)
            captcha = CaptchaSolver('')
            captcha_value = captcha.solve(self.config['captcha_file'])
            self.s.post(self.config['sendsms_url'], data={"mobileNo":self.config['mobile']})
            sms_code = self.__get_sms_code(self.config['exqqmail'],self.config['qqmail_pass'])

    def __get_sms_code(self, mail_address, mail_pwd):

        M = QQEmail(mail_address, mail_pwd)
        ms = M.get_mails_header_by_folder("inbox")
        now = int(datetime.now().timestamp())
        for item in ms:
            mailtime = email.utils.mktime_tz(email.utils.parsedate_tz(item['Date']))
            if (item["Subject"]=="Message from 95565") and (now - mailtime < 120):
                msg = M.get_mail_body_by_id(id).decode("gbk")
                
                return matchobj.group(1)


# -*- coding: utf-8 -*- 招商证券 web方式登录与交易 # 资金换算倍数 实现自动登录         :param limit: 登录次数限制