create procedure penalty_over_inint(IN r_plan_id varchar(32), IN r_plan_date varchar(32))
BEGIN
        DECLARE r_contract_id VARCHAR(32);
        DECLARE r_penaty_rate DECIMAL(18,2);
        DECLARE r_all_penalty DECIMAL(18,2);
        DECLARE r_penalty_adjust_date INT;
        DECLARE r_over_date INT;
        -- SET r_penaty_rate=0.05;
        -- SET r_penalty_adjust_date=7;
        SELECT contract_id INTO r_contract_id FROM lc_rent_plan WHERE id=r_plan_id;
        SELECT PENA_RATE,FREE_DEFA_INTER_DAY INTO r_penaty_rate,r_penalty_adjust_date FROM lc_calc_condition
        WHERE contract_id=r_contract_id;
         SELECT SUM(CASE WHEN difday>0 THEN a.fact_rent*r_penaty_rate*difday/10000 ELSE 0 END),MAX(difday)   INTO  r_all_penalty,r_over_date
         FROM (
	 SELECT  DATEDIFF(fi.hire_date,cp.plan_date) difday,fi.fact_rent FROM lc_rent_plan cp
	 LEFT OUTER JOIN 
	 (SELECT  plan_id,rent fact_rent, hire_date FROM 
	     lc_rent_income
	      WHERE plan_id=r_plan_id
	     UNION 
	     SELECT cp.id paln_id,cp.rent-nvl(ci.rent,0) fact_rent,r_plan_date hiredate FROM 
	     lc_rent_plan cp
	     LEFT OUTER JOIN(
                SELECT plan_id,SUM(rent) rent FROM lc_rent_income
                WHERE plan_id=r_plan_id	     
	     )ci ON cp.id=ci.plan_id
	     WHERE id=r_plan_id
	  )fi
	  ON cp.id=fi.plan_id
	  WHERE cp.id=r_plan_id
	  )a;
	  IF r_over_date<=r_penalty_adjust_date THEN
	   SET  r_all_penalty=0;
	  END IF;
	  UPDATE lc_rent_plan SET penalty=r_all_penalty,penalty_overage=r_all_penalty-fact_penalty-fact_penalty_adjust,over_date=r_over_date	   WHERE id=r_plan_id;
	 -- select r_all_penalty,r_plan_id;
END;

