using System;
using System.Collections.Generic;
using System.Windows.Forms;
using CLIP.eForm.Consent.UI.HospitalSvcRef;

namespace CLIP.eForm.Consent.UI
{
    /// <summary>
    /// 환자목록 > 환자검색 팝업창 클래스
    /// </summary>
    /// <remarks>
    /// <p>[설계자]</p>
    /// <p>  클립소프트 연구소 홍지철 (jchong@clipsoft.co.kr)</p>
    /// <p>[수정 작성자]</p>
    /// <p>  클립소프트 기술부 이인희</p>
    /// <p>----------------------------------------------------------------------------------------</p>
    /// <p>[HISTORY]</p>
    /// <p> 2016-07-11 : 최초작성</p>
    /// <p>----------------------------------------------------------------------------------------</p>
    /// </remarks>  
    public partial class PatientSearchPopup : Form
    {
        private HospitalSvcRef.HospitalSvcSoapClient hospitalWebService = null;
        private string strSearchText = "";  //검색어
        private string dutinstcd = "";
        private string m_ServerName = string.Empty;
        
        //선택된 환자 등록번호
        public string PatientID
        {
            get { return strSearchText; }
            set { strSearchText = value; }
        }

        /// <summary>
        /// 환자검색 팝업 생성자.
        /// 경북대학교병원에서는 근무지기관코드가 필요하므로
        /// 경북대학교병원에서 사용할 경우 PatientSearchPopup(string, string)
        /// 타입의 생성자를 사용하십시요
        /// </summary>
        [Obsolete("이 생성자는 근무지기관코드가 추가되지 않았으므로 경북대학교병원에서는 사용하지 마십시요.")]
        public PatientSearchPopup()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 환자검색 팝업 생성자.
        /// 경북대학교병원에서는 근무지기관코드가 필요하므로
        /// 경북대학교병원에서 사용할 경우 PatientSearchPopup(string, string)
        /// 타입의 생성자를 사용하십시요
        /// </summary>
        /// <param name="searchText"></param>
        [Obsolete("이 생성자는 근무지기관코드가 추가되지 않았으므로 경북대학교병원에서는 사용하지 마십시요.")]
        public PatientSearchPopup(string searchText)
        {
            InitializeComponent();

            strSearchText = searchText;
        }

        public PatientSearchPopup(string searchText, string dutinstcd, string p_ServerName) {
            InitializeComponent();

            strSearchText = searchText;
            this.dutinstcd = dutinstcd;
            m_ServerName = p_ServerName;
        }

        private void PatientSearchPopup_Load(object sender, EventArgs e)
        {
            if (this.DesignMode)
            {
                return;
            }

            Dictionary<string, string> configDic = ConsentMainControl.GetConfigDictionary(m_ServerName);
            hospitalWebService = WebMethodCommon.GetHospitalWebService(configDic["hospitalSvcUrl"]);

            InitDataGrid();
            InitSearchCondition(); 
        }

        private void InitSearchCondition()
        {
            Dictionary<string, string> comboItems = new Dictionary<string, string>();
            comboItems.Add("등록번호", "1");
            comboItems.Add("환자명", "2");
            comboItems.Add("주민번호", "3");

            comboSearchType.DataSource = new BindingSource(comboItems, null);
            comboSearchType.DisplayMember = "Key";
            comboSearchType.ValueMember = "Value";


            this.textboxSearchText.Text = strSearchText;

            if (strSearchText.Length > 0)
            {
                int iResult = 0;
                if (int.TryParse(strSearchText, out iResult))
                    this.comboSearchType.SelectedIndex = 0;
                else
                    this.comboSearchType.SelectedIndex = 1;

                this.buttonPatientSelect.PerformClick();
            }
        }

        private void InitDataGrid()
        {
            this.dataGridViewPatientSelectResult.AutoGenerateColumns = false;
            this.dataGridViewPatientSelectResult.AllowUserToAddRows = false;
            this.dataGridViewPatientSelectResult.CellClick += new DataGridViewCellEventHandler(dataGridViewPatientSelectResult_CellClick);
            
            CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "등록번호", "pid", true, 100);
            //CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "합번", "Gubun", true, 80);
            CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "환자성명", "hngnm", true, 100);
            CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "나이", "age", true, 80);
            CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "주민등록번호", "rrgstno1", true, 100);
            CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "주민등록번호", "rrgstno2", true, 100);
            CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "주소", "addr", true, 100);
            CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "휴대전화번호", "mpphontel", true, 120);
            CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "최근보험유형", "lastinsukind", true, 100);
            CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "최근내원일", "lastorddd", true, 100);
            //CommonUtil.AddNewColumnToDataGridView(this.dataGridViewPatientSelectResult, "spcendcnt", "ClnDoctor", true, 100);
        }

        /// <summary>
        /// 환자목록을 조회하여 그리드에 매핑
        /// </summary>
        private void BindDataGridRows()
        {
            string srchcond = this.comboSearchType.SelectedValue.ToString();
            string pid = "";
            string hngnm = "";
            string rrgstno1 = "";
            string rrgstno2 = "";

            if (srchcond == "1")
            {
                pid = this.textboxSearchText.Text.Trim();
            }
            else if (srchcond == "2")
            {
                hngnm = this.textboxSearchText.Text.Trim();
            }
            else if (srchcond == "3")
            {
                string temp = this.textboxSearchText.Text.Trim();
                rrgstno1 = (temp.Length > 6) ? temp.Substring(0, 6) : temp;
                rrgstno2 = (temp.Length > 6) ? temp.Substring(6) : "";
            }

            PatInfoListVO [] resultData = hospitalWebService.GetSrchPatInfo(srchcond, pid, hngnm, rrgstno1, rrgstno2, this.dutinstcd);

            if (resultData == null)
            {
                return;
            }

            this.dataGridViewPatientSelectResult.DataSource = new SortableBindingList<PatInfoListVO>(resultData);            
        }
        
        private void comboSearchType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.textboxSearchText.Focus();
        }

        /// <summary>
        /// 검색조건 입력 컨트롤 키보드 입력 이벤트
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
        private void textboxSearchText_KeyDown(object sender, KeyEventArgs e)
        {
            // 엔터키 입력 시 조회
            if (e.KeyCode == Keys.Enter)
                this.buttonPatientSelect.PerformClick();
        }

        /// <summary>
        /// 조회 버튼 클릭 이벤트
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void buttonPatientSelect_Click(object sender, EventArgs e)
        {
            // 조회 조건이 있을경우
            if (this.textboxSearchText.Text.Trim().Length > 0) {
                BindDataGridRows();
            }
            // 조회 조건이 없을 경우
            else {
                MessageBox.Show(string.Format(Properties.Resources.msg_error_search_args)
                                               , string.Format(Properties.Resources.msg_caption_confirm),
                                                       MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void dataGridViewPatientSelectResult_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.RowIndex < 0)
            {
                return;
            }

            PatInfoListVO vo = this.dataGridViewPatientSelectResult.Rows[e.RowIndex].DataBoundItem as PatInfoListVO;

            if (vo != null)
            {
                strSearchText = vo.pid;
                // 오버라이딩 메서드가 없기 때문에 클릭 이벤트 시 기본 동작만 수행
                this.buttonOK.PerformClick();
            }
        }
    }
}
