# -*- coding: utf-8 -*-
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.path.insert(0, 'c:\\Users\\청춘약국\\source\\pharmacy-pos-qr-system\\backend')

from db.dbsetup import get_db_session
from sqlalchemy import text
from datetime import datetime

session = get_db_session('PM_DRUG')

# 1. 기존 데이터에서 가격 정보 가져오기
print('1. 기존 레코드에서 가격 정보 조회...')
existing = session.execute(text("""
    SELECT TOP 1 CD_MY_UNIT, CD_IN_UNIT 
    FROM CD_ITEM_UNIT_MEMBER 
    WHERE DRUGCODE = 'LB000003140'
    ORDER BY SN DESC
""")).fetchone()

sale_price = existing.CD_MY_UNIT
purchase_price = existing.CD_IN_UNIT
print(f'   판매가: {sale_price:,.0f}원')
print(f'   입고가: {purchase_price:,.0f}원')

# 2. 오늘 날짜
today = datetime.now().strftime('%Y%m%d')
print(f'\n2. 날짜: {today}')

# 3. INSERT 실행
print('\n3. INSERT 실행...')
apc_code = '0231093520106'  # 복합개시딘 10g

try:
    session.execute(text("""
        INSERT INTO CD_ITEM_UNIT_MEMBER (
            DRUGCODE, CD_CD_UNIT, CD_NM_UNIT, CD_MY_UNIT, CD_IN_UNIT,
            CD_CD_BARCODE, CD_CD_POS, CHANGE_DATE
        ) VALUES (
            :drugcode, :unit, :nm_unit, :my_unit, :in_unit,
            :barcode, :pos, :change_date
        )
    """), {
        'drugcode': 'LB000003140',
        'unit': '015',
        'nm_unit': 1.0,
        'my_unit': sale_price,
        'in_unit': purchase_price,
        'barcode': apc_code,
        'pos': '',
        'change_date': today
    })
    
    session.commit()
    print(f'   ✅ 성공! APC {apc_code} 추가됨')
    
    # 4. 확인
    print('\n4. 결과 확인...')
    result = session.execute(text("""
        SELECT DRUGCODE, CD_CD_BARCODE, CD_MY_UNIT, SN
        FROM CD_ITEM_UNIT_MEMBER 
        WHERE DRUGCODE = 'LB000003140' AND CD_CD_BARCODE = :apc
    """), {'apc': apc_code})
    
    row = result.fetchone()
    if row:
        print(f'   DRUGCODE: {row.DRUGCODE}')
        print(f'   BARCODE: {row.CD_CD_BARCODE}')
        print(f'   SN: {row.SN}')
    
except Exception as e:
    session.rollback()
    print(f'   ❌ 실패: {e}')

session.close()
