-- A5M2で実行時に[SQL] - [スラッシュ(/)のみの行でSQLを区切る]に変えてから実行する
CREATE PROCEDURE src05.sales_lau_upsert(target_table VARCHAR(255), extract_from_date DATE,
                                    extract_to_date DATE)
SQL SECURITY INVOKER
BEGIN
    -- スキーマ名
    DECLARE schema_name VARCHAR(50) DEFAULT (SELECT DATABASE());
    -- プロシージャ名
    DECLARE procedure_name VARCHAR(100) DEFAULT 'sales_lau_upsert';
    -- プロシージャの引数
    DECLARE procedure_args JSON DEFAULT JSON_OBJECT('target_table', target_table, 'extract_from_date', 
                            extract_from_date, 'extract_to_date', extract_to_date);

    -- 例外処理
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
        BEGIN
            GET DIAGNOSTICS CONDITION 1
                @error_state = RETURNED_SQLSTATE, @error_msg = MESSAGE_TEXT;
            CALL medaca_common.put_error_log(schema_name, procedure_name, procedure_args,
                                    'sales_lau_upsertでエラーが発生', @error_state, @error_msg);
            SET @error_msg = (
                CASE
                WHEN LENGTH(@error_msg) > 128 THEN CONCAT(SUBSTRING(@error_msg, 1, 125), '...')
                ELSE @error_msg
                END
            );
            SIGNAL SQLSTATE '45000'
                SET MYSQL_ERRNO = @error_state, MESSAGE_TEXT = @error_msg;
        END;

    SET @error_state = NULL, @error_msg = NULL;

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成① 開始'
    );

    TRUNCATE TABLE internal05.bu_prd_name_contrast_t;

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成① 終了' 
    );

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成② 開始' 
    );

    INSERT INTO
        internal05.bu_prd_name_contrast_t (
            prd_cd,
            bu_cd,
            phm_itm_cd,
            pp_start_date,
            pp_end_date,
            update_date,
            bp_start_date,
            bp_end_date
        )
    SELECT
        ppmv.prd_cd,
        bpnc.bu_cd,
        ppmv.phm_itm_cd,
        ppmv.start_date AS pp_start_date,
        ppmv.end_date AS pp_end_date,
        bpnc.update_date AS update_date,
        bpnc.start_date AS bp_start_date,
        bpnc.end_date AS bp_end_date
    FROM
        src05.phm_prd_mst_v AS ppmv
    LEFT OUTER JOIN src05.bu_prd_name_contrast AS bpnc
        ON ppmv.phm_itm_cd = bpnc.phm_itm_cd
    WHERE
        ppmv.rec_sts_kbn != '9'
    ;

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成② 終了' 
    );


    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成③ 開始'
    );

    TRUNCATE TABLE internal05.fcl_mst_v_t;

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成③ 終了'
    );

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成④ 開始'
    );

    INSERT INTO
        internal05.fcl_mst_v_t
    SELECT
        fmv1.v_inst_cd,
        fmv1.sub_num,
        fmv1.start_date,
        fmv1.end_date,
        fmv1.closed_dt,
        fmv1.fcl_name,
        fmv1.fcl_kn_name,
        fmv1.fcl_abb_name,
        fmv1.fcl_abb_kn_name,
        fmv1.mkr_cd,
        fmv1.jsk_proc_kbn,
        fmv1.fmt_addr,
        fmv1.fmt_kn_addr,
        fmv1.postal_cd,
        fmv1.prft_cd,
        fmv1.prft_name,
        fmv1.city_name,
        fmv1.addr_line_1,
        fmv1.tel_num,
        fmv1.admin_kbn,
        fmv1.fcl_type,
        fmv1.rec_sts_kbn,
        fmv1.ins_dt,
        fmv1.upd_dt,
        fmv1.dwh_upd_dt
    FROM
        src05.fcl_mst_v AS fmv1
    INNER JOIN (
        SELECT
            fmv.v_inst_cd,
            MAX(fmv.sub_num) AS sno  
        FROM
            src05.fcl_mst_v AS fmv
        GROUP BY
            fmv.v_inst_cd
        ) AS fmv2 
        ON fmv1.v_inst_cd = fmv2.v_inst_cd
        AND fmv1.sub_num = fmv2.sno
    WHERE
        fmv1.rec_sts_kbn != '9'
    ;

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成④ 終了'
    );

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成⑤ 開始'
    );

    SET @extract_from_datetime = CAST(extract_from_date AS DATETIME);
    SET @extract_to_datetime = ADDTIME(CAST(extract_to_date AS DATETIME), '23:59:59');

    SET @upsert_sales_launderning = "
        INSERT INTO
            $$target_table$$ (
                rec_whs_cd,
                rec_whs_sub_cd,
                rec_whs_org_cd,
                rec_cust_cd,
                rec_comm_cd,
                rec_tran_kbn,
                rev_hsdnymd_wrk,
                rev_hsdnymd_srk,
                rec_urag_num,
                rec_qty,
                rec_nonyu_price,
                rec_nonyu_amt,
                rec_comm_name,
                rec_nonyu_fcl_name,
                free_item,
                rec_nonyu_fcl_addr,
                rec_nonyu_fcl_post,
                rec_nonyu_fcl_tel,
                rec_bef_hsdn_ymd,
                rec_bef_slip_num,
                rec_ymd,
                sale_data_cat,
                slip_file_name,
                slip_mgt_num,
                row_num,
                hsdn_ymd,
                exec_dt,
                v_tran_cd,
                tran_kbn_name,
                whs_org_cd,
                v_whsorg_cd,
                whs_org_name,
                whs_org_kn,
                v_whs_cd,
                whs_name,
                nonyu_fcl_cd,
                inst_name,
                inst_name_kana,
                address,
                comm_cd,
                comm_name,
                nonyu_qty,
                nonyu_price,
                nonyu_amt,
                shikiri_price,
                shikiri_amt,
                nhi_price,
                nhi_amt,
                v_inst_cd,
                inst_clas_cd,
                bu_cd,
                item_cd,
                item_name,
                item_english_name,
                pref_cd,
                whspos_err_kbn,
                htdnymd_err_kbn,
                prd_exis_kbn,
                fcl_exis_kbn,
                bef_hsdn_ymd,
                bef_slip_num,
                slip_org_kbn,
                kjyo_ym,
                tksnbk_kbn,
                fcl_exec_kbn,
                rec_sts_kbn,
                ins_dt,
                ins_usr,
                dwh_upd_dt 
            )
        SELECT
            s.rec_whs_cd,
            s.rec_whs_sub_cd,
            s.rec_whs_org_cd,
            s.rec_cust_cd,
            s.rec_comm_cd,
            s.rec_tran_kbn,
            s.rev_hsdnymd_wrk,
            s.rev_hsdnymd_srk,
            s.rec_urag_num,
            s.rec_qty,
            s.rec_nonyu_price,
            s.rec_nonyu_amt,
            s.rec_comm_name,
            s.rec_nonyu_fcl_name,
            s.free_item,
            s.rec_nonyu_fcl_addr,
            s.rec_nonyu_fcl_post,
            s.rec_nonyu_fcl_tel,
            s.rec_bef_hsdn_ymd,
            s.rec_bef_slip_num,
            s.rec_ymd,
            s.sale_data_cat,
            s.slip_file_name,
            s.slip_mgt_num,
            s.row_num,
            s.hsdn_ymd,
            s.exec_dt,
            s.v_tran_cd,
            s.tran_kbn_name,
            s.whs_org_cd,
            s.v_whsorg_cd,
            s.whs_org_name,
            s.whs_org_kn,
            s.v_whs_cd,
            s.whs_name,
            s.nonyu_fcl_cd,
            s.v_inst_name,
            s.v_inst_kn,
            s.v_inst_addr,
            s.comm_cd,
            s.comm_name,
            CASE
                WHEN
                    (LEFT(s.v_tran_cd, 1) = 2 AND (s.err_flg20 IS NULL OR s.err_flg20 != 'M'))
                THEN
                    -s.nonyu_qty
                ELSE
                    s.nonyu_qty
            END AS nonyu_qty,
            s.nonyu_price,
            CASE
                WHEN
                    (LEFT(s.v_tran_cd, 1) = 2 AND (s.err_flg20 IS NULL OR s.err_flg20 != 'M'))
                THEN
                    -s.nonyu_amt
                ELSE
                    s.nonyu_amt
            END AS nonyu_amt,
            s.shikiri_price,
            CASE
                WHEN
                    (LEFT(s.v_tran_cd, 1) = 2 AND (s.err_flg20 IS NULL OR s.err_flg20 != 'M'))
                THEN
                    -s.shikiri_amt
                ELSE
                    s.shikiri_amt
            END AS shikiri_amt,
            s.nhi_price,
            CASE
                WHEN
                    (LEFT(s.v_tran_cd,1) = 2 AND (s.err_flg20 IS NULL OR s.err_flg20 != 'M'))
                THEN
                    -s.nhi_amt
                ELSE
                    s.nhi_amt
            END AS nhi_amt,
            s.v_inst_cd,
            CASE 
                WHEN
                    (fmvt.fcl_type = 'A1' or fmvt.fcl_type = 'A0') THEN '3'
                WHEN
                    fmvt.fcl_type BETWEEN '20' AND '29' THEN '2'
                ELSE
                    '1'
            END AS inst_clas_cd,
            bpnct.bu_cd,
            ppmv.mkr_cd,
            ppmv.mkr_inf_1,
            ppmv.mkr_inf_2,
            CASE
                WHEN
                    s.v_inst_cd LIKE '00%'
                THEN
                    ci.prefc_cd
                ELSE
                    fmvt.prft_cd
            END AS pref_cd,
            s.whspos_err_kbn,
            s.htdnymd_err_kbn,
            s.prd_exis_kbn,
            s.fcl_exis_kbn,
            s.bef_hsdn_ymd,
            s.bef_slip_num,
            s.slip_org_kbn,
            s.kjyo_ym,
            s.tksnbk_kbn,
            s.fcl_exec_kbn,
            s.rec_sts_kbn,
            s.ins_dt,
            s.ins_usr,
            SYSDATE()
        FROM (
            SELECT
                ? AS extract_from_datetime,
                ? AS extract_to_datetime 
        ) AS sub
        INNER JOIN src05.sales AS s
            ON s.dwh_upd_dt BETWEEN sub.extract_from_datetime AND sub.extract_to_datetime
        LEFT OUTER JOIN src05.phm_prd_mst_v AS ppmv
            ON s.comm_cd = ppmv.prd_cd
            AND STR_TO_DATE(s.hsdn_ymd,'%Y%m%d') BETWEEN ppmv.start_date AND ppmv.end_date
            AND ppmv.rec_sts_kbn != '9'
        LEFT OUTER JOIN internal05.fcl_mst_v_t AS fmvt
            ON s.v_inst_cd = fmvt.v_inst_cd
        LEFT OUTER JOIN internal05.bu_prd_name_contrast_t AS bpnct
            ON s.comm_cd = bpnct.prd_cd
            AND STR_TO_DATE(s.hsdn_ymd, '%Y%m%d') BETWEEN bpnct.pp_start_date AND bpnct.pp_end_date
            AND STR_TO_DATE(s.hsdn_ymd, '%Y%m%d') BETWEEN bpnct.bp_start_date AND bpnct.bp_end_date
        LEFT OUTER JOIN src05.com_inst AS ci
            ON s.v_inst_cd = ci.dcf_dsf_inst_cd
        WHERE
            (s.rec_sts_kbn = '0' AND s.err_flg20 = 'M')
            OR (
                        s.rec_sts_kbn = '0'
                    AND s.err_flg20 != 'M'
                    AND s.v_tran_cd IN (110, 120, 210, 220)
                    AND (
                                (s.fcl_exec_kbn NOT IN ('2', '5') AND (s.fcl_exec_kbn != '6' OR ppmv.prd_sale_kbn != 1))
                            OR  s.fcl_exec_kbn IS NULL
                    )
            )

        ON DUPLICATE KEY UPDATE
            rec_whs_cd = s.rec_whs_cd,
            rec_whs_sub_cd = s.rec_whs_sub_cd,
            rec_whs_org_cd = s.rec_whs_org_cd,
            rec_cust_cd = s.rec_cust_cd,
            rec_comm_cd = s.rec_comm_cd,
            rec_tran_kbn = s.rec_tran_kbn,
            rev_hsdnymd_wrk = s.rev_hsdnymd_wrk,
            rev_hsdnymd_srk = s.rev_hsdnymd_srk,
            rec_urag_num = s.rec_urag_num,
            rec_qty = s.rec_qty,
            rec_nonyu_price = s.rec_nonyu_price,
            rec_nonyu_amt = s.rec_nonyu_amt,
            rec_comm_name = s.rec_comm_name,
            rec_nonyu_fcl_name = s.rec_nonyu_fcl_name,
            free_item = s.free_item,
            rec_nonyu_fcl_addr = s.rec_nonyu_fcl_addr,
            rec_nonyu_fcl_post = s.rec_nonyu_fcl_post,
            rec_nonyu_fcl_tel = s.rec_nonyu_fcl_tel,
            rec_bef_hsdn_ymd = s.rec_bef_hsdn_ymd,
            rec_bef_slip_num = s.rec_bef_slip_num,
            rec_ymd = s.rec_ymd,
            sale_data_cat = s.sale_data_cat,
            slip_file_name = s.slip_file_name,
            row_num = s.row_num,
            hsdn_ymd = s.hsdn_ymd,
            exec_dt = s.exec_dt,
            v_tran_cd = s.v_tran_cd,
            tran_kbn_name = s.tran_kbn_name,
            whs_org_cd = s.whs_org_cd,
            v_whsorg_cd = s.v_whsorg_cd,
            whs_org_name = s.whs_org_name,
            whs_org_kn = s.whs_org_kn,
            v_whs_cd = s.v_whs_cd,
            whs_name = s.whs_name,
            nonyu_fcl_cd = s.nonyu_fcl_cd,
            inst_name = s.v_inst_name,
            inst_name_kana = s.v_inst_kn,
            address = s.v_inst_addr,
            comm_cd = s.comm_cd,
            comm_name = s.comm_name,
            nonyu_qty = VALUES(nonyu_qty),
            nonyu_price = s.nonyu_price,
            nonyu_amt = VALUES(nonyu_amt),
            shikiri_price = s.shikiri_price,
            shikiri_amt = VALUES(shikiri_amt),
            nhi_price = s.nhi_price,
            nhi_amt = VALUES(nhi_amt),
            v_inst_cd = s.v_inst_cd,
            inst_clas_cd = VALUES(inst_clas_cd),
            bu_cd = bpnct.bu_cd,
            item_cd = ppmv.mkr_cd,
            item_name = ppmv.mkr_inf_1,
            item_english_name = ppmv.mkr_inf_2,
            pref_cd = VALUES(pref_cd),
            whspos_err_kbn = s.whspos_err_kbn,
            htdnymd_err_kbn = s.htdnymd_err_kbn,
            prd_exis_kbn = s.prd_exis_kbn,
            fcl_exis_kbn = s.fcl_exis_kbn,
            bef_hsdn_ymd = s.bef_hsdn_ymd,
            bef_slip_num = s.bef_slip_num,
            slip_org_kbn = s.slip_org_kbn,
            kjyo_ym = s.kjyo_ym,
            tksnbk_kbn = s.tksnbk_kbn,
            fcl_exec_kbn = s.fcl_exec_kbn,
            rec_sts_kbn = s.rec_sts_kbn,
            ins_dt = s.ins_dt,
            ins_usr = s.ins_usr,
            dwh_upd_dt = SYSDATE()
    ";
    SET @upsert_sales_launderning = REPLACE(@upsert_sales_launderning, "$$target_table$$", target_table);
    PREPARE upsert_sales_launderning_stmt from @upsert_sales_launderning;
    EXECUTE upsert_sales_launderning_stmt USING @extract_from_datetime, @extract_to_datetime;

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成⑤ 終了'
    );

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成⑥ 開始'
    );    

    SET @update_institution_code = "  
        UPDATE (
                SELECT 
                    ? AS extract_from_datetime,
                    ? AS extract_to_datetime 
            ) AS sub,
            $$target_table$$ AS tt,
            src05.sales AS s
        SET
            tt.inst_cd = (
                CASE
                    WHEN
                        (s.err_flg20 != 'M' AND tt.inst_clas_cd IN ('2', '3')) OR (s.err_flg20 = 'M')
                    THEN
                        s.v_inst_cd
                    ELSE
                        NULL
                END
            )
        WHERE
                s.dwh_upd_dt BETWEEN sub.extract_from_datetime AND sub.extract_to_datetime
            AND tt.slip_mgt_num = s.slip_mgt_num
            AND tt.row_num = s.row_num
    ";
    SET @update_institution_code = REPLACE(@update_institution_code, "$$target_table$$", target_table);
    PREPARE update_institution_code_stmt from @update_institution_code;
    EXECUTE update_institution_code_stmt USING @extract_from_datetime, @extract_to_datetime;

    CALL medaca_common.put_info_log(schema_name, procedure_name, procedure_args,
                            '卸販売実績テーブル（洗替後）作成⑥ 終了'
    );

END