#!/usr/bin/env python3
from datetime import datetime

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time


class Taobao:
    def __init__(self):
        self._driver = webdriver.Firefox(firefox_binary='C:\\Program Files\\Mozilla Firefox\\firefox.exe',
                                         executable_path='C:\\Program Files\\Mozilla Firefox\\geckodriver.exe')

    def _log(self, s):
        print('[Taobao][%s] : %s' % (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), s))
        print('by:52pojie - 夏天夏天悄悄过去留下小秘密~~~')
        print('此脚本理论永久有效，如有bug反馈给作者不定时更新')

    def _waite_for_element_id(self, id):
        locator_ma = (By.ID, id)
        WebDriverWait(self._driver, 20, 0.5).until(EC.presence_of_element_located(locator_ma))

    def _waite_for_element_xpath(self, xpath):
        locator_ma = (By.XPATH, xpath)
        WebDriverWait(self._driver, 20, 0.5).until(EC.presence_of_element_located(locator_ma))

    def _do_click_on_point(self, element, x, y):
        ActionChains(self._driver).move_to_element_with_offset(element, x, y).click().perform()

    def qr_login(self):
        self._driver.get('https://login.taobao.com/')
        switch_button_id = 'J_Static2Quick'
        self._waite_for_element_id(switch_button_id)
        self._log('登录页面载入完成')
        ma = self._driver.find_element_by_id(switch_button_id)
        if not ma.is_displayed():
            self._log('页面切换失败，请手动切换二维码登录')
        else:
            self._do_click_on_point(ma, 20, 0)
            self._log('已切换为二维码登录，请扫码登录')
        self._waite_for_element_xpath('/html/body/div[1]/div[1]/div/ul[1]/li[2]/div[1]/div[2]/a[1]')
        self._log('登录成功')

    @staticmethod
    def _datetime_to_timestamp(dt):
        t = dt.timetuple()
        ts = int(time.mktime(t))
        ts = float(str(ts) + str("%06d" % dt.microsecond)) / 1000000
        return ts

    def buy_on_cart(self, start, end):
        while True:
            start_ts = int(self._datetime_to_timestamp(datetime.fromisoformat(datetime.now().date().strftime('%Y-%m-%d') + 'T' + start)))
            end_ts = int(self._datetime_to_timestamp(datetime.fromisoformat(datetime.now().date().strftime('%Y-%m-%d') + 'T' + end)))
            ts = int(time.time())
            if ts < start_ts:
                self._log('秒杀时间没到，%s' % start)
                time.sleep(0.5)
                continue
            if ts > end_ts:
                self._log('秒杀时间已过，秒杀失败，%s-%s' % (start, end))
                return
            try:
                self._driver.get('https://cart.taobao.com/cart.htm')
                select_all_checkbox = '/html/body/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[1]/div/div'
                self._waite_for_element_xpath(select_all_checkbox)
                self._log('购物车页面加载完成')
                select_all = self._driver.find_element_by_xpath(select_all_checkbox)
                if not select_all.is_displayed():
                    self._log('没找到全选按钮或者购物车为空')
                    return
                self._do_click_on_point(select_all, 0, 0)
                self._log('全选成功')
                settlement = self._driver.find_element_by_xpath('//*[@id="J_Go"]')

                # wait for button enable
                while 'disabled' in settlement.get_attribute('class'):
                    time.sleep(0.1)

                settlement = self._driver.find_element_by_xpath(
                    '/html/body/div[1]/div[2]/div[2]/div/div[3]/div/div[2]/div[3]/div[5]/a/span')
                self._do_click_on_point(settlement, 0, 0)

                self._driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div[1]/div[1]/div/div[9]/div/div/a[2]')
                break
            except Exception:
                self._log('未找到元素，正在重试')
                time.sleep(1)
                continue
            submit_order = self._driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div[1]/div[1]/div/div[9]/div/div/a[2]')
            self._log('正在提交订单')
            self._do_click_on_point(submit_order, 0, 0)
            raise RuntimeError('秒杀有可能成功了')


def main():
    t = [('09:59:30', '10:01:00'), ('19:59:30', '20:01:00')]
    tb = Taobao()
    tb.qr_login()
    for start, end in t:
        tb.buy_on_cart(start, end)


if __name__ == "__main__":
    main()


