# encoding: utf8
from __future__ import unicode_literals

import pandas as pd
from sqlalchemy import create_engine

pd.options.mode.chained_assignment = None
import sys

reload(sys)
sys.setdefaultencoding('utf8')
engine_xyqb = create_engine('mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/xyqb?charset=utf8',
                            echo=True)
engine_audit = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/audit?charset=utf8', echo=True)
# engine_audit = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/all_back_0601?charset=utf8', echo=True)

funding_detail_sql = """ SELECT
	fc.`name` 资金方,
	frr.loan_id 产品编号,
	ui.name 借款人姓名,
	ui.id_no 借款人身份证号,
	flm.loan_paid_at 放款日期,
	la.accountName 放款账户,
	flm.lending_amount 放款金额,
	lm.real_loan_amount 本金,
	flm.term 贷款总期数,
	frr.term_no,
	frr.deadline 应还资金方日期,
	frr.repaid_at 实还资金方日期,
	frr.principle 实际支付本金,
	frr.interest 实际支付利息,
	frr.AIR 利率,
	lm.contract_term,
	lm.monthly_interest_rate,
	lm.contract_loan_amount,
	frr.funding_code

FROM
	funding_repayment_record frr
LEFT JOIN funding_loan_manifest flm ON flm.loan_id = frr.loan_id
LEFT JOIN funding_corp fc ON frr.funding_code = fc.funding_code
LEFT JOIN loan_manifest lm ON lm.ref_id =flm.ref_id
LEFT JOIN user_info ui  ON lm.user_biz_id = ui.user_biz_id
LEFT JOIN loan_account la ON la.id = lm.loan_account_id WHERE frr.funding_code= %s AND year(flm.loan_paid_at)=%s AND MONTH(flm.loan_paid_at)=%s  ORDER BY flm.loan_paid_at  """
funding_code = 150
columns_detail = ['资金方', '产品编号', '借款人姓名', '借款人身份证号', '放款日期', '放款账户', '放款金额', '本金', '兜底利息', '贷款总期数', '应还款期数',
                  '应还资金方日期', '应还款本金', '应还款利息', '实还资金方日期', '实际支付本金', '实际支付利息', '利率']
columns = ['打款年份', '打款月份', '打款账户', '资金方', '当期本息和', '当期本金', '当期利息', '提前还款服务费']



def repay_funding_excel_new():
    # 原脚本中存在广源小贷，2015年10的马上金融以及2017年01和02科易小贷的remark有一部分不为null,所以需要将该sql取出后去掉部分t1.remark限制条件然后单独处理，
    # 湖北消金含有“已代偿且分账成功”，需加上限制等问题
    # 但是新脚本中已经修正
    sql = """SELECT
            YEAR (t1.repaid_at) 打款年份,
                MONTH (t1.repaid_at) 打款月份,
                fc.`name` 资金方,
            sum(
                    IFNULL(t1.current_repayment, 0)
                ) 当期总额,
                sum(IFNULL(t1.principle, 0)) 当期本金,
                sum(IFNULL(t1.interest, 0)) 当期利息,
                sum(IFNULL(t1.prepay_fee, 0)) 提前还款服务费,
                sum(
                    IFNULL(t1.funding_service_fee, 0)
                ) 资金方服务费,
                sum(IFNULL(t1.punish_fee, 0)) 逾期罚息
            
            FROM
                audit.funding_repayment_record t1
             JOIN basic.funding_corp fc ON t1.funding_code = fc.funding_code
            WHERE
                t1.repaid_at IS NOT NULL
            AND t1.funding_code not IN (290,330)
             AND t1.repaid_at>='2015-01-01'
            GROUP BY
                1,2,3"""
    # sql_diandi = """
     #      SELECT
     #        YEAR (plan.deadline) 打款年份,
     #        MONTH (plan.deadline) 打款月份,
     #        fc.`name` 资金方,
     #        sum(
     #            IFNULL(plan.required_repayment, 0)
     #        ) 当期总额,
     #        sum(IFNULL(plan.principle, 0)) 当期本金,
     #        sum(IFNULL(plan.interest, 0)) 当期利息,
     #        0 提前还款服务费,
     #        sum(IFNULL(plan.service_fee, 0)) 资金方服务费,
     #        0 逾期罚息
     #    FROM
     #        audit.funding_repayment_record t1
     #    LEFT JOIN new_transaction.user_repayment_plan plan ON plan.real_loan_id = t1.loan_id
     #    AND t1.term_no = plan.term_no
     #    LEFT JOIN audit.funding_corp fc ON t1.funding_code = fc.funding_code
     #    WHERE
     #        t1.funding_code IN (3, 2)
     #        AND plan.deadline is NOT NULL
     #    GROUP BY
     #        1,
     #        2,
     #        3
	# """
    sql_hubei_fenzhang = """SELECT
    YEAR (t1.repaid_at) 打款年份,
    	MONTH (t1.repaid_at) 打款月份,
    	concat(fc.`name`,'-易宝分账') 资金方,
    sum(
    		IFNULL(t1.current_repayment, 0)
    	) 当期总额,
    	sum(IFNULL(t1.principle, 0)) 当期本金,
    	sum(IFNULL(t1.interest, 0)) 当期利息,
    	sum(IFNULL(t1.prepay_fee, 0)) 提前还款服务费,
    	sum(
    		IFNULL(t1.funding_service_fee, 0)
    	) 资金方服务费,
    	sum(IFNULL(punish_fee, 0)) 逾期罚息

    FROM
    	audit.funding_repayment_record t1
     JOIN basic.funding_corp fc ON t1.funding_code = fc.funding_code
    WHERE
    	t1.repaid_at IS NOT NULL
    AND t1.remark is not NULL 
    AND t1.funding_code IN (290,330)
    AND  t1.repaid_at>='2015-01-01'
    GROUP BY
    	1,
    	2,
    	3"""
    select_hubei = """SELECT
    YEAR (t1.repaid_at) 打款年份,
    	MONTH (t1.repaid_at) 打款月份,
    	fc.`name` 资金方,
    sum(
    		IFNULL(t1.current_repayment, 0)
    	) 当期总额,
    	sum(IFNULL(t1.principle, 0)) 当期本金,
    	sum(IFNULL(t1.interest, 0)) 当期利息,
    	sum(IFNULL(t1.prepay_fee, 0)) 提前还款服务费,
    	sum(
    		IFNULL(t1.funding_service_fee, 0)
    	) 资金方服务费,
    	sum(IFNULL(punish_fee, 0)) 逾期罚息

    FROM
    	audit.funding_repayment_record t1
     JOIN basic.funding_corp fc ON t1.funding_code = fc.funding_code
    WHERE
    	t1.repaid_at IS NOT NULL
    AND (t1.remark is null OR  t1.remark='已代偿且分账成功')
    AND  t1.repaid_at>='2015-01-01'
    AND t1.funding_code=290
    GROUP BY
    	1,
    	2,
    	3"""
    sql_yangguang = """SELECT
                YEAR (t1.repaid_at) 打款年份,
                    MONTH (t1.repaid_at) 打款月份,
                    fc.`name` 资金方,
                sum(
                        IFNULL(t1.current_repayment, 0)
                    ) 当期总额,
                    sum(IFNULL(t1.principle, 0)) 当期本金,
                    sum(IFNULL(t1.interest, 0)) 当期利息,
                    sum(IFNULL(t1.prepay_fee, 0)) 提前还款服务费,
                    sum(
                        IFNULL(t1.funding_service_fee, 0)
                    ) 资金方服务费,
                    sum(IFNULL(t1.punish_fee, 0)) 逾期罚息

                FROM
                    audit.funding_repayment_record t1
                 JOIN basic.funding_corp fc ON t1.funding_code = fc.funding_code
                WHERE
                    t1.repaid_at IS NOT NULL
                AND t1.funding_code=330
                AND  t1.repaid_at>='2015-01-01'
                AND  t1.remark is NULL 
                GROUP BY 1,2,3"""
    # df_diandi = pd.read_sql(sql=sql_diandi, con=engine_audit)
    df_bubei_fenzhang = pd.read_sql(sql=sql_hubei_fenzhang, con=engine_audit)
    df_bubei = pd.read_sql(sql=select_hubei, con=engine_audit)
    df_yangguang = pd.read_sql(sql=sql_yangguang, con=engine_audit)
    df = pd.read_sql(sql=sql, con=engine_audit)
    df = df.append(df_bubei).append(df_bubei_fenzhang).append(df_yangguang)
    df.sort_values([u'打款年份', u'打款月份'])
    df.to_excel(u'E:/数据汇总/现金贷/还资金方表汇总2017-09_1027.xlsx', index=None)




def yggy_huizong():
    shihua_sql = """SELECT
    t1.loan_id,t1.term_no,
	t1.principle 实还本金,
	t1.interest 实还利息,
	t1.funding_service_fee 实还服务费,
	t1.punish_fee 实还罚息
FROM
	audit.funding_repayment_record t1
WHERE
	t1.repaid_at IS NOT NULL
AND t1.funding_code=330
AND t1.loan_id IN(SELECT loan_id FROM yangguang_batch_no WHERE batch_no='HZ20170316-055-001-001') ORDER BY t1.loan_id """
    df_sh = pd.read_sql(shihua_sql, con=engine_audit)
    df_sh['loan_id'] = df_sh['loan_id'].astype(str)
    df_sh['term_no'] = df_sh['term_no'].astype(str)
    df_sh['loan_id_term_no'] = df_sh['loan_id'] + df_sh['term_no']
    yinghuan_sql = """
SELECT
	ycp.principle 应还本金,ycp.interest 应还利息,ycp.loan_id,ycp.term_no
FROM
	new_transaction.yangbao_compensatory_plan ycp 
LEFT JOIN yangguang_batch_no ybn ON ybn.loan_id = ycp.loan_id
WHERE ybn.batch_no='HZ20170316-055-001-001'
AND ycp.term_no=1 ORDER BY ycp.loan_id """
    df_yh = pd.read_sql(yinghuan_sql, con=engine_audit)
    df_yh['loan_id'] = df_yh['loan_id'].astype(str)
    df_yh['term_no'] = df_yh['term_no'].astype(str)
    df_yh['loan_id_term_no'] = df_yh['loan_id'] + df_yh['term_no']
    df_sh = pd.merge(df_sh, df_yh, how='outer',on='loan_id_term_no')
    df_sh.rename(columns={'loan_id_x': '实还loan_id'}, inplace=True)
    df_sh.rename(columns={'loan_id_y': '应还loan_id'}, inplace=True)
    df_sh.rename(columns={'term_no_x': '实还期数'}, inplace=True)
    df_sh.rename(columns={'term_no_y': '应还期数'}, inplace=True)
    df_sh.rename(columns={'term_no_y': '应还期数'}, inplace=True)
    df_sh = df_sh.drop(['loan_id_term_no'], axis=1)
    df_sh.to_excel(u'E:/数据汇总/阳光广源实还赔付对照表new.xlsx', index=None)


repay_funding_excel_new()
# yggy_huizong()