create function getRentPenalty(r_payment_number varchar(40), r_plan_list varchar(40), calc_date varchar(40)) returns varchar(200)
RETURN (
SELECT ROUND(MAX(te.rpenalty)+SUM(te.ipenalty)+SUM(te.tpenalty),2) FROM(
SELECT lrp.ID,lrp.PLAN_LIST,lccs.payment_number,
CASE WHEN (STR_TO_DATE(lrp.PLAN_DATE,'%Y/%m/%d')+c.attr_value)<=STR_TO_DATE(calc_date,'%Y/%m/%d') THEN lcc.PENA_RATE/10000*(DATEDIFF(STR_TO_DATE(calc_date,'%Y/%m/%d'),STR_TO_DATE(lrp.PLAN_DATE,'%Y/%m/%d')))*(lrp.rent-IFNULL(lric.rent,0)-IFNULL(lrit.rent,0)) ELSE 0 END rpenalty,
CASE WHEN (STR_TO_DATE(lrp.PLAN_DATE,'%Y/%m/%d')+c.attr_value)<=STR_TO_DATE(lri.hire_date,'%Y/%m/%d') THEN lcc.PENA_RATE/10000*(DATEDIFF(STR_TO_DATE(IF(STR_TO_DATE(lri.hire_date,'%Y/%m/%d')>STR_TO_DATE(calc_date,'%Y/%m/%d'),calc_date,lri.hire_date),'%Y/%m/%d'),STR_TO_DATE(lrp.PLAN_DATE,'%Y/%m/%d')))*IFNULL(lri.rent,0) ELSE 0 END ipenalty,
CASE WHEN (STR_TO_DATE(lrp.PLAN_DATE,'%Y/%m/%d')+c.attr_value)<=STR_TO_DATE(lrit.hire_date,'%Y/%m/%d') THEN lcc.PENA_RATE/10000*(DATEDIFF(STR_TO_DATE(IF(STR_TO_DATE(lrit.hire_date,'%Y/%m/%d')>STR_TO_DATE(calc_date,'%Y/%m/%d'),calc_date,lrit.hire_date),'%Y/%m/%d'),STR_TO_DATE(lrp.PLAN_DATE,'%Y/%m/%d')))*IFNULL(lrit.rent,0) ELSE 0 END tpenalty
FROM (SELECT * FROM lc_calc_condition_status WHERE PAYMENT_NUMBER=r_payment_number)  lccs 
LEFT JOIN lc_calc_condition lcc ON lcc.PAYMENT_NUMBER=lccs.PAYMENT_NUMBER
LEFT JOIN CONFIGURATE c ON 1=1 AND  c.attr_id='免罚息天数配置' AND c.field1='汽车'
LEFT JOIN lc_rent_plan lrp ON lrp.PAYMENT_NUMBER=lccs.PAYMENT_NUMBER  AND LRP.PAYMENT_NUMBER=r_payment_number
LEFT JOIN  (SELECT * FROM lc_rent_income WHERE hire_date<calc_date ) lri ON lri.PLAN_ID=lrp.ID AND lri.ROLL_BACK='0' AND LRI.PAYMENT_NUMBER=r_payment_number
LEFT JOIN (SELECT contract_id,plan_id,SUM(rent) rent,MAX(hire_date) hire_date FROM lc_rent_income WHERE ROLL_BACK='0' AND PAYMENT_NUMBER=r_payment_number AND STR_TO_DATE(hire_date,'%Y/%m/%d')<=STR_TO_DATE(calc_date,'%Y/%m/%d') GROUP BY contract_id,plan_id) lric ON lric.PLAN_ID=lrp.ID 
LEFT JOIN (SELECT contract_id,plan_id,SUM(rent) rent,MAX(hire_date) hire_date FROM lc_rent_income_temp WHERE ROLL_BACK='0' AND PAYMENT_NUMBER=r_payment_number AND IS_FLOWING='0'  GROUP BY contract_id,plan_id) lrit ON lrit.PLAN_ID=lrp.ID  
WHERE lccs.payment_number=r_payment_number AND lrp.plan_list=r_plan_list
) te GROUP BY te.payment_number,te.id
);

