﻿#!/usr/bin/env python
# coding: utf-8

from dateutil.relativedelta import relativedelta
import datetime
import os
import csv

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.wait import WebDriverWait
from time import sleep


MUFG_TOP_URL = 'https://entry11.bk.mufg.jp/ibg/dfw/APLIN/loginib/login?_TRANID=AA000_001'
INFORMATION_TITLE = 'お知らせ - 三菱東京ＵＦＪ銀行'
# MUFG_ID&Pass
ACCOUNT_ID = os.environ['ACCOUNT_ID']
IB_PASSWORD = os.environ['IB_PASSWORD']

driver = webdriver.PhantomJS( executable_path='./phantomjs' )


def login(account_id: str, ib_password: str):
	str_error = None
	for x in range(0, 5):  # try 4 times
		try:
			driver.get(MUFG_TOP_URL)
			sleep(2)
			driver.find_element_by_id('tx-contract-number').send_keys(account_id)
			driver.find_element_by_id('tx-ib-password').send_keys(ib_password)
			#driver.find_element_by_xpath('//img[@alt="ログイン"]').click()
			driver.find_element_by_xpath('//button[@class="gonext"]').click()
			str_error = None
		except Exception as str_error:
			pass
		if str_error:
			sleep(4)  # wait for 2 seconds before trying to fetch the data again
			if x == 4:
				error_path ='{}/{}'.format( os.environ['BKLIST_PATH'], 'error.txt')
				fp_error= open(error_path, "w", encoding="utf-8")
				fp_error.write(str_error.message + ':'  + str_error.args + '\n')
				fp_error.flush()
				fp_error.close()
		else:
			break


def logout():
	# <li class="logout"><a href="#" onClick="JavaScript:logoutFromAD001(); return false;">ログアウト</a></li>
	driver.find_element_by_link_text('ログアウト').click()


def read_information():
	"""
	お知らせがある場合は既読にします
	:return:
	"""
	while True:
		if not driver.title == INFORMATION_TITLE:
			return
		information = driver.find_element_by_xpath(
			'//table[@class="data"]/tbody/tr')
		information.find_element_by_name('hyouzi').click()
		driver.find_element_by_xpath('//img[@alt="トップページへ"]').click()


def select_selectbox_value(element_name: str, value: str):
	"""
	セレクトボックスの値を選択します
	:param element_name:
	:param value:
	:return:
	"""
	selectbox = Select(driver.find_element_by_name(element_name))
	#print(str(value))
	selectbox.select_by_visible_text(str(value))


def select_time_period(_from: datetime, _to: datetime):
	"""
	指定した表示期間を選択します
	:param _from:
	:param _to:
	:return:
	"""

	wait = WebDriverWait(driver, 30)
	wait.until(ec.presence_of_element_located((By.ID, 'appoint')))

	driver.find_element_by_id('appoint').click()
	# driver.find_element_by_name('SHOUKAIKIKAN_RADIO').click()

	select_selectbox_value('SHOUKAIKIKAN_FROM_Y', str(_from.year))
	select_selectbox_value('SHOUKAIKIKAN_FROM_M', str(_from.month))
	select_selectbox_value('SHOUKAIKIKAN_FROM_D', str(_from.day))
	select_selectbox_value('SHOUKAIKIKAN_TO_Y', str(_to.year))
	select_selectbox_value('SHOUKAIKIKAN_TO_M', str(_to.month))
	select_selectbox_value('SHOUKAIKIKAN_TO_D', str(_to.day))


def show_details(_fp_list, _fp_book, _last: str,  _dataline: str):
	banking_list = driver.find_elements_by_xpath(
		'//table[@class="data memo yen_nyushutsukin_003"]/tbody/tr')
	flg = 0
	lastflg = 0
	for banking in banking_list:
		detail = banking.find_elements_by_tag_name('td')

		date = datetime.datetime.strptime(detail[0].text.replace('\n', ''), '%Y年%m月%d日')

		#payment = in_or_out_payment(detail[1].text, detail[2].text)
		content = detail[3].text
		conlist = content.split("　")
		cont1=conlist[0]
		del conlist[0]
		cont2=''.join(conlist)
		total = to_number(detail[4].text)
		pay = to_number(detail[1].text)
		income = to_number(detail[2].text)
		line = '{}\t{}\t{}\t{}\t{}\t{}'.format(date.strftime('%Y-%m-%d'),cont1, cont2, pay, income , total )
		_fp_list.write(line + '\n')
		print(line)
		
		if flg == 1:
			if lastflg == 0:
				#print(dataline)
				_fp_book.write(_dataline + '\n')
			_fp_book.write(line + '\n')
			lastflg = flg
		else:
			lastflg = flg
			if _last == '':
				flg=1
			if _last == line + '\n':
				flg=1

	try:
		driver.find_element_by_xpath('//a/img[@alt="新しい明細"]').click()
	except NoSuchElementException:
		return
	else:
		# 例外がない(=次のページがある)から次のページへ
		show_details()


def to_number(yen: str) -> int:
	"""
	xxx,xxx,xxx円からカンマと「円」を削除します
	:param yen:
	:return: int:
	"""
	if yen == '':
		return ''
	return int(yen.replace(',', '').replace('円', ''))


def in_or_out_payment(_out: str, _in: str) -> int:
	"""
	入出金の判定を行います
	:param _out:
	:param _in:
	:return:
	"""
	if not _out == '':
		# 出金
		return to_number(_out) * -1
	# 入金
	return to_number(_in)


def main(_from: datetime, _to: datetime):
	try:
		#account_id = os.environ['ACCOUNT_ID']
		#ib_password = os.environ['IB_PASSWORD']
		account_id = ACCOUNT_ID
		ib_password = IB_PASSWORD

		login(account_id, ib_password)
		
		str_error = None
		for x in range(0, 5):  # try 4 times
			try:
				##driver.find_element_by_link_text('入出金明細').click()
				driver.find_element_by_xpath('//div[@class="detail"]').click()
				str_error = None
			except Exception as str_error:
				pass
			if str_error:
				driver.navigate().refresh();
				if x == 4:
					error_path ='{}/{}'.format( os.environ['BKLIST_PATH'], 'error.txt')
					fp_error= open(error_path, "w", encoding="utf-8")
					fp_error.write(str_error.message + ':'  + str_error.args + '\n')
					fp_error.flush()
					fp_error.close()
			else:
				break


		# お知らせ画面がある場合は既読にする
		read_information()
		
		

		# 残高を取得
		#total = driver.find_element_by_id('setAmountDisplay')
		total = driver.find_element_by_xpath('//td[@class="number"]/strong')
		print(total.text )
		total_amount = to_number(total.text)
		##total = driver.find_element_by_id('account')
		##total_amount = to_number(total.text)

		print('{:,d}円'.format(total_amount))

		##driver.find_element_by_xpath('//img[@alt="入出金明細をみる"]').click()

		# 期間を指定する
		select_time_period(_from, _to)
		driver.find_element_by_xpath('//img[@alt="照会"]').click()
		flist_path ='{}/{}'.format( os.environ['BKLIST_PATH'], os.environ['BKLIST_NAME'])
		fbook_path ='{}/{}'.format( os.environ['BKLIST_PATH'], os.environ['BKBOOK_NAME'])
		
		targetLine = ""
		if os.path.isfile(fbook_path):
			fcheck = open(fbook_path, "r", encoding="utf-8")
			while 1:
				mLine = fcheck.readline();
				if not mLine:
					break;
				targetLine = mLine;
			fcheck.close()
		fp_list = open(flist_path, "a", encoding="utf-8")
		fp_book = open(fbook_path, "a", encoding="utf-8")
		
		dataline = '------------------{}----------------'.format(datetime.datetime.now().strftime('%Y-%m-%d  %H:%M:%S'))
		print(dataline)
		fp_list.write(dataline + '\n' )
		show_details(fp_list, fp_book, targetLine, dataline)
		fp_book.flush()
		fp_book.close()
		
		fp_list.flush()
		fp_list.close()
		##driver.find_element_by_xpath('//img[@alt="明細をダウンロード"]').click()
		##
		##select_time_period(_from, _to)
		##driver.find_element_by_xpath('//img[@alt="ダウンロード（CSV形式）"]').click

		logout()
	finally:
		driver.close()

if __name__ == '__main__':
	td_1m =relativedelta(months=1) 
	end = datetime.datetime.now()
	tmp_start = end - td_1m
	start = datetime.datetime(year=tmp_start.year, month=tmp_start.month, day=1)
	main(start, end)
