create function bb_getLoanInterest_gs(bill_id_ varchar(32), start_date_ varchar(32), end_date_ varchar(32)) returns varchar(1000)
BEGIN
  DECLARE gs VARCHAR(1000) default '';
  DECLARE real_start_date VARCHAR(32);
  DECLARE temp_date VARCHAR(32);
  DECLARE plan_date_ VARCHAR(32);
  DECLARE year_rate_ DECIMAL(22,6);
  DECLARE temp_rate DECIMAL(22,6);
  DECLARE gtype INT;
  DECLARE day_flag INT;
  DECLARE rate_year_days_ INT;#年计息天数
  DECLARE remcorpus DECIMAL(22,2);
  DECLARE days INT;
  DECLARE done BOOLEAN DEFAULT FALSE;
  DECLARE outer_cursor CURSOR FOR
  SELECT * FROM (
    SELECT plan_date,0 AS rate,0 AS gtype FROM loan_fund_plan
    WHERE bill_id=bill_id_ AND plan_date>=start_date_
    AND plan_date<=end_date_ AND IFNULL(corpus,0)>0
    UNION
    SELECT adjust_date AS plan_date,rate_new AS rate,1 AS gtype FROM loan_rate_adjust
    WHERE bill_id=bill_id_ AND status_='rate_adjust' AND mod_reason='his_rate_change'
          AND adjust_date>=start_date_ AND adjust_date<=end_date_
    UNION
    SELECT end_date_ AS  plan_date,0 AS rate,0 AS gtype FROM DUAL
  ) tab ORDER BY plan_date;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=TRUE;
  SET rate_year_days_ = 360;
  SET year_rate_ = 0;
  SET temp_rate = 0;
  SET temp_date = start_date_;
  SET gtype = 0;
  SET day_flag = 0;
  SET days = 0;
  #如果计提利息期间开始时间小于借据放款日期，则以借据放款日期为开始时间
  SELECT GREATEST(start_date_,loan_start_date) INTO real_start_date FROM loan_bill_info WHERE id=bill_id_;
  SET temp_date = real_start_date;
  SELECT tmp.rate_new INTO temp_rate FROM (SELECT t.rate_new FROM
  (SELECT adjust_date,rate_new,create_date FROM loan_rate_adjust WHERE bill_id=bill_id_ AND status_='rate_adjust' AND mod_reason='his_rate_change' AND adjust_date<=real_start_date
  UNION
  SELECT loan_start_date AS adjust_date,rate AS rate_new, create_date FROM loan_bill_info WHERE id=bill_id_
    ) t ORDER BY adjust_date DESC,create_date DESC) tmp LIMIT 1;
  #取年计息天数
  SELECT rate_year_days INTO rate_year_days_ FROM loan_bill_info WHERE id=bill_id_;
  #对计提利息期间按利率变化及本金变化分段
  OPEN outer_cursor;
  myLoop:LOOP
    FETCH outer_cursor INTO plan_date_,year_rate_,gtype;
    IF done THEN LEAVE myLoop;
    END IF;
    #算头不算尾，第1个分段，时间加一天
    SELECT DATEDIFF(plan_date_,temp_date) + day_flag INTO days FROM DUAL;
    SET day_flag = 0;
    if days>=0 then
    SELECT SUM(IFNULL(corpus,0)) INTO remcorpus FROM loan_fund_plan WHERE bill_id=bill_id_ AND plan_date>=plan_date_;
    IF remcorpus>0 THEN
       SELECT CONCAT(gs,days,'天*剩余本金',remcorpus,'*日利率(',temp_rate,'/100)/',rate_year_days_ ,'),开始:',temp_date,'结束:',plan_date_,';') INTO gs FROM DUAL;
    END IF;
    end if;
    IF gtype=1 THEN
      SET temp_rate = year_rate_;
    END IF;
    SET temp_date = plan_date_;
  END LOOP myLoop;
  CLOSE outer_cursor;
  RETURN gs;
END;

