CREATE OR REPLACE FUNCTION f_import_cast_item(
    IN itemcode integer,
    IN castcode integer[],
    IN castname character varying[],

    IN _shopdiv integer,

    IN usr character varying,


    OUT errcd integer,
    OUT errmsg character varying) AS
$BODY$

DECLARE
     cast integer;
	 cnt integer;
     i   integer;
     flg integer;
BEGIN
    errcd := 1;
    i := 1;

    IF itemcode IS NULL THEN
        errmsg := '品目コードが指定されていません。';
        errcd := -10;
        RETURN;
    END IF;

    IF usr IS NULL THEN
        errmsg := '更新ユーザが指定されていません。';
        errcd := -10;
        RETURN;
    END IF;

    LOOP
        flg := 1;

        IF castcode[i] = 0 AND castname[i] = 'NULL' THEN
            flg := 0;

        ELSIF _shopdiv = 1 THEN
            -- 
            IF castcode[i] <> 0 THEN
                SELECT castcd INTO cast FROM t_cast WHERE castcd = castcode[i] AND castdiv=1 AND shopdiv = _shopdiv;
                IF cast IS NULL THEN
                    errmsg := castcode[i] || 'はキャストマスタにありません';
                    errcd := -10;
                    RETURN;
                END IF;

            ELSIF castcode[i] = 0 THEN
                -- キャスト名からキャストコード取得
                SELECT castcd INTO cast FROM t_cast WHERE castnm LIKE castname[i] AND castdiv=1 AND shopdiv = _shopdiv;
                IF cast IS NULL THEN
                    errmsg := castname[i] || 'はキャストマスタにありません';
                    errcd := -10;
                    RETURN;
                END IF;
            END IF;
        ELSIF _shopdiv = 2 THEN
            -- 一般
            IF castcode[i] <> 0 THEN
                SELECT castcd INTO cast FROM t_cast WHERE castcd = castcode[i] AND (castdiv=1 OR castdiv=3) AND shopdiv = _shopdiv;
                IF cast IS NULL THEN
                    errmsg := castcode[i] || 'はキャストマスタにありません';
                    errcd := -10;
                    RETURN;
                END IF;

            ELSIF castcode[i] = 0 THEN
                -- キャスト名からキャストコード取得
                SELECT castcd INTO cast FROM t_cast WHERE castnm LIKE castname[i] AND (castdiv=1 OR castdiv=3) AND shopdiv = _shopdiv;
                IF cast IS NULL THEN
                    errmsg := castname[i] || 'はキャストマスタにありません';
                    errcd := -10;
                    RETURN;
                END IF;
            END IF;
        END IF;


        -- 追加(重複しない)
        SELECT count(*) INTO cnt FROM t_cast_item WHERE itemcd=itemcode AND castcd=cast;
        IF cnt <= 0 AND flg = 1 THEN
            INSERT INTO t_cast_item(castcd, itemcd, disppriority, updusrnm) VALUES(cast, itemcode, 6-i, usr);
        END IF;

        -- ループ終了
        i := i + 1;
        IF castcode[i] IS NULL AND castname[i] IS NULL THEN
            EXIT;
        END IF;

    END LOOP;
    errcd := 1;
END;

$BODY$
  LANGUAGE 'plpgsql' VOLATILE;
