using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using util = FCOMMON.Util;


namespace FED0000
{
    public partial class fLicenseList : FCOMMON.fBase
    {
        string fn_fpcolsize = "";

        public fLicenseList()
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;
            Properties.Settings.Default["EEEntities"] = FCOMMON.info.CS;

            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.dsPurchase.EETGW_License.TableNewRow += Purchase_TableNewRow;
            this.FormClosing += FPurchase_FormClosing;
            this.FormClosed += __Closed;
        }

        private void FPurchase_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (dsPurchase.HasChanges())
            {
                var dlg = FCOMMON.Util.MsgQ("변경된 자료가 있습니다. 화면을 닫을까요? 닫으면 변경된 자료는 손실 됩니다");
                if (dlg != DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }


        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

        void Purchase_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            e.Row["sdate"] = DateTime.Now.ToString("yyyy-MM-dd");
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;

        }

        private void __Load(object sender, EventArgs e)
        {


            EnsureVisibleAndUsableSize();
            refreshData();

        }


        private void refreshData()
        {

            try
            {

                this.ta.Fill(this.dsPurchase.EETGW_License, FCOMMON.info.Login.gcode);
                //FCOMMON.Util.FPColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

            FormattingData();
        }
        void FormattingData()
        {

        }

        Font fBase = new Font("맑은 고딕", 9);
        Font fBold = new Font("맑은 고딕", 9, FontStyle.Bold);

        private void saveData(Boolean prompt)
        {
            this.Validate();
            this.bs.EndEdit();
            try
            {
                var cnt = this.ta.Update(this.dsPurchase);
                if (prompt) FCOMMON.Util.MsgI(string.Format("{0}건의 자료가 저장 되었습니다.", cnt));
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("저장 실패\n" + ex.Message);
            }


        }


        private void btSearch_Click(object sender, EventArgs e)
        {
            refreshData();
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            func_add();
        }

        private void tbRequest_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btSearch.PerformClick();
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            saveData(true);
        }



        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            func_delete();
        }
        void func_add()
        {
            var newdr = this.bs.AddNew();
            this.bs.Position = this.bs.Count - 1;


        }
        void func_delete()
        {
            var drv = bs.Current as DataRowView;
            if (drv == null) return;

            //삭제기능구현필요
        }


        private void btFind_Click(object sender, EventArgs e)
        {
            var dv = this.dv1;
            var cols = new List<string>();
            foreach (DataGridViewColumn col in dv.Columns)
            {
                if (col.Visible == false || col.DataPropertyName.isEmpty()) continue;
                if (col.ValueType == typeof(bool)) continue;
                if (col.ValueType == typeof(Int32)) continue;
                cols.Add(col.DataPropertyName);
            }

            var search = tbFind.Text.Trim();
            search = search.Replace("*", "x");
            string filter = string.Empty;
            if (tbFind.Text != search) tbFind.Text = search;
            try
            {
                if (search.isEmpty())
                {
                    this.bs.Filter = "";
                    tbFind.BackColor = Color.White;
                }
                else
                {
                    search = search.Replace("'", "''");
                    filter = string.Join(" like ? or ", cols.ToArray());
                    filter = filter.Replace("?", "'%" + search + "%'");
                    filter += " like '%" + search + "%'";
                    this.bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                tbFind.SelectAll();
                tbFind.Focus();
            }
            catch (Exception ex)
            {
                this.tbFind.BackColor = Color.Tomato;
                FCOMMON.Util.MsgE(ex.Message + "\n" + filter);
            }
        }

        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) btFind.PerformClick();
        }

        private void editDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Func_Edit();
        }
        void Func_Edit()
        {


        }

        private void autoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //  FCOMMON.Util.FPColSizeAuto(this.fpSpread1);
            //this.fpSpread1.ActiveSheet.DataAutoSizeColumns = true;

            //for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            //    this.fpSpread1.ActiveSheet.SetRowHeight(i, 25);
            //dv1.AutoResizeColumns();
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //foreach (FarPoint.Win.Spread.Column col in this.fpSpread1.ActiveSheet.Columns)
            //{
            //    col.Width = 100;
            //}
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {//
         // FCOMMON.Util.FPColsizeSave(this.fpSpread1, fn_fpcolsize);
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // FCOMMON.Util.FPColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Func_Edit();
        }


        void dv1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
            //var state = this.dv1.Rows[e.RowIndex].Cells["dvc_state"].Value.ToString();
            //switch (state)
            //{
            //    case "00":  //입력대기(미확인)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightGray;
            //        break;
            //    case "01":  //파트장 승인 기다림
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.DarkBlue;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        break;
            //    case "03":  //PO (협력업체 전달)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.DarkMagenta;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        break;
            //    case "04":  //자재 수령
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Green;
            //        break;
            //    case "05": //canceld (취소)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightGray;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Red;
            //        break;
            //    case "06":  //cancel (취소됨)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.HotPink;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
            //        break;
            //    case "08":  //문의
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Green;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.White;
            //        break;
            //    default:
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
            //        break;
            //}
        }

        private void updateSCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dlg = FCOMMON.Util.MsgQ("#SC가 없는 자료에 한하여 일괄 기록을 실행 합니다.");
            if (dlg == System.Windows.Forms.DialogResult.Yes)
            {

            }
        }

        private void exportDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "csv|*.csv";
            sd.FileName = "edulist.csv";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dv1.ExportData(sd.FileName, false);
                //fpSpread1.SaveExcel(sd.FileName,
                //    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                //    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                //    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                //    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
                FCOMMON.Util.MsgI("다음 파일이 생성 되었습니다.\n\n" + sd.FileName);
            }

        }



        private void btViewDel_Click(object sender, EventArgs e)
        {
            refreshData();
        }


        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        void func_copy()
        {
            //복사기능 구현해야함
        }



        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null)
            {
                this.label1.Text = "데이터가 선택되지 않았습니다";
                return;
            }
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {

        }

        string getmaxstr(string src, int len = 30)
        {
            if (src.Length > len) return src.Substring(0, len) + "...";
            else return src;
        }

        List<string> ChangeMailAddress(List<string> userid)
        {
            var db = new DataClasses1DataContext();

            List<string> retval = new List<string>();
            foreach (var id in userid)
            {
                UInt32 userno;
                if (UInt32.TryParse(id, out userno) == true)
                {
                    var user = db.Users.Where(t => t.id == id).FirstOrDefault();
                    if (user != null)
                    {
                        var data = string.Format("{0}<{1}>", user.name, user.email);
                        if (retval.Contains(data) == false)
                            retval.Add(data);
                    }
                }
                else
                {
                    if (retval.Contains(id) == false)
                        retval.Add(id);
                }
            }
            return retval;
        }

        private void toolStripButton3_Click_1(object sender, EventArgs e)
        {
            var fn = System.IO.Path.Combine(FCOMMON.Util.CurrentPath, "PurcManual.pdf");
            if (System.IO.File.Exists(fn))
            {
                FCOMMON.Util.RunExplorer(fn);
            }
            else FCOMMON.Util.MsgE("설명서 파일(manual.pdf)이 없습니다. 개발자 문의 해주세요(chikyun.kim@amkor.co.kr)");
        }

        private void fpSpread1_EditModeOff(object sender, EventArgs e)
        {

        }

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

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //open path

            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as EEDataSet.EETGW_LicenseRow;
            if (dr.RowState == DataRowState.Added || dr.RowState == DataRowState.Detached)
            {
                FCOMMON.Util.MsgE("자료가 저장된 후 폴더열기를 사용할 수 있습니다");
                return;
            }

            FCOMMON.Util.OpenSharedPath(null, "Data", "License", dr.idx.ToString());

        }
    }
}
