# -*- encoding: utf8 -*-
from __future__ import unicode_literals
import pandas as pd
from sqlalchemy import create_engine
import sys
reload(sys)
sys.setdefaultencoding('utf8')

engine_audit = create_engine('mysql+mysqldb://yulong_rw:TouBStYwN8wkdxVt@172.16.3.201:3306/all_back_0430?charset=utf8', echo=True)


df_fund_corp = pd.read_sql(sql="select funding_code, name '资金方' from audit.funding_corp", con=engine_audit)
df_loan_account = pd.read_sql(sql="select id loan_account_id, accountName '放款账户' from audit.loan_account", con=engine_audit)
df_repay_channel = pd.read_sql(sql="select id repay_channel_id, approach_name '收款账户' from new_transaction.repay_channel", con=engine_audit)

excel_file = pd.ExcelWriter('放款数据汇总核对表.xlsx')
################################################
# 放款表汇总
sql = """
select year(t1.loan_paid_at) '年', month(t1.loan_paid_at) '月', funding_code , loan_account_id , sum(t1.real_loan_amount) '放款金额', sum(t1.contract_loan_amount) '本金债权',
sum(t1.qg_one_time_service_fee) '一次性扣除手续费QG', sum(t1.funding_one_time_service_fee) ' 一次性扣除手续费点滴' from loan_manifest t1  where t1.is_active in (1,-2)
group by 1,2,3,4;
"""
df = pd.read_sql(sql=sql, con=engine_audit)
df['funding_code'] = df['funding_code'].astype(int)
df['loan_account_id'] = df['loan_account_id'].astype(int)
df = df.merge(df_fund_corp, on='funding_code', how='left').merge(df_loan_account, on='loan_account_id', how='left')
df.drop(['funding_code', 'loan_account_id'], axis=1, inplace=True)
# df.to_excel(u'放款表汇总.xlsx', index=None)
df.to_excel(excel_file, '放款表汇总', columns=['年', '月', '资金方', '放款账户', '放款金额', '本金债权', '一次性扣除手续费QG', '一次性扣除手续费点滴'], index=None)

################################################
# 债转汇总
# sql = """
# select year(debt_time) 年, month(debt_time) 月,src_funding_code, dest_funding_code, sum(money_value) 债转金额  from funding_debet_transfer where debt_time is not null group by 1,2,3,4;
# """
# df = pd.read_sql(sql=sql, con=engine_audit)
# df['src_funding_code'] = df['src_funding_code'].astype(int)
# df['dest_funding_code'] = df['dest_funding_code'].astype(int)
# df = df.merge(df_fund_corp, left_on='src_funding_code', right_on='funding_code', how='left')
# df.rename(columns={'资金方': '原资金方'}, inplace=True)
# df.drop(['src_funding_code', 'funding_code'], axis=1, inplace=True)
# df = df.merge(df_fund_corp, left_on='dest_funding_code', right_on='funding_code', how='left')
# df.rename(columns={'资金方': '债转资金方'}, inplace=True)
# df.drop(['dest_funding_code', 'funding_code'], axis=1, inplace=True)
# df.to_excel(excel_file, '债转表汇总', columns=['年', '月', '原资金方', '债转资金方', '债转金额'], index=None)

################################################
# 收客户还款汇总
# 需要修改，用ref表关联user_repayment_plan ,再关联还款记录表
#
# sql_alipay = """select year(t3.transfer_time) 年, month(t3.transfer_time) 月, t4.funding_code funding_code, '支付宝' 收款账户, sum(t1.ref_amount) 总额, sum(t1.principle) 本金, sum(t1.interest) 利息, sum(t1.service_fee) 服务费,
# sum(t1.collection_relief) 红包减免金额, sum(t1.punish) 逾期罚款收益, sum(t1.remain_income) 其他收益, sum(mitigate_principle) 减免本金, sum(mitigate_interest) 减免利息, sum(mitigate_service_fee) 减免服务费, sum(mitigate_collection_relief) 减免罚息
#  from new_transaction.xjd_repay_plan_repay_record_ref t1
# join new_transaction.user_repayment_plan t2 on t2.id = t1.plan_id
# inner join (select distinct funding_code,ref_id from  audit.loan_manifest ) t4 on t4.ref_id = t2.ref_id
# join new_transaction.offline_alipay_record t3 on t1.repay_channel =13 and t3.id = t1.record_id where t4.funding_code = '210' group by 1,2,3,4"""
# df_alipay = pd.read_sql(sql=sql_alipay, con=engine_audit)
# df_alipay['funding_code'] = df_alipay['funding_code'].astype(int)
# df_alipay = df_alipay.merge(df_fund_corp, on='funding_code', how='left')
# df_alipay.drop(['funding_code'], axis=1, inplace=True)
#
# sql_bank = """select year(t3.transfer_time) 年, month(t3.transfer_time) 月, t4.funding_code funding_code, t1.repay_channel, sum(t1.ref_amount) 总额, sum(t1.principle) 本金, sum(t1.interest) 利息, sum(t1.service_fee) 服务费,
# sum(t1.collection_relief) 红包减免金额, sum(t1.punish) 逾期罚款收益, sum(t1.remain_income) 其他收益, sum(mitigate_principle) 减免本金, sum(mitigate_interest) 减免利息, sum(mitigate_service_fee) 减免服务费, sum(mitigate_collection_relief) 减免罚息
#  from new_transaction.xjd_repay_plan_repay_record_ref t1
# join new_transaction.user_repayment_plan t2 on t2.id = t1.plan_id
# inner join (select distinct funding_code,ref_id from  audit.loan_manifest ) t4 on t4.ref_id = t2.ref_id
# join new_transaction.offline_bank_repay_record t3 on t1.repay_channel in (14,15,16) and t3.id = t1.record_id where t4.funding_code = '210' group by 1,2,3,4"""
# df_bank = pd.read_sql(sql=sql_bank, con=engine_audit)
# df_bank['funding_code'] = df_bank['funding_code'].astype(int)
# df_bank['repay_channel'] = df_bank['repay_channel'].astype(int)
# df_bank = df_bank.merge(df_fund_corp, on='funding_code', how='left').merge(df_repay_channel, left_on='repay_channel', right_on='repay_channel_id', how='left')
# df_bank.drop(['funding_code', 'repay_channel', 'repay_channel_id'], axis=1, inplace=True)
#
# sql_online = """select year(t3.bill_time) 年, month(t3.bill_time) 月, t4.funding_code  funding_code, t1.repay_channel, sum(t1.ref_amount) 总额, sum(t1.principle) 本金, sum(t1.interest) 利息, sum(t1.service_fee) 服务费,
# sum(t1.collection_relief) 红包减免金额, sum(t1.punish) 逾期罚款收益, sum(t1.remain_income) 其他收益, sum(mitigate_principle) 减免本金, sum(mitigate_interest) 减免利息, sum(mitigate_service_fee) 减免服务费, sum(mitigate_collection_relief) 减免罚息
# from new_transaction.xjd_repay_plan_repay_record_ref t1
# join new_transaction.user_repayment_plan t2 on t2.id = t1.plan_id
# inner join (select distinct funding_code,ref_id from  audit.loan_manifest ) t4 on t4.ref_id = t2.ref_id
# join new_transaction.repay_record_online t3 on t1.repay_channel in (1,2,3,4,5,6,7,8,9,10,11,12,17) and t3.id = t1.record_id where t4.funding_code = '210' group by 1,2,3,4"""
# df_online = pd.read_sql(sql=sql_online, con=engine_audit)
# df_online['funding_code'] = df_online['funding_code'].astype(int)
# df_online['repay_channel'] = df_online['repay_channel'].astype(int)
# df_online = df_online.merge(df_fund_corp, on='funding_code', how='left').merge(df_repay_channel, left_on='repay_channel', right_on='repay_channel_id', how='left')
# df_online.drop(['funding_code', 'repay_channel', 'repay_channel_id'], axis=1, inplace=True)
#
# df = pd.concat([df_alipay, df_bank, df_online], ignore_index=True)
# df.sort_values(['年', '月', '资金方', '收款账户'], inplace=True)
# df.to_excel(excel_file, '收客户还款汇总', columns=['年', '月', '资金方', '收款账户', '总额', '本金', '利息', '服务费', '红包减免金额', '逾期罚款收益', '其他收益', '减免本金', '减免利息', '减免服务费', '减免罚息'], index=None)

################################################
# 还资金方汇总
# sql = """select year(repaid_at) 年, month(repaid_at) 月, funding_code, t2.bank 还款账户, sum(principle) 当期本金,
# sum(interest) 当期利息, sum(prepay_fee) 提前还款服务费, sum(t1.funding_service_fee) 资金方服务费（点滴）, sum(punish_fee) 逾期罚息
#  from funding_repayment_record t1 join lkb_to_fund t2 on t2.id = t1.lkb2fund_id where repaid_at is not null group by 1,2,3,4;"""
# df = pd.read_sql(sql=sql, con=engine_audit)
# # 补充马上金融的（马上金融没有关联lkb2fund，现在已经补充完全，不需要这一部分了）
# # sql = """select year(repaid_at) 年, month(repaid_at) 月, funding_code, '平安银行' 还款账户, sum(principle) 当期本金,
# # sum(interest) 当期利息, sum(prepay_fee) 提前还款服务费 from funding_repayment_record t1
# #  where funding_code = '29' and repaid_at is not null and lkb2fund_id is null group by 1,2,3,4;"""
# # df = df.append(pd.read_sql(sql=sql, con=engine_audit))
# df['funding_code'] = df['funding_code'].astype(int)
# df = df.merge(df_fund_corp, on='funding_code', how='left')
# df.drop(['funding_code'], axis=1, inplace=True)
# df['当期本息和'] = df['当期本金'] + df['当期利息'] + df['提前还款服务费']
# df.ix[df['资金方'].isin(['北京点滴', '云南点滴']), '当期本息和'] = df.ix[df['资金方'].isin(['北京点滴', '云南点滴']), '当期本金'] + df.ix[df['资金方'].isin(['北京点滴', '云南点滴']), '当期利息'] + df.ix[df['资金方'].isin(['北京点滴', '云南点滴']), '资金方服务费（点滴）'] + df.ix[df['资金方'].isin(['北京点滴', '云南点滴']), '逾期罚息']
# df.ix[df['资金方'] == '马上金融', '当期本息和'] = df.ix[df['资金方'] == '马上金融', '当期本金'] + df.ix[df['资金方'] == '马上金融', '当期利息'] + df.ix[df['资金方'] == '马上金融', '逾期罚息']
# df.fillna(0, inplace=True)
# df.to_excel(excel_file, u'还资金方表汇总', columns=['年', '月', '资金方', '还款账户', '当期本息和', '当期本金', '当期利息', '提前还款服务费', '资金方服务费（点滴）', '逾期罚息'], index=None)
#
#
excel_file.save()