// 下水データ管理システム
// Copyright (C) 2018 公益財団法人とちぎ建設技術センター(https://www.tochigictc.or.jp/)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.If not, see<http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SQLite;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace WindowsFormsApplication1 {
    public partial class Form32PrintPreviewGraph : Form30PrintPreviewBase {
        public Form32PrintPreviewGraph() {
            InitializeComponent();
        }


        public DataGridView dataGridView1 { get; set; }
        public ComboBox comboBox1 { get; set; }
        public ComboBox comboBox2 { get; set; }

        List<ColumnConfig> ccSet = ColumnsConfigSet.getSet;

        BindingList<SelectableMonth> CBStMonthItem = new BindingList<SelectableMonth>();
        BindingList<SelectableSpan> CBSpanItem = new BindingList<SelectableSpan>();
        BindingList<SelectableMonth> CBEdMonthItem = new BindingList<SelectableMonth>();

        DateTime timeSpanSt = new DateTime();
        DateTime timeSpanEd = new DateTime();
        int spanDays = 0;
        int selectedStY = 0;
        int selectedStM = 0;
        int selectedEdY = 0;
        int selectedEdM = 0;

        Color seriesEnable = Color.Black;
        Color seriesEnableBC = Color.White;
        Color seriesDisable = Color.Gray;
        Color seriesDisableBC = Color.Gainsboro;

        graphSeries[] graphSerieses = new graphSeries[PrintContainer.graphSeriesNo];




        //ロード時イベント
        private void Form32PrintPreviewGraph_Load(object sender, EventArgs e) {
            CBStMonthInitialize();
            makeInputForm();
            setLandscape();
            viewPrintPreview();
        }




        //入力フォーム作成
        private void makeInputForm() {
            for(int i = 1; i < PrintContainer.graphSeriesNo; i++) {
                graphSerieses[i] = new graphSeries();

                Label newLabel1 = new Label();
                newLabel1.Name = "labelSeries" + i.ToString() + "1";
                newLabel1.Text = "系列" + i.ToString();
                newLabel1.Size = new Size(230, 15);
                newLabel1.Location = new Point(0, 1);
                newLabel1.TextAlign = ContentAlignment.MiddleLeft;
                newLabel1.ForeColor = seriesDisable;
                
                panel1.Controls["panelSeries" + i.ToString()].Controls.Add(newLabel1);

                Label newLabel2 = new Label();
                newLabel2.Name = "labelSeries" + i.ToString() + "2";
                newLabel2.Size = new Size(230, 15);
                newLabel2.Location = new Point(0, 17);
                newLabel2.TextAlign = ContentAlignment.MiddleLeft;

                panel1.Controls["panelSeries" + i.ToString()].Controls.Add(newLabel2);

                Label newLabel3 = new Label();
                newLabel3.Name = "labelSeries" + i.ToString() + "3";
                newLabel3.Size = new Size(280, 15);
                newLabel3.Location = new Point(0, 33);
                newLabel3.TextAlign = ContentAlignment.MiddleLeft;

                panel1.Controls["panelSeries" + i.ToString()].Controls.Add(newLabel3);
                
                Button newButton1 = new Button();
                newButton1.Name = "buttonSeries" + i.ToString();
                newButton1.BackColor = Color.White;
                newButton1.Location = new Point(232, 2);
                newButton1.Size = new Size(50, 25);
                newButton1.Text = "追加";
                newButton1.UseVisualStyleBackColor = false;

                if(i != 1) {
                    newButton1.Visible = false;
                }

                newButton1.Click += new EventHandler(buttonSeries_Click);

                panel1.Controls["panelSeries" + i.ToString()].Controls.Add(newButton1);
            }
        }




        //開始月選択ボックス初期化
        private void CBStMonthInitialize() {
            CBStMonth.DisplayMember = "selectionName";
            CBStMonth.ValueMember = "primaryKey";
            CBStMonth.DataSource = CBStMonthItem;
            CBStMonth.BeginUpdate();

            CBStMonthItem.Clear();

            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                using(var cmd = con.CreateCommand()) {
                    cmd.CommandText = "SELECT MIN(sokutei_dt) AS min_dt, MAX(sokutei_dt) AS max_dt FROM suishitsu_kanri WHERE del_flg IS NULL;";

                    using(var reader = cmd.ExecuteReader()) {
                        if(reader.Read()) {
                            DateTime minDt = DateTime.Parse(reader.GetString(0));
                            DateTime maxDt = DateTime.Parse(reader.GetString(1));

                            DateTime stDt = DateTime.Parse(minDt.Year.ToString() + "/" + minDt.Month.ToString() + "/1");
                            DateTime edDt = DateTime.Parse(maxDt.Year.ToString() + "/" + maxDt.Month.ToString() + "/1");

                            CBStMonthItem.Add(new SelectableMonth(0, 0));

                            int i = 1;
                            int c = 0;
                            for(DateTime cDt = stDt; cDt <= edDt; cDt = cDt.AddMonths(1)) {
                                DateTime cnDt = cDt.AddMonths(1);
                                CBStMonthItem.Add(new SelectableMonth(cDt.Year, cDt.Month));

                                if(cDt.Year == DateTime.Now.Year && cDt.Month == DateTime.Now.Month) {
                                    c = i;
                                }

                                i++;
                            }

                            if(i > 1) {
                                CBStMonth.SelectedIndex = c;
                                CBStMonth.Enabled = true;
                                CBStMonth.BackColor = Color.White;
                            }
                            else {
                                CBStMonth.Enabled = false;
                                CBStMonth.BackColor = Color.Gainsboro;
                            }
                        }
                    }
                }
            }
            CBStMonth.EndUpdate();

            selectedStY = DateTime.Now.Year;
            selectedStM = DateTime.Now.Month;

            CBSpanSelectSet();
            setTimeSpan();

            CBStMonth.SelectionChangeCommitted += new EventHandler(CBStMonth_SelectionChangeCommitted);
            CBSpan.SelectionChangeCommitted += new EventHandler(CBSpan_SelectionChangeCommitted);
            CBEdMonth.SelectionChangeCommitted += new EventHandler(CBEdMonth_SelectionChangeCommitted);
        }




        //期間選択ボックス設定
        private void CBSpanSelectSet() {
            CBSpan.DisplayMember = "selectionName";
            CBSpan.ValueMember = "months";
            CBSpan.DataSource = CBSpanItem;

            if(selectedStY == 0 && selectedStM == 0) {
                //開始月が全期間
                CBSpanItem.Clear();
                CBSpan.Enabled = false;
                CBSpan.BackColor = Color.Gainsboro;
                CBEdMonthItem.Clear();
                CBEdMonth.Enabled = false;
                CBEdMonth.BackColor = Color.Gainsboro;
            }
            else {
                if(!CBSpan.Enabled) {
                    CBSpanItem.Add(new SelectableSpan(1));
                    CBSpanItem.Add(new SelectableSpan(3));
                    CBSpanItem.Add(new SelectableSpan(6));
                    CBSpanItem.Add(new SelectableSpan(12));
                    CBSpanItem.Add(new SelectableSpan(36));
                    CBSpanItem.Add(new SelectableSpan(60));
                    CBSpanItem.Add(new SelectableSpan(120));
                    CBSpanItem.Add(new SelectableSpan(0));

                    CBSpan.SelectedIndex = 0;
                    CBSpan.Enabled = true;
                    CBSpan.BackColor = Color.White;
                }

                CBEdMonthSelectSet();
            }
        }




        //終了月選択ボックス設定
        private void CBEdMonthSelectSet() {
            CBEdMonth.DisplayMember = "selectionName";
            CBEdMonth.ValueMember = "primaryKey";
            CBEdMonth.DataSource = CBEdMonthItem;

            CBEdMonthItem.Clear();

            SelectableSpan CBSpanSelectedItem = (SelectableSpan)CBSpan.SelectedItem;

            if(CBSpanSelectedItem == null) {
                CBEdMonth.BackColor = Color.Gainsboro;
                CBEdMonth.Enabled = false;
                return;
            }
            
            if(CBSpanSelectedItem.months != 0) {
                CBEdMonth.BackColor = Color.Gainsboro;
                CBEdMonth.Enabled = false;
                return;
            }
            
            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                using(var cmd = con.CreateCommand()) {
                    cmd.CommandText = "SELECT MIN(sokutei_dt) AS min_dt, MAX(sokutei_dt) AS max_dt FROM suishitsu_kanri WHERE del_flg IS NULL;";

                    using(var reader = cmd.ExecuteReader()) {
                        if(reader.Read()) {
                            SelectableMonth CBStMonthSelectedItem = (SelectableMonth)CBStMonth.SelectedItem;
                            int cDtY = CBStMonthSelectedItem.primaryKey(0);
                            int cDtM = CBStMonthSelectedItem.primaryKey(1);

                            DateTime maxDt = DateTime.Parse(reader.GetString(1));

                            DateTime stDt = DateTime.Parse(cDtY + "/" + cDtM + "/1");
                            DateTime edDt = DateTime.Parse(maxDt.Year.ToString() + "/" + maxDt.Month.ToString() + "/1");

                            int i = 0;
                            int c = 0;
                            for(DateTime cDt = stDt; cDt <= edDt; cDt = cDt.AddMonths(1)) {
                                DateTime cnDt = cDt.AddMonths(1);
                                CBEdMonthItem.Add(new SelectableMonth(cDt.Year, cDt.Month));

                                if(cDt.Year == selectedEdY && cDt.Month == selectedEdM) {
                                    c = i;
                                }

                                i++;
                            }

                            if(i > 1) {
                                CBEdMonth.SelectedIndex = c;
                                CBEdMonth.BackColor = Color.White;
                                CBEdMonth.Enabled = true;
                            }
                            else {
                                CBEdMonth.BackColor = Color.Gainsboro;
                                CBEdMonth.Enabled = false;
                            }
                        }
                    }
                }
            }
        }




        //開始月選択ボックスのユーザーによる変更イベント
        private void CBStMonth_SelectionChangeCommitted(object sender, EventArgs e) {
            SelectableMonth item1 = (SelectableMonth)CBStMonth.SelectedItem;
            selectedStY = item1.primaryKey(0);
            selectedStM = item1.primaryKey(1);

            CBSpanSelectSet();
            setTimeSpan();
        }




        //期間選択ボックスユーザーによる変更イベント
        private void CBSpan_SelectionChangeCommitted(object sender, EventArgs e) {
            CBEdMonthSelectSet();
            setTimeSpan();
        }




        //終了月選択ボックスユーザーによる変更イベント
        private void CBEdMonth_SelectionChangeCommitted(object sender, EventArgs e) {
            setTimeSpan();
        }

        
        
        
        //表示期間月日の設定
        private void setTimeSpan() {
            if(selectedStY == 0 && selectedStM == 0) {
                //全期間
                using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                    con.Open();

                    using(var cmd = con.CreateCommand()) {
                        cmd.CommandText = "SELECT MIN(sokutei_dt) AS min_dt, MAX(sokutei_dt) AS max_dt FROM suishitsu_kanri WHERE del_flg IS NULL;";

                        using(var reader = cmd.ExecuteReader()) {
                            if(reader.Read()) {
                                DateTime minDt = DateTime.Parse(reader.GetString(0));
                                DateTime maxDt = DateTime.Parse(reader.GetString(1));

                                timeSpanSt = DateTime.Parse(minDt.Year.ToString() + "/" + minDt.Month.ToString() + "/1");
                                timeSpanEd = (DateTime.Parse(maxDt.Year.ToString() + "/" + maxDt.Month.ToString() + "/1")).AddMonths(1).AddDays(-1);
                            }
                        }
                    }
                }
            }
            else {
                timeSpanSt = DateTime.Parse(selectedStY + "/" + selectedStM + "/1");

                SelectableSpan item2 = (SelectableSpan)CBSpan.SelectedItem;

                if(item2 != null) {
                    int months = item2.months;

                    if(months > 0) {
                        //年間月間指定
                        timeSpanEd = timeSpanSt.AddMonths(months).AddDays(-1);
                    }
                    else {
                        //終了月指定
                        SelectableMonth item3 = (SelectableMonth)CBEdMonth.SelectedItem;

                        if(item3 != null) {
                            selectedEdY = item3.primaryKey(0);
                            selectedEdM = item3.primaryKey(1);

                            timeSpanEd = (DateTime.Parse(selectedEdY + "/" + selectedEdM + "/1")).AddMonths(1).AddDays(-1);
                        }
                    }
                }
            }

            TimeSpan timeSpan = timeSpanEd - timeSpanSt;
            spanDays = timeSpan.Days + 1;
            label9.Text = timeSpanSt.ToString("yyyy/MM/dd") + "～" + timeSpanEd.ToString("yyyy/MM/dd") + "（" + spanDays.ToString("#,0") + "日間）";

            if(spanDays < 185) {
                radioButton11.Checked = true;
                radioButton12.Enabled = false;
            }
            else {
                radioButton12.Enabled = true;
            }

            viewPrintPreview();
        }




        //初期の用紙方向の指定
        private void setLandscape() {
            printDocument1.DefaultPageSettings.Landscape = true;
        }




        //日単位・月平均ラジオボタン選択変更イベント
        private void radioButton12_CheckedChanged(object sender, EventArgs e) {
            if(radioButton11.Checked == true) {
                PrintContainer.monthAverage = false;
            }
            else {
                PrintContainer.monthAverage = true;
            }

            viewPrintPreview();
        }




        //カラー・モノクロラジオボタン選択変更イベント
        private void radioButton22_CheckedChanged(object sender, EventArgs e) {
            if(radioButton21.Checked == true) {
                PrintContainer.colorPrint = true;
            }
            else {
                PrintContainer.colorPrint = false;
            }

            viewPrintPreview();
        }




        //系統設定ボタンクリックイベント
        private void buttonSeries_Click(object sender, EventArgs e) {
            Button b = (Button)sender;
            string seriesStr = (b.Name).Substring((b.Name).Length - 1, 1);
            int series = int.Parse(seriesStr);

            var win = new Form32z1SettingSeries();
            win.Owner = this;
            win.StartPosition = FormStartPosition.CenterParent;
            win.series = series;
            win.graphSerieses = graphSerieses;

            if(b.Text == "変更") {
                win.deletable = true;
            }

            win.ShowDialog();

            if(win.chenged) {
                graphSerieses[series] = win.graphSerieses[series];
                refreshSeriesBox();
            }

            if(win.deleted) {
                graphSerieses[series].delete();
                refreshSeriesBox();
            }

            win.Dispose();
        }




        //系統設定の表示更新
        private void refreshSeriesBox() {
            for(int i = 1; i < PrintContainer.graphSeriesNo; i++) {
                if(!string.IsNullOrEmpty(graphSerieses[i].kanrisya)) {
                    panel1.Controls["panelSeries" + i.ToString()].BackColor = seriesEnableBC;
                    panel1.Controls["panelSeries" + i.ToString()].Controls["labelSeries" + i.ToString() + "1"].ForeColor = seriesEnable;

                    string sameScaleStr = "";
                    string scaleKeitou = "";

                    int samaScale = 0;
                    for(int j = 1; j < PrintContainer.graphSeriesNo; j++) {
                        if(graphSerieses[j].scaleNo == graphSerieses[i].scaleNo) {
                            if(samaScale > 0) {
                                sameScaleStr += ",";
                            }

                            sameScaleStr += j.ToString();
                            samaScale++;
                        }
                    }

                    if(samaScale > 1) {
                        scaleKeitou = "（同一スケール：" + sameScaleStr + "）";
                    }

                    panel1.Controls["panelSeries" + i.ToString()].Controls["labelSeries" + i.ToString() + "1"].Text = "系列" + i.ToString() + scaleKeitou;
                    panel1.Controls["panelSeries" + i.ToString()].Controls["labelSeries" + i.ToString() + "2"].Text = ccSet[graphSerieses[i].columnsIndex].HeaderText + ccSet[graphSerieses[i].columnsIndex].unit;
                    panel1.Controls["panelSeries" + i.ToString()].Controls["labelSeries" + i.ToString() + "3"].Text = graphSerieses[i].kanrisya + "：" + graphSerieses[i].syorijou;
                    panel1.Controls["panelSeries" + i.ToString()].Controls["buttonSeries" + i.ToString()].Text = "変更";
                    panel1.Controls["panelSeries" + i.ToString()].Controls["buttonSeries" + i.ToString()].Visible = true;

                    if(i > 1) {
                        panel1.Controls["panelSeries" + (i - 1).ToString()].Controls["buttonSeries" + (i - 1).ToString()].Visible = false;
                    }
                }
                else {
                    panel1.Controls["panelSeries" + i.ToString()].BackColor = seriesDisableBC;
                    panel1.Controls["panelSeries" + i.ToString()].Controls["labelSeries" + i.ToString() + "1"].ForeColor = seriesDisable;
                    panel1.Controls["panelSeries" + i.ToString()].Controls["labelSeries" + i.ToString() + "1"].Text = "系列" + i.ToString();
                    panel1.Controls["panelSeries" + i.ToString()].Controls["labelSeries" + i.ToString() + "2"].Text = null;
                    panel1.Controls["panelSeries" + i.ToString()].Controls["labelSeries" + i.ToString() + "3"].Text = null;

                    if(i == 1 || !string.IsNullOrEmpty(graphSerieses[i - 1].kanrisya)) {
                        panel1.Controls["panelSeries" + i.ToString()].Controls["buttonSeries" + i.ToString()].Text = "追加";
                        panel1.Controls["panelSeries" + i.ToString()].Controls["buttonSeries" + i.ToString()].Visible = true;
                    }
                    else {
                        panel1.Controls["panelSeries" + i.ToString()].Controls["buttonSeries" + i.ToString()].Visible = false;
                    }
                }
            }

            viewPrintPreview();
        }




        //印刷プレビューの表示
        private void viewPrintPreview() {
            PrintContainer.printType = "Graph";
            PrintContainer.dataGridView1 = dataGridView1;
            PrintContainer.timeSpanSt = timeSpanSt;
            PrintContainer.timeSpanEd = timeSpanEd;
            PrintContainer.monthAverage = radioButton12.Checked;
            PrintContainer.colorPrint = radioButton21.Checked;
            PrintContainer.graphSerieses = graphSerieses;

            makePreview();
        }




        //ファイル出力ボタンクリックイベント
        private void outputFile(object sender, EventArgs e) {
            PrintContainer.printType = "Graph";
            PrintContainer.dataGridView1 = dataGridView1;
            PrintContainer.timeSpanSt = timeSpanSt;
            PrintContainer.timeSpanEd = timeSpanEd;
            PrintContainer.monthAverage = radioButton12.Checked;
            PrintContainer.colorPrint = radioButton21.Checked;
            PrintContainer.graphSerieses = graphSerieses;

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            DateTime now = DateTime.Now;
            string fileName = "下水グラフ_" + now.ToString("yyyyMMdd") + "_" + now.ToString("HHmmss");
            string fileNameExtension = "emf";

            saveFileDialog1.FileName = fileName + "." + fileNameExtension;
            saveFileDialog1.InitialDirectory = @"%USERPROFILE%\Desktop";
            saveFileDialog1.Filter = "拡張メタファイル(*.emf)|*.emf";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.Title = "グラフファイル出力";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.OverwritePrompt = true;
            saveFileDialog1.CheckPathExists = true;

            //ダイアログの表示
            if(saveFileDialog1.ShowDialog() == DialogResult.OK) {
                FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
                progressSplash1.Owner = this;
                progressSplash1.Show();
                progressSplash1.Refresh();

                progressSplash1.ProgressMessage = "ファイル出力中";
                Application.DoEvents();

                fileName = saveFileDialog1.FileName;
                fileNameExtension = fileName.Substring(fileName.Length - 4);

                if(fileNameExtension != ".emf") {
                    fileName += ".emf";
                }

                try {
                    Bitmap tempB = new Bitmap(1, 1);
                    Graphics tempG = Graphics.FromImage(tempB);
                    IntPtr intptrHdc = tempG.GetHdc();

                    using(Metafile metafile1 = new Metafile(fileName, intptrHdc, new RectangleF(0, 0, PrintArea.printAreaWmm, PrintArea.printAreaHmm), MetafileFrameUnit.Millimeter)) {
                        using(Graphics g = Graphics.FromImage(metafile1)) {
                            bool x = PrintDrawerGraph.printDrawer(g, true);
                        }
                    }

                    tempG.ReleaseHdc(intptrHdc);
                    tempG.Dispose();
                    tempB.Dispose();

                    MessageBox.Show("グラフの出力が完了しました");
                }
                catch {
                    MessageBox.Show("ファイルが使用中等の理由により、保存できませんでした");
                }

                progressSplash1.Close();
                progressSplash1.Dispose();
                this.Activate();
            }
        }

    }
}

