using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

namespace Cosmos.Win
{
    public partial class frmStoreEquipCheck : Form
    {
        #region 변수 선언
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private IStoreEquipCheck m_cStoreEquipCheck = null;                         // 일일점검리스트 조회
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출

        // 점검 상태 변수
        private string m_sCheckState = "0";
        #endregion 변수 선언

        #region 생성자 & 소멸자
        public frmStoreEquipCheck()
        {
            InitializeComponent();

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

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cStoreEquipCheck = (IStoreEquipCheck)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.STORE_EQUIP_CHECK);  // 일일점검리스트조회
        }

        private void frmStoreEquipCheck_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();

            // 점검항목 로드
            StoreCheckInfo();
        }

        private void frmStoreEquipCheck_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);
        }
        #endregion 생성자 & 소멸자

        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                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);
                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);
                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 = "";

                btnUp.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP1_BASIC);
                btnUp.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP1_PRESS);

                btnDn.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_DOWN1_BASIC);
                btnDn.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_DOWN1_PRESS);

                // 라벨 이름 설정
                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0965);

                // 버튼 이름 설정
                btnSave.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0225);
                btnCancel.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0010);

                // 일일점검 상세 리스트 그리드 초기화
                SetListColumn();

            }
            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>
        /// 일일점검 리스트 DataGridView 초기화
        /// </summary>
        private void SetListColumn()
        {
            try
            {
                int[] arColumnsWidth = { 100, 150, 305, 100, 100, 0, 0, 0, 0 }; //컬럼넓이 지정(755)
                int[] arColumnsAlignment = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

                dgvCheckList.Columns.Clear();
                dgvCheckList.Rows.Clear();

                dgvCheckList.Columns.Add("FLAG", MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0532));
                dgvCheckList.Columns.Add("EQUIP", MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0968));
                dgvCheckList.Columns.Add("CHECK_LIST", MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0969));
                dgvCheckList.Columns.Add("CHECK1", MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0970));
                dgvCheckList.Columns.Add("CHECK2", "");
                dgvCheckList.Columns.Add("CHECK_MSG", "");
                dgvCheckList.Columns.Add("CHECK_RET", "");
                dgvCheckList.Columns.Add("CHECK_DIV_CD", "");
                dgvCheckList.Columns.Add("CHECK_EQU_CD", "");

                dgvCheckList.ColumnHeadersHeight = 40;
                dgvCheckList.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
                dgvCheckList.RowHeadersVisible = false;
                dgvCheckList.AllowUserToAddRows = false;
                dgvCheckList.Font = new Font(m_cPosStatus.Base.FONT, 12);
                dgvCheckList.RowTemplate.Height = 40;

                for (int nLoop = 0; nLoop < dgvCheckList.Columns.Count; nLoop++)
                {
                    dgvCheckList.Columns[nLoop].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    dgvCheckList.Columns[nLoop].Width = arColumnsWidth[nLoop];
                    dgvCheckList.Columns[nLoop].Resizable = DataGridViewTriState.False;

                    if (nLoop == 0 || nLoop == 1 || nLoop == 2)
                    {
                        dgvCheckList.Columns[nLoop].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                        dgvCheckList.Columns[nLoop].ReadOnly = true;
                    }
                    else if (nLoop >= 5)
                    {
                        dgvCheckList.Columns[nLoop].Visible = false;
                    }

                    switch (arColumnsAlignment[nLoop])
                    {
                        case 0:
                            dgvCheckList.Columns[nLoop].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
                            break;
                        case 1:
                            dgvCheckList.Columns[nLoop].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                            break;
                        default:
                            dgvCheckList.Columns[nLoop].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                            break;
                    }

                    dgvCheckList.Columns[nLoop].SortMode = DataGridViewColumnSortMode.NotSortable;
                }

            }
            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
        /// <summary>
        /// 조회 그리드 업/다운 클릭 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelProc_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvCheckList.Rows.Count == 0) return;

                int nRow = dgvCheckList.CurrentRow.Index;

                if ((UI.CsmButton)sender == btnUp)                               // 상단 그리드 Up
                {
                    if (nRow > 0)
                    {
                        nRow--;
                        dgvCheckList.Rows[nRow].Selected = true;
                        dgvCheckList.Rows[nRow].Cells[dgvCheckList.CurrentCell.ColumnIndex].Selected = true;
                    }
                }
                else if ((UI.CsmButton)sender == btnDn)                          // 상단 그리드 Down
                {
                    if (nRow < dgvCheckList.Rows.Count - 1)
                    {
                        nRow++;
                        dgvCheckList.Rows[nRow].Selected = true;
                        dgvCheckList.Rows[nRow].Cells[dgvCheckList.CurrentCell.ColumnIndex].Selected = 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);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // 빠짐없이 입력됐는지 체크
            if (AllCheck() == true)
            {
                // Loacl 저장
                StoreCheckSave();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvCheckList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (dgvCheckList.RowCount <= 0 || e.RowIndex < 0) return;

                int nRow = e.RowIndex;

                // 라디오 박스
                int nCol = e.ColumnIndex;
                if ((nCol == 3 || nCol == 4) && dgvCheckList.Rows[nRow].Cells[nCol].Value.ToString() != "")
                {
                    string[] sEntryName = dgvCheckList.Rows[nRow].Cells[5].Value.ToString().Split('|');

                    if (sEntryName[0] != "") dgvCheckList.Rows[nRow].Cells[3].Value = (nCol == 3 ? "● " : "○ ") + sEntryName[0];
                    if (sEntryName[1] != "") dgvCheckList.Rows[nRow].Cells[4].Value = (nCol == 4 ? "● " : "○ ") + sEntryName[1];

                    dgvCheckList.Rows[nRow].Cells[6].Value = (nCol == 3 ? "1" : "2");
                }
            }
            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 btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvCheckList_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            try
            {
                if (e.RowIndex < dgvCheckList.RowCount - 1)
                    e.AdvancedBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.None;
                else
                    e.AdvancedBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.Single;

                if (e.RowIndex == 0 || (e.ColumnIndex != 0 && e.ColumnIndex != 1))
                {
                    e.AdvancedBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.Single;
                }
                else
                {
                    if (e.Value.ToString() == "")
                    {
                        e.AdvancedBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.None;
                    }
                    else
                    {
                        e.AdvancedBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.Single;
                    }
                }

                if (e.ColumnIndex == 3 || e.ColumnIndex == 4)
                {
                    e.AdvancedBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.None;
                }
            }
            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
        private void StoreCheckInfo()
        {
            string sEntryName = "";
            string sGood = "";
            string sBad = "";

            try
            {
                DataTable dtData = new DataTable();

                dtData = (DataTable)m_cStoreEquipCheck.SearchStoreEquipCheckInfo();

                if (dtData == null || dtData.Rows.Count == 0) return;

                sGood = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0990);
                sBad = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0991);

                for (int nLoop = 0; nLoop < dtData.Rows.Count; nLoop++)
                {

                    // 라디오 박스
                    int iRow = dgvCheckList.Rows.Add();
                    dgvCheckList.Rows[iRow].Cells[0].Value = CmUtil.GetDataRowStr(dtData.Rows[nLoop], "CD_NM1");
                    dgvCheckList.Rows[iRow].Cells[1].Value = CmUtil.GetDataRowStr(dtData.Rows[nLoop], "CD_NM2");
                    dgvCheckList.Rows[iRow].Cells[2].Value = CmUtil.GetDataRowStr(dtData.Rows[nLoop], "EXPLN");

                    sEntryName = "";

                    sEntryName = sGood + "|";
                    dgvCheckList.Rows[iRow].Cells[3].Value = "○ " + sGood;
                    dgvCheckList.Rows[iRow].Cells[3].ReadOnly = true;

                    sEntryName += sBad + "|";
                    dgvCheckList.Rows[iRow].Cells[4].Value = "○ " + sBad;
                    dgvCheckList.Rows[iRow].Cells[4].ReadOnly = true;

                    dgvCheckList.Rows[iRow].Cells[5].Value = sEntryName;
                    dgvCheckList.Rows[iRow].Cells[6].Value = "0";

                    dgvCheckList.Rows[iRow].Cells[7].Value = CmUtil.GetDataRowStr(dtData.Rows[nLoop], "CMM_CD");
                    dgvCheckList.Rows[iRow].Cells[8].Value = CmUtil.GetDataRowStr(dtData.Rows[nLoop], "CHAR_VAL_TITLE_VAL_01");
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        /// <summary>
        /// 체크리스트 체크 항목 필요
        /// </summary>
        /// <returns></returns>
        private bool AllCheck()
        {
            bool bRet = false;
            int nCnt = 0;

            m_sCheckState = "1"; // 항목별 점검 상태 (이상무)

            try
            {
                if (dgvCheckList.RowCount <= 0)
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0435));
                    return bRet;
                }

                for (int iRow = 0; iRow < dgvCheckList.RowCount; iRow++)
                {
                    // 라디오 버튼
                    if (dgvCheckList.Rows[iRow].Cells[6].Value.ToString() == "0")
                    {
                        nCnt++;
                    }

                    if (dgvCheckList.Rows[iRow].Cells[6].Value.ToString() == "2")
                    {
                        // 불량이 있을 경우
                        m_sCheckState = "2";
                    }
                }

                if (nCnt > 0)
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0436));
                    return bRet;
                }

                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;

        }

        /// <summary>
        /// 점포 점검 내역 저장
        /// </summary>
        /// <returns></returns>
        private void StoreCheckSave()
        {
            string sRet = UserCom.RST_ERR;
            string sInsertUpdate = string.Empty;

            try
            {
                if (dgvCheckList.RowCount <= 0) return;

                string sRegUserId = m_cPosStatus.Base.CashierNo;

                // 점포 점검 리스트(헤더)
                DataTable dtData1 = new DataTable();
                dtData1.Columns.Add(new DataColumn("SALE_DT", typeof(string)));
                dtData1.Columns.Add(new DataColumn("CHECK_STATE", typeof(string)));
                dtData1.Columns.Add(new DataColumn("REG_USER_ID", typeof(string)));

                // 점포 점검 리스트(디테일)
                DataTable dtData2 = new DataTable();
                dtData2.Columns.Add(new DataColumn("SALE_DT", typeof(string)));
                dtData2.Columns.Add(new DataColumn("CHECK_DIV_CD", typeof(string)));
                dtData2.Columns.Add(new DataColumn("CHECK_EQU_CD", typeof(string)));
                dtData2.Columns.Add(new DataColumn("CHECK_RESULT", typeof(string)));
                dtData2.Columns.Add(new DataColumn("REG_USER_ID", typeof(string)));
                dtData2.Columns.Add(new DataColumn("AS_RESULT", typeof(string)));
                dtData2.Columns.Add(new DataColumn("STOR_RESULT", typeof(string)));


                // 점포점검 마스터 헤더 값 설정
                DataRow dr1 = dtData1.NewRow();
                dr1["SALE_DT"] = m_cPosStatus.Global.CultureToDate(m_cPosStatus.Base.SaleDate);
                dr1["CHECK_STATE"] = m_sCheckState;
                dr1["REG_USER_ID"] = sRegUserId;   //cbCashierName.ValueMember;

                dtData1.Rows.Add(dr1);

                for (int i = 0; i < dgvCheckList.RowCount; i++)
                {
                    DataRow dr2 = dtData2.NewRow();
                    dr2["SALE_DT"] = m_cPosStatus.Global.CultureToDate(m_cPosStatus.Base.SaleDate);

                    dr2["CHECK_RESULT"] = ((string)dgvCheckList.Rows[i].Cells[6].Value);
                    dr2["CHECK_DIV_CD"] = ((string)dgvCheckList.Rows[i].Cells[8].Value);
                    dr2["CHECK_EQU_CD"] = ((string)dgvCheckList.Rows[i].Cells[7].Value);
                    dr2["AS_RESULT"] = "0";
                    dr2["STOR_RESULT"] = "0";

                    dr2["REG_USER_ID"] = sRegUserId;   //cbCashierName.ValueMember;

                    dtData2.Rows.Add(dr2);
                }

                sRet = m_cStoreEquipCheck.StoreCheckSave(dtData1, dtData2);
                if (sRet == UserCom.RST_OK)
                {
                    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);
            }
        }
        #endregion User Method
    }
}
