
#!/usr/bin/python3
# coding=utf-8
##################################################################
#              ____     _     _ __  __                 
#             / __/__  (_)___(_) /_/ /  ___  ___  ___ _
#            _\ \/ _ \/ / __/ / __/ /__/ _ \/ _ \/ _ `/
#           /___/ .__/_/_/ /_/\__/____/\___/_//_/\_, / 
#              /_/                              /___/  
# 
# Copyright (c) 2026 Chongqing Spiritlong Technology Co., Ltd.
# All rights reserved.
# @author	arthuryang
# @brief	财务处理
##################################################################

import	os
import	SpiritLong_utility
import	SpiritLong_excel
import	accounting

from	SpiritLong_database.database_SQLite	import	SQLiteDatabase

## 从银行对账记录导入对账数据，记录文件格式应该是xlsx，其他格式需要先转换
# 每个记录都应该包含时间/收支/余额信息
def get_balance_from_xlsx(filename):
	# 打开数据文件
	book	= SpiritLong_excel.open_xlsx(filename)
	if not book:
		return None
	
	# 读取全部数据
	cells	= SpiritLong_excel.get_cells(book.active)

	# 根据情况添加可能的名称
	titles	= {
		'TIME'		: ['时间', '交易日期', '交易时间'],
		'INCOMING'	: ['收入', '收入金额', '交易金额(收入)', '收支', '金额(元)', '记账金额(收入)'],	# 如果收支在一起，则放在这里
		'OUTGOING'	: ['支出', '支出金额', '交易金额(支出)', '记账金额(支出)'],			
		'BALANCE'	: ['余额', '账户余额', '余额(元)', '账户余额（元）'],
		'CHANNEL'	: ['交易渠道', '交易场所', '资金渠道'],
		'PAYER_NUMBER'	: ['付款账号', '对方账号'],	# 只有对方的情况，放在PAYER
		'PAYER_NAME'	: ['付款账户名', '对方户名'],
		'PAYER_BANK'	: ['对方开户行'],
		'PAYEE_NUMBER'	: ['收款账号'],
		'PAYEE_NAME'	: ['收款账户名'],
		'REMARK'	: ['交易名称', '备注', '交易说明'],
		'BRIEF'		: ['摘要（备注）', '摘要', '名称'],
		'USAGE'		: ['用途', '交易用途'],
	}

	# 寻找标题栏： TIME BALANCE INCOMING的标题都出现的那一行
	title_row	= -1
	for i, r in enumerate(cells):
		# 检查标题行
		titles_column	= {t:None for t in titles}
		for t in titles:
			result			= [j for j,n in enumerate(r) if str(n).strip() in titles[t]]
			if result:
				titles_column[t]	= result[0]
		if titles_column['TIME']	is not None and \
		   titles_column['BALANCE']	is not None and \
		   titles_column['INCOMING']	is not None :
			title_row	= i
			# titles在此时转换为该标题对应列数了
			titles		= {t:cells[title_row][titles_column[t]] if titles_column[t] is not None else None for t in titles}
			break
	
	if title_row==-1:
		# 未找到
		print(f"{filename} 没找到标题行")
		return None
	
	# 测试必须的数据是否存在
	def try_get_row_data(row):
		try:
			row_data	= {}
			# 尝试将余额转换为浮点数，需要去掉其中的千分号和空白字符
			balance_string		= str(row[titles_column['BALANCE']]).replace(',', '').replace(' ', '').strip()
			row_data['BALANCE']	= SpiritLong_utility.decimal2(balance_string)
			# 尝试日期转换为时间
			row_data['TIME']	= SpiritLong_utility.input_date(row[titles_column['TIME']].strip())['datetime']
			
			return row_data if row_data['TIME'] else None
		except:
			return None

	# 从后往前寻找：能正确获得日期和余额的，才是数据行。要考虑有可能数据行中间有空行。
	data_end_row	= -1
	for i in range(len(cells)-1, -1, -1):
		if try_get_row_data(cells[i]):
			# 如果以上都成功，则到达数据末尾了
			data_end_row	= i
			break
			
	if data_end_row	== -1:
		print(f"{filename} 没有找到数据结束的行")
		return None

	if title_row>=data_end_row:
		print(f"{filename} 标题行下没有数据")
		return []

	# 数据，跳过无效行
	data_cells	= cells[title_row+1:data_end_row+1]
	data	= []
	for j, row in enumerate(data_cells):
		row_data	= try_get_row_data(row)
		if row_data:
			# 此行可用
			# 尝试添加其他列
			for title in titles:
				# 这两项已经有了
				if title in ['BALANCE', 'TIME']:
					continue

				try:
					if title in ['INCOMING', 'OUTGOING']:
						# 金额
						row_data[title]	= SpiritLong_utility.decimal2(str(row[titles_column[title]]).replace(',', '').replace(' ', '').strip())
						if not row_data[title]:
							# 空则记录为0
							row_data[title]	= SpiritLong_utility.decimal2(0)
					else:
						# 字符串
						row_data[title]	= str(row[titles_column[title]]).strip()
				except:
					pass
			data.append(row_data)
		
	# 检查每行的时间
	for d in data:
		if not d['TIME']:
			# 时间日期有错误
			print(f'时间日期有错误:{d}')
			return None
		
	# 确保总是时间增长的顺序，注意确保原始数据中同一天的记录顺序，不能直接按时间排序
	if data[0]['TIME']>data[-1]['TIME']:
		# 时间逆序改为顺序
		data	= data[::-1]

	# 生成统一格式的交易记录
	# 交易记录
	records	= []
	for d in data:
		incoming	= d['INCOMING']
			
		if titles['OUTGOING'] is None:
			# 只有收支的情况，假定收为正
			incoming	= d['INCOMING']
			if incoming>0:
				outgoing	= 0
			else:
				outgoing	= -incoming
				incoming	= 0
		else:
			outgoing	= d['OUTGOING']
		
		if incoming<0:
			# 确保总是正数
			incoming	= -incoming
		if outgoing<0:
			# 确保总是正数
			outgoing	= -outgoing

		if titles['PAYER_NUMBER']	and \
		   titles['PAYER_NAME']		and \
		   titles['PAYEE_NUMBER']	and \
		   titles['PAYEE_NAME']:
			counterparty_number	= d['PAYER_NUMBER'] if incoming>0 else d['PAYEE_NUMBER']
			counterparty_name	= d['PAYER_NAME'] if incoming>0 else d['PAYEE_NAME']
		elif titles['PAYER_NUMBER']	and \
		     titles['PAYER_NAME']	and \
		     titles['PAYER_BANK']:
			counterparty_number	= d['PAYER_NUMBER'] if d['PAYER_NUMBER'] else ''
			counterparty_name	= d['PAYER_NAME']+d['PAYER_BANK'] if d['PAYER_NAME'] else ''
		else:
			counterparty_number	= ''
			counterparty_name	= ''
		
		remark	= d['REMARK']	if titles['REMARK'] else ''
		brief	= d['BRIEF']	if titles['BRIEF'] else ''
		usage	= d['USAGE']	if titles['USAGE'] else ''
		channel	= d['CHANNEL']	if titles['CHANNEL'] else ''

		# 确保是字符串而不会出现None
		counterparty_number	= counterparty_number if counterparty_number else ''
		counterparty_name	= counterparty_name if counterparty_name else ''
		remark			= remark if remark else ''
		brief			= brief if brief else ''
		usage			= usage if usage else ''
		channel			= channel if channel else ''

		# 描述是多个字段合并的
		description	= f"<{channel}>{counterparty_name}{counterparty_number} {brief}{remark}{usage}"
	
		records.append({
			'TIME'		: d['TIME'],
			'INCOMING'	: incoming,		
			'OUTGOING'	: outgoing,		
			'BALANCE'	: d['BALANCE'],
			'DESCRIPTION'	: description,
		})
	return records


## 从个人所得税中导入记录

## 从银行代发导入记录

## 从社保记录导入数据

## 薪酬日志处理

## 发票导入

## 财务类
class accounting:
	## 初始化
	#	db		数据库
	#	SVN_path	SVN:SPIRITLONG所在路径
	def __init__(self, db, SVN_path):
		pass


if __name__ == '__main__':

	db	= SQLiteDatabase('SpiritLong_accounting/accounting.db')
	schema_filename	= "SpiritLong_accounting/SQLITE数据库结构accounting.xlsx"

	db.import_excel_schema(schema_filename)

	# path		= r'C:\Users\yangs\Documents\SVN\SPIRITLONG\财务\数据\2023\原始数据\账户对账\重庆灵悠科技有限公司'
	# filename	= os.path.join(path, 'ICC4602 对账记录 2023-09-01_2023-09-30.xlsx')
	# records		= get_balance_from_xlsx(filename)
	# for r in records:
	# 	print(r)
	