# -*- coding: utf-8 -*-
# 多线程类
# 作者: 陈磊
# 时间: 2019-10-21

import threading
import requests
import time
import json

from WorkUtils.UtilsLog import UtilsLog


class UtilsThread:
    def __init__(self, url, headers, params, method, thread_num, every_num):
        self.log = UtilsLog()
        self.log.info("调用多线程类")
        self.log.info(self.__class__)

        self.url = url
        self.headers = headers
        self.params = params
        self.method = method
        self.thread_num = thread_num
        self.every_num = every_num
        self.response = ""
        self.responses = []

    def thread_api(self, headers):
        try:
            if self.method == "Post":
                self.response = requests.post(url=self.url, headers=headers, params=self.params)
                return self.response
            if self.method == "Get":
                self.response = requests.get(url=self.url, headers=headers, params=self.params)
                return self.response
            else:
                return False
        except requests.ConnectionError:
            return False

    def thread_error(self, headers):
        try:
            code = self.thread_api(headers).status_code
            if code == 200:
                text = self.thread_api(headers).text
                self.log.info("状态码：" + str(code))
                self.log.info(text)
                self.responses.append(text)
                return True
            else:
                self.log.info("状态码：" + str(code))
                return False
        except AttributeError:
            self.log.info("请求异常")
            return False

    def thread_work(self, headers):
        self.log.info("请求地址:" + self.url)
        thread_name = threading.currentThread().getName()
        self.log.info(time.asctime(time.localtime(time.time())))
        self.log.info(thread_name + "线程开始")
        self.thread_api(headers)
        self.thread_error(headers)
        self.log.info(thread_name + "线程结束...")
        self.log.info(time.asctime(time.localtime(time.time())))

    def thread_run(self):
        threads = []
        for i in range(self.thread_num):
            self.log.info(self.headers[i])
            t = threading.Thread(target=self.thread_work(self.headers[i]))
            t.setDaemon(True)
            threads.append(t)
        for t in threads:
            t.start()
        # 启动所有线程
        for t in threads:
            t.join()


if __name__ == '__main__':
    # h = [
    #     {'userToken': '74b6873e1240f1d2d16edd692b8cf7e4', 'platForm': 'Test'},
    #     {'userToken': 'cc18e1c142d05f5d2df543ec63c2fbaf', 'platForm': 'Test'}
    # ]
    # a = UtilsThread(url="http://shop.uat.cnmmt.com/rapi/coupon/add", headers=h,
    #                 params={'coupon_id': '179'}, method="Post", thread_num=2, every_num=1)
    # a.thread_run()
    import datetime

    a = time.strftime("%Y-%m-%d 00:00:00")
    print()

