using System;
using System.Text;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;

using Cosmos.Win;
using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using Cosmos.UI;

//#16232 환경부 1회용컵 사용줄이기 관련 테이크인아웃 설정 start

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 제조음료 Take In/Out
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmTakeInOutProd : Form
    {

        #region 변수 선언

        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private TranStatus m_cTrnStatus = new TranStatus();                         // 거래정보 참조        
        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리
        private PosOLEDevice.DelegateOlePos delegatePos;

        private IICReaderUs m_cDeviceICReader = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IDataProcessUs m_cDataService = null;
        private ISalePluItemUs m_cPluService = null;                                // 판매 등록 관리
        private IPaymentUs m_cCouponDC = null;

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmTakeInOutProd()
        {
            InitializeComponent();

            base.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);
            //this.UpdateStyles();

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보 
            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;

            m_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDeviceICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cPluService = (ISalePluItemUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_PLU_ITEM);
            m_cCouponDC = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.COUPONDC);

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
        }

        private void frmTakeInOut_Load(object sender, EventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
            InitControl();
        }

        private void frmTakeInOut_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

        private void frmTakeInOut_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }

        private void frmTakeInOut_FormClosing(object sender, FormClosingEventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                 System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", lblTitle.Text);
        }

        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);

                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);
                FormManager.SetTextBoxGlobalInfo(this, m_cPosStatus.Global.m_stCultureMaster.nGroupingDigits, m_cPosStatus.Global.m_stCultureMaster.strGroupingSymbol
                    , m_cPosStatus.Global.m_stCultureMaster.nDecimalDigits, m_cPosStatus.Global.m_stCultureMaster.strDecimalSymbol);

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1175);
                lblProd.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1176);
                btn_AllTakeIn.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1177);
                btn_AllTakeOut.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1178);
                
                btnSave.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0225);

                btnGridUp.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_GRID_UP_ARROW);
                btnGridUp.ImageAlign = ContentAlignment.MiddleCenter;
                btnGridUp.BorderStyle = BorderStyle.None;

                btnGridDown.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_GRID_DOWN_ARROW);
                btnGridUp.ImageAlign = ContentAlignment.MiddleCenter;
                btnGridDown.BorderStyle = BorderStyle.None;

                DataGridSetting();      // 그리드 초기화

                LoadItemToGridView();

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion


        #region 그리드 설정 및 사용
        private void DataGridSetting()
        {
            try
            {
                btnGridUp.Top = dgvPluItem.Top;
                btnGridUp.Height = dgvPluItem.Height / 2;

                btnGridDown.Top = btnGridUp.Top + btnGridUp.Height;
                btnGridDown.Height = dgvPluItem.Height / 2;

                dgvPluItem.Rows.Clear();

                dgvPluItem.AllowUserToAddRows = false;
                dgvPluItem.EnableHeadersVisualStyles = false;
                dgvPluItem.RowsDefaultCellStyle.BackColor = Color.White;
                dgvPluItem.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(249, 249, 249);
                dgvPluItem.Font = this.Font;
                dgvPluItem.DefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 10);

                dgvPluItem.Font = new Font(m_cPosStatus.Base.FONT, 10);
                dgvPluItem.RowHeadersDefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 10);

                dgvPluItem.Columns[0].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0410);  //순번
                dgvPluItem.Columns[1].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0015);  //상품명
                dgvPluItem.Columns[2].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0302);  //take in
                dgvPluItem.Columns[3].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0303);  //take out
                dgvPluItem.Columns[4].HeaderText = "";                                                          //상품코드
                dgvPluItem.Columns[5].HeaderText = "";                                                          //rowseq
                dgvPluItem.Columns[6].HeaderText = "";                                                          //제조음료 Take In/Out 설정값
                dgvPluItem.Columns[7].HeaderText = "";                                                          //서브점포코드
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region Control Event
        private void dgvPluItem_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (dgvPluItem.CurrentCell != null)
                {
                    if (e.RowIndex == -1)
                    {
                        dgvPluItem.ClearSelection();
                        dgvPluItem.CurrentCell = null;

                        for (int iRow = 0; iRow < dgvPluItem.Rows.Count; iRow++)
                        {

                            TakeInOutPrcDisp(e.ColumnIndex, iRow);
                        }
                    }
                    else
                    {

                        TakeInOutPrcDisp(e.ColumnIndex, e.RowIndex);                        
                    }
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 버튼 입력 처리
        /// <summary>
        /// 버튼 입력 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Cosmos.UI.CsmButton)sender) == btn_AllTakeIn)
                {
                    dgvPluItem.ClearSelection();
                    dgvPluItem.CurrentCell = null;

                    for (int iRow = 0; iRow < dgvPluItem.Rows.Count; iRow++)
                    {

                        TakeInOutPrcDisp(2, iRow);
                    }
                }
                else if (((Cosmos.UI.CsmButton)sender) == btn_AllTakeOut)
                {
                    dgvPluItem.ClearSelection();
                    dgvPluItem.CurrentCell = null;

                    for (int iRow = 0; iRow < dgvPluItem.Rows.Count; iRow++)
                    {

                        TakeInOutPrcDisp(3, iRow);
                    }
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnSave)
                {
                    if (SaveData() == false) return;

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        /// <summary>
        /// 닫기
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion Control Event

        #region User Method

        /// <summary>
        /// 등록 상품 로드
        /// </summary>
        private void LoadItemToGridView()
        {
            try
            {
                int iRowSeq = 0;

                // 상품정보
                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);                

                for (int iLoop = 0; iLoop < aSaleItem.Count; iLoop++)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iLoop];
                    
                    int iRow = dgvPluItem.Rows.Add();

                    //지정취소 상품은 제외
                    if (cSaleItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cSaleItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL)
                    {
                        dgvPluItem.Rows[iRow].Visible = false; 
                        continue;
                    }
                    else
                    {
                        dgvPluItem.Rows[iRow].Visible = true;
                    }

                    //Take In/Out 설정이 필요한 제품이면 그리드에 표시
                    if (cSaleItem.PROD_TAKEINOUT_YN == "1")
                    {
                        dgvPluItem.Rows[iRow].Visible = true;
                    }
                    else
                    {
                        dgvPluItem.Rows[iRow].Visible = false;
                        continue;// 지정취소
                    }

                    iRowSeq++;

                    dgvPluItem.Rows[iRow].Cells[0].Value = iRowSeq;             // 순번
                    dgvPluItem.Rows[iRow].Cells[1].Value = cSaleItem.ITEM_NAME; // 상품명

                    //상품 배열에 설정된 데이터 우선 반영, 없다면 기본값 반영
                    if (cSaleItem.PROD_TAKEINOUT_DIV == PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_IN)
                    {
                        dgvPluItem.Rows[iRow].Cells[2].Value = true;
                        dgvPluItem.Rows[iRow].Cells[3].Value = false;
                        dgvPluItem.Rows[iRow].Cells[6].Value = PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_IN;    // 제조음료 Take In/Out 설정값
                    }
                    else if (cSaleItem.PROD_TAKEINOUT_DIV == PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_OUT)
	                {
                        dgvPluItem.Rows[iRow].Cells[2].Value = false;
                        dgvPluItem.Rows[iRow].Cells[3].Value = true;
                        dgvPluItem.Rows[iRow].Cells[6].Value = PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_OUT;    // 제조음료 Take In/Out 설정값
                    }
                    else if (m_cPosStatus.Base.ProdTakeInOutDiv == PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_IN)
                    {
                        dgvPluItem.Rows[iRow].Cells[2].Value = true;
                        dgvPluItem.Rows[iRow].Cells[3].Value = false;
                        dgvPluItem.Rows[iRow].Cells[6].Value = PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_IN;    // 제조음료 Take In/Out 설정값
                    }
                    else if (m_cPosStatus.Base.ProdTakeInOutDiv == PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_OUT)
                    {
                        dgvPluItem.Rows[iRow].Cells[2].Value = false;
                        dgvPluItem.Rows[iRow].Cells[3].Value = true;
                        dgvPluItem.Rows[iRow].Cells[6].Value = PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_OUT;    // 제조음료 Take In/Out 설정값
                    }

                    dgvPluItem.Rows[iRow].Cells[4].Value = cSaleItem.ITEM_PLU_CD;           // 상품코드
                    dgvPluItem.Rows[iRow].Cells[5].Value = iLoop;                           // rowseq
                    dgvPluItem.Rows[iRow].Cells[7].Value = cSaleItem.SUB_SHOP_CD;           // 서브점포코드
                }
                dgvPluItem.Refresh();

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }


        private void TakeInOutPrcDisp(int iColumnIndex ,int iRow)
        {
            try
            {
                //안보이는 row는 제외
                if (dgvPluItem.Rows[iRow].Visible == false) return;

                //Take In 컬럼 선택시
                if (iColumnIndex == 2)
                {
                    if (dgvPluItem.Rows[iRow].Cells[2].Value.Equals(false))
                    {
                        dgvPluItem.Rows[iRow].Cells[2].Value = true;
                        dgvPluItem.Rows[iRow].Cells[3].Value = false;
                        dgvPluItem.Rows[iRow].Cells[6].Value = PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_IN;
                    }

                }
                //Take Out 컬럼 선택시
                else if (iColumnIndex == 3)
                {
                    if (dgvPluItem.Rows[iRow].Cells[3].Value.Equals(false))
                    {
                        dgvPluItem.Rows[iRow].Cells[2].Value = false;
                        dgvPluItem.Rows[iRow].Cells[3].Value = true;
                        dgvPluItem.Rows[iRow].Cells[6].Value = PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_OUT;
                    }
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        private bool SaveData()
        {

            bool bRet = false;
            int sSelectPos = 0;
            string sMainItemCd = "";
            string sMainSubStorCd = "";
            string sSubItemCd = "";
            string sSubItemNm = "";

            int iAddCnt = 0;

            try
            {
                // 상품정보
                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                //그리드 돌면서 해당 상품에 부가상품으로 Take In/Out 추가
                for (int iRow = 0; iRow < dgvPluItem.Rows.Count; iRow++)
                {
                    //대상 상품이 아닌 경우 제외
                    if (dgvPluItem.Rows[iRow].Visible == false) continue;

                    //메인상품
                    sSelectPos = CmUtil.IntParse(dgvPluItem.Rows[iRow].Cells[5].Value.ToString());
                    //메인상품코드
                    sMainItemCd = dgvPluItem.Rows[iRow].Cells[4].Value.ToString();
                    //메인상품 서브점포코드
                    sMainSubStorCd = dgvPluItem.Rows[iRow].Cells[7].Value.ToString();

                    //Take In 선택된 상태인 경우
                    if (dgvPluItem.Rows[iRow].Cells[6].Value.ToString() == PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_IN)
                    {
                        sSubItemNm = "Take In";
                        sSubItemCd = "9901";
                    }
                    //Take Out 선택된 상태인 경우
                    else if (dgvPluItem.Rows[iRow].Cells[6].Value.ToString() == PosConst.PROD_TAKE_IN_OUT_DIV.PROD_TAKE_OUT)
                    {
                        sSubItemNm = "Take Out";
                        sSubItemCd = "9902";
                    }

                    // 메인 상품에 take in/out 값 설정
                    // 2019-04-19 - 1997fx11 : POS에서 Take In / Take Out 판매 데이터에 설정
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[sSelectPos + iAddCnt];
                    cSaleItem.PROD_TAKEINOUT_DIV = dgvPluItem.Rows[iRow].Cells[6].Value.ToString();

                    // 부가 상품 정보 생성
                    Column.TR_PLU.DATA cPluItem = new Column.TR_PLU.DATA();

                    cPluItem.SUB_SHOP_CD = sMainSubStorCd;
                    cPluItem.ITEM_PLU_CD = sSubItemCd;
                    cPluItem.ITEM_DIV = ItemConst.PLU_ITEM_DIV.OPT_MENU;
                    cPluItem.SALE_QTY = 1;
                    cPluItem.ITEM_NAME = ">>" + sSubItemNm;
                    cPluItem.SUBPRC_MENU_KEY_DIV = "1";    // 부가메뉴구분(1:속성,2:업차지,3:선택메뉴)
                    cPluItem.NONSALES_RSN_CD = "0";
                    cPluItem.NONSALES_RSN_NM = "";
                    cPluItem.SUB_MENU_MAIN_CD = sMainItemCd;
                    cPluItem.PROD_TAKEINOUT_DIV = dgvPluItem.Rows[iRow].Cells[6].Value.ToString();

                    if (sSelectPos >= dgvPluItem.Rows.Count - 1)
                    {
                        aSaleItem.Add(cPluItem);                    // 등록 처리
                    }
                    else
                    {
                        sSelectPos = sSelectPos + 1;
                        aSaleItem.Insert(sSelectPos + iAddCnt, cPluItem);        // 등록 처리
                        iAddCnt++;
                    }

                // 상품 판매가 계산
                //ItemAmountExeccute(true, true);
                }

                bRet = true;

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return bRet;
        }

        #endregion User Method

        #region DeviceEvent 관련
        /// <summary>
        /// DeviceEvent 관련
        /// </summary>
        /// <param name="sDevice"></param>
        /// <param name="sData1"></param>
        /// <param name="sData2"></param>
        /// <param name="sData3"></param>
        public void OnDeviceEvent(string sDevice, string sData1, string sData2, string sData3)
        {
            try
            {
                switch (sDevice)
                {
                    case PosConst.OPOS_DEVICE.MSR:
                        this.Invoke(new EventHandler(OnMSREvent));
                        break;
                    case PosConst.OPOS_DEVICE.SCANNER:
                        this.Invoke(new EventHandler(OnScannerEvent));
                        break;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        /// <summary>
        /// MSR Event
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnMSREvent(object source, EventArgs e)
        {

        }
        /// <summary>
        /// 스캐너 이벤트 처리
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnScannerEvent(object source, EventArgs e)
        {

        }
        #endregion


    }

}
