# -*- coding: utf-8 -*-
import pandas as pd

pd.options.mode.chained_assignment = None
import sys
from sqlalchemy import create_engine

reload(sys)
sys.setdefaultencoding('utf8')
engine_baitiao_audit = create_engine(
    'mysql+mysqldb://yulong_rw:TouBStYwN8wkdxVt@172.16.3.201:3306/baitiao_audit?charset=utf8',
    echo=True)

select_sql = """
SELECT
	SUM(frr.current_amount) 债权原始价,
	SUM(frr.transfer_amount) 折扣价,
	tfq.fund_name 资金方,
	year(tfq.repay_time) 债转年份,
	month(tfq.repay_time) 债转月份
FROM
	baitiao_fund_repayment_record frr
JOIN fund_qg_detail tfq ON tfq.package_name = frr.package_name
WHERE
	frr.package_type IN ('1', '2')
GROUP BY
	3,
	4,
	5"""

select_jinrongquan_sql = """
SELECT
	SUM(frr.current_amount) 债权原始价,
	SUM(frr.transfer_amount) 折扣价,
	frr.fund_name 资金方,
	year(frr.start_time) 债转年份,
	month(frr.start_time) 债转月份
FROM
	baitiao_fund_repayment_record frr 
WHERE  locate('金融圈',frr.fund_name) > 0
GROUP BY
	3,
	4,
	5"""


def debet():
    df_1 = pd.read_sql(sql=select_sql, con=engine_baitiao_audit)
    df_2 = pd.read_sql(sql=select_jinrongquan_sql, con=engine_baitiao_audit)
    df = df_1.append(df_2)
    df.to_excel(u"E:/数据汇总/还资金方/白条债转表2017-06.xlsx", index=None)


debet()


def update_fund_repayment_record():
    df = pd.read_excel(u"E:/baitiao/金融圈去哪儿.xlsx", sheetname='Sheet1')
    df.rename(columns={u'产品编号': 'loan_no',
                       u'贷款时间': 'start_time'
                       }, inplace=True)
    df['loan_no'] = df['loan_no'].astype(str)
    a = df['loan_no'].tolist()
    query_sql = """SELECT id,loan_no FROM baitiao_fund_repayment_record WHERE loan_no in %s"""
    df_1 = pd.read_sql(query_sql % (str(tuple(a)),), engine_baitiao_audit)
    df_1['loan_no'] = df_1['loan_no'].astype(str)
    df_1['id'] = df_1['id'].astype(int)
    df = pd.merge(df, df_1, on='loan_no')
    values_list = df[['start_time', 'id']].values.tolist()
    update_sql = """update baitiao_fund_repayment_record set start_time=%s WHERE  id=%s """
    engine_baitiao_audit.execute(update_sql, values_list)
