# encoding: utf8

import pandas as pd
from sqlalchemy import create_engine

engine_audit = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/audit?charset=utf8',
                             echo=True)
# TODO 代码需要作者检查

"""


A
给资金方流水 按 时间排序
  一笔id, 转账时间, fund_cop,   银行, 实还,   应还 , 流水差额;
  一笔id2, 转账时间2,  银行, 实还2,     应还2 , 流水差额 ;
每笔加上 fund_cop_name

B
用户该还, 按照 天,资金方  来汇总和排序
    天, 资金方, 总钱.


按照时间归并AB, 按照时间选出a,b
    a,
         a.transfer_time
         a.bank
         a.fund_cop
         a.amount
         此时该还的拿到 清0
         算差异
     b,
         资金方欠款总钱+进去
"""

sqla = """
SELECT
  date_format(transfer_time, '%%y-%%m-%%d') transfer_date,
  altf.fund_corp,
  altf.bank,
  (CASE
   WHEN (fc.funding_code IS NULL)
     THEN (
       CASE
       WHEN (fund_corp = '洋钱罐（直投）') THEN 140
       WHEN (fund_corp = '洋钱罐（债转）') THEN 141
       WHEN (fund_corp = '夸客') THEN 100
       WHEN (fund_corp = '橘子理财') THEN 250
       WHEN (fund_corp IN ('李然', '张初阳', '姚晓蕾')) THEN -1 # 这里有问题的 !!!!
       ELSE -2 END
     )
   ELSE fc.funding_code
   END) funding_code,
  transfer_amount                   pay_amount,
  0.0 need_pay,
  0.0 trans_diff

FROM audit.lkb_to_fund altf
  LEFT JOIN audit.funding_corp fc ON altf.fund_corp = fc.name
ORDER BY transfer_date, funding_code;

"""

sqlb = """
#funding_repayment_record 用户还给资金方的钱  每日汇总  user_fund_daily
SELECT
  (CASE
   WHEN (date_format(repaid_at, '%H%i%S') = '000000')
     THEN date_format(DATE_SUB(repaid_at, INTERVAL 1 SECOND), '%y-%m-%d')
   ELSE date_format(repaid_at, '%y-%m-%d') END) repaid_date,
  afrr.funding_code,
  (sum(principle) +
   sum(interest) +
   sum(prepay_fee) +
   sum(IFNULL(funding_service_fee, 0)) +
   sum(IFNULL(punish_fee, 0)) +
   sum(IFNULL(AIR, 0))
  ) AS                                          need_pay
FROM audit.funding_repayment_record afrr
WHERE repaid_at IS NOT NULL
GROUP BY repaid_date, funding_code
ORDER BY repaid_date, funding_code;
"""

# a = engine_financial.execute(sql, params=('%Y-%m',)).fetchall()
# df = pd.DataFrame(values=a, columns=[u'类别', u'放款年', u'放款月', u'应还年', u'应还月', u'应收本金', u'应收利息'])

need_pay_dict = {}
Adf = pd.read_sql(sql=sqla, con=engine_audit)
Bdf = pd.read_sql(sql=sqlb, con=engine_audit)
bi = 0
blen = len(Bdf)

for ai, a in Adf.iterrows():
    while bi < blen and Bdf.iloc[bi]['repaid_date'] < a['transfer_date']:
        b = Bdf.iloc[bi]
        need_pay_dict[b['funding_code']] = need_pay_dict.get(b['funding_code'], 0.0) + b['need_pay']
        bi += 1

    need_pay = need_pay_dict.setdefault(a['funding_code'], 0.0)
    a['need_pay'] = need_pay
    a['diff'] = a['pay_amount'] - need_pay

path_out = u'~/Desktop/'
Adf.to_excel(path_out + u'现金贷应收本金利息汇总', index=None)
