# -*- encoding: utf8 -*-
from __future__ import unicode_literals
from sqlalchemy import create_engine
import pandas as pd

mysql_engine = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/test_mzh?charset=utf8', echo=0)


def bt_loan_check():
    sql_version = """SELECT * FROM test_mzh.bt_loan_version"""
    sql_details = """
    SELECT
      sum(contract_loan_amount) contract_loan_amount,
      sum(real_loan_amount)     real_loan_amount
    FROM (
       SELECT
         contract_loan_amount,
         real_loan_amount
       FROM %s.baitiao_order bo
              WHERE YEAR(loan_paid_at) = %d AND MONTH(loan_paid_at) = %d 
              AND is_active = 1 AND funding_corp_id = %d AND baitiao_type = %d
       UNION ALL 
       SELECT
           contract_loan_amount,
           real_loan_amount
       FROM %s.baitiao_order bo
       WHERE YEAR(train_cancel_at) = %d AND MONTH(train_cancel_at) = %d 
       AND is_active = -2 AND funding_corp_id = %d AND baitiao_type = %d) t
    """
    sql_details_xiaolian = """
    SELECT
      SUM(bo.contract_loan_amount),
      SUM(bo.funding_loan_amount)
    FROM %s.baitiao_order bo
      JOIN %s.baitiao_finance_record bfr
        ON bfr.batch_no = bo.batch_no_id AND bo.funding_corp_id = %d AND bo.is_active = 1
           AND YEAR(bfr.trans_date) = %d AND MONTH(bfr.trans_date) = %d;
    """
    err_msg = '白条放款：year = %d, month = %d, version = %s, %s 校验不一致: %.4f(%s), %.4f(version)'
    col_names = ['contract_loan_amount', 'real_loan_amount']
    df_version = pd.read_sql(sql=sql_version, con=mysql_engine)
    for ix, row in df_version.iterrows():
        version = row['version']
        funding_corp = row['funding_code']
        business_type = row['business_type']
        year = row['year']
        month = row['month']
        # 区分白条业务，现金支付 or 白条支付，区分资金方
        if funding_corp == 5:
            # 笑脸直投
            sql = sql_details_xiaolian % (version, version, funding_corp, year, month)
        else:
            sql = sql_details % ((version, year, month, funding_corp, business_type) * 2)
        try:
            res = mysql_engine.execute(sql).fetchone()
            for i in range(0, len(col_names)):
                col_name = col_names[i]
            if abs(round(float(res[i]) - row[col_name])) > 0.01:
                print err_msg % (year, month, version, col_name, res[i], version, row[col_name])
        except Exception, e:
            raise ValueError('白条放款：查询数据库出错，数据库异常！\n' + str(e))
    print '白条放款金额检查完毕！'


def bt_repay_check():
    sql_version = """SELECT * FROM test_mzh.bt_repay_version"""
    sql_details_bt = """
    SELECT
      sum(repay_amount),
      sum(prin),
      sum(inst),
      sum(fee),
      sum(punish),
      sum(remain)
    FROM (
           SELECT
             brprrr.ref_amount                                 repay_amount,
             brprrr.principle - brprrr.mitigate_principle      prin,
             brprrr.interest - brprrr.mitigate_interest        inst,
             brprrr.service_fee - brprrr.mitigate_service_fee  fee,
             brprrr.punish - brprrr.mitigate_collection_relief punish,
             brprrr.remain_income                              remain
           FROM %s.baitiao_repay_plan_repay_record_ref brprrr
             JOIN test_mzh.repay_record_amount rr
               ON rr.record_id = brprrr.record_id AND rr.repay_channel = brprrr.repay_channel AND
                  YEAR(rr.repaid_at) = %d AND MONTH(rr.repaid_at) = %d
             JOIN %s.user_bt_repayment_plan ubrp ON ubrp.id = brprrr.plan_id
             JOIN %s.baitiao_order bo
               ON bo.ref_id = ubrp.ref_id AND bo.funding_corp_id = %d AND bo.baitiao_type = %d
           UNION ALL
           SELECT
             bcrr.ref_amount repay_amount,
             bcrr.ref_amount prin,
             0               inst,
             0               fee,
             0               punish,
             0               remain
           FROM %s.baitiao_cash_record_ref bcrr
             JOIN %s.baitiao_cash_repay bcr ON bcrr.repay_id = bcr.id
             JOIN test_mzh.repay_record_amount rra ON rra.record_id = bcrr.record_id AND bcrr.repay_channel = rra.repay_channel 
              AND bcrr.repay_channel = 13 AND YEAR(rra.repaid_at) = %d AND MONTH(rra.repaid_at) = %d
         ) t;
    """
    sql_details_cash = """
    SELECT
      sum(bcrr.ref_amount) repay_amount,
      sum(bcrr.ref_amount) prin,
      0                    inst,
      0                    fee,
      0                    punish,
      0                    remain
    FROM %s.baitiao_cash_record_ref bcrr
      JOIN %s.baitiao_cash_repay bcr ON bcrr.repay_id = bcr.id
      JOIN test_mzh.repay_record_amount rra ON bcrr.repay_channel <> 13 AND rra.record_id = bcrr.record_id
                                               AND YEAR(rra.repaid_at) = %d AND MONTH(rra.repaid_at) = %d;
    """
    sql_details_xiaolian = """
    SELECT
      sum(brprrr.ref_amount),
      sum(brprrr.principle - brprrr.mitigate_principle),
      sum(brprrr.interest - brprrr.mitigate_interest),
      sum(brprrr.service_fee - brprrr.mitigate_service_fee),
      sum(brprrr.punish - brprrr.mitigate_collection_relief),
      sum(brprrr.remain_income)
    FROM %s.baitiao_repay_plan_repay_record_ref brprrr
      JOIN test_mzh.repay_record_amount rr
        ON rr.record_id = brprrr.record_id AND rr.repay_channel = brprrr.repay_channel
           AND YEAR(rr.repaid_at) = %d AND MONTH(rr.repaid_at) = %d
      JOIN %s.user_bt_repayment_plan ubrp ON ubrp.id = brprrr.plan_id
      JOIN %s.baitiao_order bo ON bo.ref_id = ubrp.ref_id AND bo.funding_corp_id = %d;
    """
    err_msg = '白条还款：year = %d, month = %d, version = %s, %s 校验不一致: %.4f(%s), %.4f(version)'
    col_names = ['repay_amount', 'principle', 'interest', 'service_fee', 'punish_fee', 'remain']
    df_version = pd.read_sql(sql=sql_version, con=mysql_engine)
    for ix, row in df_version.iterrows():
        version = row['version']
        funding_corp = row['funding_code']
        business_type = row['business_type']
        year = row['year']
        month = row['month']
        # 区分白条业务，现金支付 or 白条支付，区分资金方
        if funding_corp == 5:
            # 笑脸直投
            sql = sql_details_xiaolian % (version, year, month, version, version, funding_corp)
        elif business_type == 0:
            sql = sql_details_bt % (
                version, year, month, version, version, funding_corp, business_type, version, version, year, month)
        else:
            sql = sql_details_cash % (version, version, year, month)
        try:
            res = mysql_engine.execute(sql).fetchone()
            for i in range(0, len(col_names)):
                col_name = col_names[i]
                if abs(round(float(res[i]) - row[col_name])) > 0.01:
                    print err_msg % (year, month, version, col_name, res[i], version, row[col_name])
        except Exception, e:
            raise ValueError('白条还款：查询数据库出错，数据库异常！\n' + str(e))
    print '白条还款金额检查完毕！'


def cash_loan_check():
    sql_version = """SELECT * FROM test_mzh.cash_loan_with_fund_version"""
    sql_details = """
    SELECT
      sum(lm.contract_loan_amount),
      sum(lm.real_loan_amount),
      sum(lm.qg_one_time_service_fee),
      sum(lm.funding_one_time_service_fee)
    FROM %s.loan_manifest lm
    WHERE
      lm.is_active IN (1, -2) AND YEAR(lm.loan_paid_at) = %d AND MONTH(lm.loan_paid_at) = %d
      AND lm.funding_code = %d AND lm.loan_account_id = %d;
    """
    err_msg = "现金贷放款：year = %d, month = %d, funding_code = %d, loan_account = %d, version = %s, %s 校验不一致: %.4f(%s), %.4f(version)"
    col_names = ['contract_loan_amount', 'real_loan_amount', 'qg_one_time_service_fee', 'funding_one_time_service_fee']
    df_version = pd.read_sql(sql=sql_version, con=mysql_engine)
    for ix, row in df_version.iterrows():
        year = row['year']
        month = row['month']
        loan_account = row['loan_account']
        funding_code = row['funding_code']
        version = row['version']
        try:
            res = mysql_engine.execute(sql_details % (version, year, month, funding_code, loan_account)).fetchone()
            for i in range(0, len(col_names)):
                col_name = col_names[i]
                if abs(round(float(res[i]) - row[col_name])) > 0.01:
                    print err_msg % (
                        year, month, funding_code, loan_account, version, col_name, res[i], version, row[col_name])
        except Exception, e:
            raise ValueError('现金贷放款：查询数据库出错，数据库异常！\n' + str(e))
    print '现金贷放款金额检查完毕！'


def cash_repay_check():
    sql_version = """SELECT * FROM test_mzh.cash_repay_with_fund_version"""
    sql_details = """
    SELECT
      sum(xrprrr.ref_amount),
      sum(xrprrr.principle - xrprrr.mitigate_principle),
      sum(xrprrr.interest - xrprrr.mitigate_interest),
      sum(xrprrr.service_fee - xrprrr.mitigate_service_fee),
      sum(xrprrr.punish - xrprrr.mitigate_collection_relief),
      sum(xrprrr.remain_income)
    FROM %s.xjd_repay_plan_repay_record_ref xrprrr
      JOIN test_mzh.repay_record_amount rra
        ON rra.record_id = xrprrr.record_id AND rra.repay_channel = xrprrr.repay_channel
           AND xrprrr.repay_channel = %d AND YEAR(rra.repaid_at) = %d AND MONTH(rra.repaid_at) = %d
      JOIN %s.user_repayment_plan urp ON urp.id = xrprrr.plan_id AND urp.fund_code = %d;
    """
    err_msg = "现金贷还款：year = %d, month = %d, funding_code = %d, repay_channel = %d, version = %s, %s 校验不一致: %.4f(%s), %.4f(version)"
    col_names = ['repay_amount', 'principle', 'interest', 'service_fee', 'punish_fee', 'remain']
    df_version = pd.read_sql(sql=sql_version, con=mysql_engine)
    df_version['repay_amount'] = df_version['repay_amount'] - df_version['dunshou_service_fee']
    # df_version = df_version.loc[(df_version.year == 2017) & (df_version.month >= 4)]
    for ix, row in df_version.iterrows():
        year = row['year']
        month = row['month']
        repay_channel = row['repay_channel']
        funding_code = row['funding_code']
        version = row['version']
        # print year, month, repay_channel, funding_code
        try:
            res = mysql_engine.execute(
                sql_details % (version, repay_channel, year, month, version, funding_code)).fetchone()
            for i in range(0, len(col_names)):
                col_name = col_names[i]
                if abs(round(float(res[i]) - row[col_name])) > 0.01:
                    print err_msg % (
                        year, month, funding_code, repay_channel, version, col_name, res[i], version, row[col_name])
        except Exception, e:
            raise ValueError('现金贷还款：查询数据库出错，数据库异常！\n' + str(e))
    if abs(round(df_version['dunshou_service_fee'].sum() - 28830, 2)) > 0.01:
        print '趸收服务费有问题', df_version['dunshou_service_fee'].sum()
    print '现金贷还款金额检查完毕！'


def qunaer_loan_check():
    sql_version = """SELECT * FROM test_mzh.qunaer_loan_version"""
    sql_baoli = """
    SELECT sum(loan_amount)
    FROM (
           SELECT loan_amount
           FROM %s.pay_detail
           WHERE fund_code = %d AND STATUS = 1 AND YEAR(trans_time) = %d AND MONTH(trans_time) = %d and is_ptf = 0
           UNION ALL
           SELECT t1.refund_principle loan_amount
           FROM %s.refund_detail t1
             JOIN %s.pay_detail t2
               ON t1.product_no = t2.product_no AND t1.fund_code = t2.fund_code AND t1.fund_code = %d AND
                  YEAR(refund_time) = %d AND MONTH(refund_time) = %d and t1.flow_id IS NULL) t;
    """
    sql_fund = """
    SELECT
      sum(loan_amount)
    FROM %s.fund_pay_detail
    WHERE STATUS = 1 AND fund_code = %d AND YEAR(trans_time) = %d AND MONTH(trans_time) = %d;
    """
    sql_zhaizhuan = """
    SELECT
      sum(loan_amount)
    FROM %s.baoli_pay_detail WHERE fund_code = %d AND YEAR(trans_time) = %d AND MONTH(trans_time) = %d;
    """
    err_msg = '去哪儿放款：year = %d, month = %d, version = %s, %s 校验不一致: %.4f(%s), %.4f(version)'
    col_names = ['loan_amount']
    df_version = pd.read_sql(sql=sql_version, con=mysql_engine)
    for ix, row in df_version.iterrows():
        version = row['version']
        funding_corp = row['funding_code']
        year = row['year']
        month = row['month']
        zhaizhuan = row['zhaizhuan']
        if zhaizhuan == 0:
            if funding_corp == 1:
                sql = sql_baoli % (version, funding_corp, year, month, version, version, funding_corp, year, month)
            else:
                sql = sql_fund % (version, funding_corp, year, month)
        else:
            sql = sql_zhaizhuan % (version, funding_corp, year, month)
        try:
            res = mysql_engine.execute(sql).fetchone()
            for i in range(0, len(col_names)):
                col_name = col_names[i]
            if abs(round(float(res[i]) - row[col_name])) > 0.01:
                print err_msg % (year, month, version, col_name, res[i], version, row[col_name])
        except Exception, e:
            raise ValueError('去哪儿放款：查询数据库出错，数据库异常！\n' + str(e))
    print '去哪儿放款金额检查完毕！'


def qunaer_repay_check():
    sql_version = """SELECT * FROM test_mzh.qunaer_repay_version"""
    sql_baoli_repay = """
    SELECT sum(repay_amount), sum(repay_principle), sum(repay_fee_amount), sum(repay_due_amount), sum(remain)
    FROM (
           SELECT 
             repay_amount,
             repay_principle,
             repay_fee_amount,
             repay_due_amount,
             remain
           FROM %s.repay_detail t1
             JOIN %s.pay_detail t2
               ON t1.product_no = t2.product_no AND t1.fund_code = t2.fund_code AND t1.fund_code = %d and t1.repay_status = 1
                  AND year(t1.repay_time) = %d AND month(t1.repay_time) = %d
           UNION ALL
           SELECT 
             -refund_amount     repay_amount,
             -refund_principle  repay_principle,
             -refund_fee_amount repay_fee_amount,
             -refund_due_amount repay_due_amount,
             0                  remain
           FROM %s.refund_detail t1
             JOIN %s.pay_detail t2
               ON t1.product_no = t2.product_no AND t1.fund_code = t2.fund_code AND t1.fund_code = %d
                  AND year(t1.refund_time) = %d AND month(t1.refund_time) = %d
                  AND t1.flow_id IS NOT NULL
           union all
           SELECT 
             repay_amount,
             repay_principle,
             repay_fee_amount,
             repay_due_amount,
             remain
           FROM %s.repay_detail t1
             JOIN %s.baoli_pay_detail t2
               ON t1.product_no = t2.product_no AND t1.fund_code = t2.fund_code AND t1.fund_code = %d AND t2.status = 1 and t1.repay_status = 1
               and year(t1.repay_time) = %d and month(t1.repay_time) = %d
           union all
           SELECT 
             -refund_amount     repay_amount,
             -refund_principle  repay_principle,
             -refund_fee_amount repay_fee_amount,
             -refund_due_amount repay_due_amount,
             0                  remain
           FROM %s.refund_detail t1
             JOIN %s.baoli_pay_detail t2
               ON t1.product_no = t2.product_no AND t1.fund_code = t2.fund_code AND t1.fund_code = %d AND t2.status = 1 
                  AND year(t1.refund_time) = %d AND month(t1.refund_time) = %d
         ) t;
    """
    sql_fund_repay = """
    SELECT sum(repay_amount), sum(repay_principle), sum(repay_fee_amount), sum(repay_due_amount), sum(remain)
    FROM (
           SELECT 
             repay_amount,
             repay_principle,
             repay_fee_amount,
             repay_due_amount,
             remain
           FROM %s.repay_detail t1
             JOIN %s.fund_pay_detail t2
               ON t1.product_no = t2.product_no AND t1.fund_code = t2.fund_code AND t2.status = 1 AND t1.fund_code = %d
                  AND year(t1.repay_time) = %d AND month(t1.repay_time) = %d
           UNION ALL
           SELECT 
             -refund_amount     repay_amount,
             -refund_principle  repay_principle,
             -refund_fee_amount repay_fee_amount,
             -refund_due_amount repay_due_amount,
             0                  remain
           FROM %s.refund_detail t1
             JOIN %s.fund_pay_detail t2
               ON t1.product_no = t2.product_no AND t1.fund_code = t2.fund_code AND t2.status = 1 AND t1.fund_code = %d
                  AND year(t1.refund_time) = %d AND month(t1.refund_time) = %d
         ) t 
    """
    err_msg = '去哪儿还款：year = %d, month = %d, version = %s, %s 校验不一致: %.4f(%s), %.4f(version)'
    col_names = ['repay_amount', 'principle', 'service_fee', 'punish_fee', 'remain']
    df_version = pd.read_sql(sql=sql_version, con=mysql_engine)
    for ix, row in df_version.iterrows():
        version = row['version']
        funding_corp = row['funding_code']
        year = row['year']
        month = row['month']
        if funding_corp == 1:
            sql = sql_baoli_repay % ((version, version, funding_corp, year, month) * 4)
        else:
            sql = sql_fund_repay % ((version, version, funding_corp, year, month) * 2)
        try:
            res = mysql_engine.execute(sql).fetchone()
            for i in range(0, len(col_names)):
                col_name = col_names[i]
                if abs(round(float(res[i]) - row[col_name])) > 0.01:
                    print err_msg % (year, month, version, col_name, res[i], version, row[col_name])
        except Exception, e:
            raise ValueError('去哪儿还款：查询数据库出错，数据库异常！\n' + str(e))
    print '去哪儿还款金额检查完毕！'

if __name__ == '__main__':
    bt_loan_check()
    bt_repay_check()
    cash_loan_check()
    cash_repay_check()
    qunaer_loan_check()
    qunaer_repay_check()

