# -*- coding: utf-8 -*-
import os
import time
import sys
import json
import chromedriver_binary
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
import urllib.request
from pprint import pprint
import datetime
import calendar
import urllib.request
import re
from webdriver_manager.chrome import ChromeDriverManager

def get_first_date(year, month):
    return datetime.date(year, month, 1)

def get_last_date(year, month):
    return datetime.date(year, month, calendar.monthrange(year, month)[1])

keys_json = open('config.json', 'r')
keys = json.load(keys_json)


#任意に変更してください
USER_ID = keys["user_id"]
PASSWORD = keys["password"]
# DRIVER_PATH = keys["driver_path"]
BASE_URL = 'https://affiliate.amazon.co.jp/home/'
#TARGET_UPDATE_MOSHIMO_URL = "http://192.168.10.20/items/update_moshimo_affiliate"
TARGET_UPDATE_MOSHIMO_URL = "https://comicy.jp/items/update_moshimo_affiliate"


#キャッシュディレクトリの作成
path = os.getcwd()
tmp_dir_name = 'tmp_data'
os.makedirs(tmp_dir_name, exist_ok=True)






options = Options()
options.add_argument('--user-data-dir='+ path + '\\' + tmp_dir_name)
#https://www.cloudgate.jp/ua.php
#ここにUAを書きます。
#--user-agent= ***
if('user_agent' in keys == False):
    options.add_argument('--user-agent=' + keys["user_agent"])
else:
    options.add_argument('--user-agent=' + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')


# driver = webdriver.Chrome(chrome_options=options)
driver = webdriver.Chrome(ChromeDriverManager().install(),options=options)
# if DRIVER_PATH == '':
#     driver = webdriver.Chrome(chrome_options=options)
# else:
#     driver = webdriver.Chrome(chrome_options=options,executable_path=DRIVER_PATH)


if __name__ == '__main__':
    try:

        print("start")

        profit = 0
        print(datetime.date.today().strftime('%Y-%m-%d'))

        year = int(datetime.date.today().strftime('%Y'))
        month = int(datetime.date.today().strftime('%m'))

        # year = 2021
        # month = 2


        start_date = str(get_first_date(year,month))
        end_date = str(get_last_date(year,month))

        print(start_date + " ~ " + end_date)


        url = "https://af.moshimo.com/af/shop/report/kpi/site?"

        url += "from_date="+start_date+"&"
        url += "to_date="+end_date+"&"
        url += "order=result_price_d&"
        url += "terminal_type=0&"
        url += "period=month"

        driver.get(url)


        sleep_time = 3
        print(str(sleep_time)+"秒待機")
        time.sleep(sleep_time)


        #ログイン処理
        if len(driver.find_elements_by_xpath("//input[@name='account']")) == 1:
            print("ログイン処理")
            email_elem = driver.find_element_by_xpath("//input[@name='account']")
            email_elem.send_keys(USER_ID)

        if len(driver.find_elements_by_xpath("//input[@name='password']")) == 1:
            password_elem = driver.find_element_by_xpath("//input[@name='password']")
            password_elem.send_keys(PASSWORD)

        if len(driver.find_elements_by_xpath("//input[@name='login']")) == 1:
            submit_elem = driver.find_element_by_xpath("//input[@name='login']")
            submit_elem.click()

        sleep_time = 3
        print(str(sleep_time)+"秒待機")
        time.sleep(sleep_time)


        


        #利益取得
        elems = driver.find_elements_by_class_name('line-color-1')
        for elem in elems:
            
            site_name = elem.find_element_by_class_name('column-site-name').text

            child_elems = elem.find_elements_by_class_name('column-result')
            for child_elem in child_elems:

                p_elems = child_elem.find_elements_by_tag_name('p')
                for p_elem in p_elems:
                    if p_elem.text.find('円') >= 0:

                        # print(p_elem.text)

                        profit = re.sub(r'\D','',p_elem.text)
                        print(str(profit))
                        break
                    



        dict = {}
        dict['start_date'] = start_date
        dict['end_date'] = end_date
        dict['profit'] = profit
        dict['site_name'] = site_name

        json_data = json.dumps(dict)

        print(json_data)

        url = TARGET_UPDATE_MOSHIMO_URL
        method = "POST"
        obj = {
            "json_data" : json_data,
        }

        json_data = json.dumps(obj).encode("utf-8")
        headers = {"Content-Type" : "application/json"}

        request = urllib.request.Request(url, data=json_data, headers=headers, method=method)
        with urllib.request.urlopen(request) as response:
            pprint(response)
            response_body = response.read().decode("utf-8")
            print(response_body)



        print("処理終了")







    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)

    finally:
        driver.quit()
        print("end")




    
