DELIMITER $$

USE `apzl`$$

DROP PROCEDURE IF EXISTS `PROC_calc_tax_tj`$$

CREATE DEFINER=`apzl`@`%` PROCEDURE `PROC_calc_tax_tj`()
BEGIN
    DELETE FROM li_invoice_tj_auto;
    REPLACE INTO li_invoice_tj_auto(ID,
                                 contract_id,
                                 contract_no,
                                 lease_form,
                                 plan_list,
                                 invoice_money,
                                 tax_type,
                                 tax_no,
                                 tax_code,
                                 cert_id,
                                 account,
                                 acc_number,
                                 bank_name,
                                 telephone,
                                 customer_type,
                                 customer_name
                                 )
   SELECT
    REPLACE(UUID(), '-', '') ID,
  `lci`.`ID`            AS `contract_id`,
  `lci`.`CONTRACT_NO`   AS `contract_no`,
  lci.leas_form         AS  lease_form,
  `vib`.`plan_list`     AS `plan_list`,
  `vib`.`invoice_money` AS `invoice_money`,
  `cl`.`itemname`       AS `tax_type`,
  `vib`.`tax_no`        AS `tax_no`,
   case lci.leas_form  when '02' then  `tci`.`code` when '01' then `tci1`.`code` end          AS `tax_code`,
  `ca`.`CERTID`         AS `cert_id`,
  `ca`.`account`        AS `account`,
  `ca`.`acc_number`     AS `acc_number`,
  `ca`.`bank_name`      AS `bank_name`,
  `ca`.`MOBILE`         AS `telephone`,
  `ci`.`customertype`   AS `customer_type`,
  `ci`.`customername`   AS `customer_name`
FROM (((((((`apzl`.`vi_li_invoice_tj_base` `vib`
         LEFT JOIN `apzl`.`lb_contract_info` `lci`
           ON ((`vib`.`contract_id` = `lci`.`ID`))))
       LEFT JOIN `apzl`.`lb_union_lessee` `lul`
         ON ((`lul`.`CONTRACT_ID` = `lci`.`ID`)))
      LEFT JOIN `apzl`.`customer_info` `ci`
        ON ((`ci`.`customerid` = `lul`.`CUSTOMER_ID`)))
     LEFT JOIN `apzl`.`customer_account` `ca`
       ON ((`ca`.`CONTRACT_ID` = `lul`.`CONTRACT_ID`)))
    LEFT JOIN `apzl`.`code_library` `cl`
      ON (((`cl`.`codeno` = 'tax_type')
           AND (`cl`.`itemno` = `vib`.`tax_no`))))
   LEFT JOIN `apzl`.`tax_code_info` `tci`
     ON ((`tci`.`tax_type` = `cl`.`itemno` and tci.`lease_form`='02'))
     LEFT JOIN `apzl`.`tax_code_info` `tci1` on `tci1`.`tax_type` = `cl`.`itemno` and tci1.`lease_form`='01'
     )
WHERE ((`vib`.`tax_no` IN('rent','interest','penalty','feetype1','feetype4','feetype30'))
       )
;
END$$

DELIMITER ;