using System;
using System.Data;
using System.Windows.Forms;
using CRVM.SIDExcuter;
using CRVM.Entity;
using System.Text;
using System.Collections.Generic;
using System.IO;

namespace CRVM
{
    public delegate void ShowGridData(object sender, string path);
    struct SelectConditions
    {
        public DateTime start;
        public DateTime end;
        public bool isSelByDate;
        public string coilid;
        public bool isAlarm;
    };
    public partial class DataSearchForm : Form
    {
        public event ShowGridData showdata;
        //string[] columnArrayCoilInfo = { "生产结束时间", "报警状态", "热卷号", "冷卷号", "钢种牌号", "出钢记号", "宽度(mm)", "入口厚度(mm)", "出口厚度(mm)", "成品长度", "结束标记", "原始数据文件路径", "能量数据文件路径" };
        //int[] columnArrayCoilInfoWidth = { 200, 100, 150, 150, 0, 120, 120, 120, 120, 120, 100, 400, 400 };
        string[] columnArrayCoilInfo = { "生产结束时间", "报警状态", "热卷号", "冷卷号", "钢种牌号", "出钢记号", "宽度(mm)", "入口厚度(mm)", "出口厚度(mm)", "成品长度", "成品长度(L2)", "结束标记", "原始数据文件路径", "能量数据文件路径"
//                                       "辊号(1/B/U)", "累重[t](1/B/U)", "辊号(1/B/L)", "累重[t](1/B/L)","辊号(1/M/U)", "累重[t](1/M/U)", "辊号(1/M/L)", "累重[t](1/M/L)","辊号(1/W/U)", "累重[t](1/W/U)", "辊号(1/W/L)", "累重[t](1/W/L)",
//                                       "辊号(2/B/U)", "累重[t](2/B/U)", "辊号(2/B/L)", "累重[t](2/B/L)","辊号(2/M/U)", "累重[t](2/M/U)", "辊号(2/M/L)", "累重[t](2/M/L)","辊号(2/W/U)", "累重[t](2/W/U)", "辊号(2/W/L)", "累重[t](2/W/L)",
 //                                      "辊号(3/B/U)", "累重[t](3/B/U)", "辊号(3/B/L)", "累重[t](3/B/L)","辊号(3/M/U)", "累重[t](3/M/U)", "辊号(3/M/L)", "累重[t](3/M/L)","辊号(3/W/U)", "累重[t](3/W/U)", "辊号(3/W/L)", "累重[t](3/W/L)",
//                                       "辊号(4/B/U)", "累重[t](4/B/U)", "辊号(4/B/L)", "累重[t](4/B/L)","辊号(4/M/U)", "累重[t](4/M/U)", "辊号(4/M/L)", "累重[t](4/M/L)","辊号(4/W/U)", "累重[t](4/W/U)", "辊号(4/W/L)", "累重[t](4/W/L)",
//                                       "辊号(5/B/U)", "累重[t](5/B/U)", "辊号(5/B/L)", "累重[t](5/B/L)","辊号(5/M/U)", "累重[t](5/M/U)", "辊号(5/M/L)", "累重[t](5/M/L)","辊号(5/W/U)", "累重[t](5/W/U)", "辊号(5/W/L)", "累重[t](5/W/L)",
                                       };
        int[] columnArrayCoilInfoWidth = { 200, 100, 150, 150, 0, 120, 120, 120, 120, 120, 120, 100, 400, 400 
//                                         125, 125, 125, 125, 125, 125,125, 125, 125, 125, 125, 125,
//                                         125, 125, 125, 125, 125, 125,125, 125, 125, 125, 125, 125,
//                                         125, 125, 125, 125, 125, 125,125, 125, 125, 125, 125, 125,
 //                                        125, 125, 125, 125, 125, 125,125, 125, 125, 125, 125, 125,
//                                         125, 125, 125, 125, 125, 125,125, 125, 125, 125, 125, 125,
                                         };
        string[] columnArrayAlarmInfo = { "开始位置", "结束位置", "机架", "类型", "能量" };
        int[] columnArrayAlarmInfoWidth = { 100, 100, 70, 70, 110 };

        string Dbpath;
        DataTable orignViewData = null;
        List<string> allCoilIdList = new List<string>();
        public DataSearchForm()
        {
            InitializeComponent();
        }

        private void DataSearch_Load(object sender, EventArgs e)
        {
            InitalSetting();
        }

        private void DoReadWork(SelectConditions condition)
        {
            if (this.backgroundWorker1.IsBusy)
            {
                MessageBox.Show("数据正在加载中，请稍后！");
                return;
            }
            else
            {
                this.backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
                this.backgroundWorker1.DoWork += backgroundWorker1_DoWork;
                this.backgroundWorker1.RunWorkerAsync(condition);//传入查询条件，开始异步查询

                this.Cursor = Cursors.WaitCursor;
                tableLayoutPanel1.Enabled = false;
            }
        }

        void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            SelectConditions condition = (SelectConditions)e.Argument;

            DataTable data = null;
            try
            {
                if (condition.isSelByDate)//根据时间查询
                {
                    data = DbHelper.GetInstance("").GetCoilInfoByDate(condition.isAlarm, condition.start, condition.end);
                }
                else//根据卷号查询
                {
                    data = DbHelper.GetInstance("").GetCoilInfoByColdId(condition.coilid);
                }

                //重新组织数据
                if (data != null)
                {
                    for (int i = 0; i < data.Columns.Count; i++)
                    {
                        data.Columns[i].ColumnName = columnArrayCoilInfo[i];
                    }

                    for (int i = 0; i < data.Rows.Count; i++)
                    {
                        if (data.Rows[i]["报警状态"].ToString().Trim() == "1")
                        {
                            data.Rows[i]["报警状态"] = "Y";
                        }
                        else
                        {
                            data.Rows[i]["报警状态"] = "N";
                        }

                        if (data.Rows[i]["结束标记"].ToString().Trim() == "0")
                        {
                            data.Rows[i]["结束标记"] = "超时";
                        }
                        else if (data.Rows[i]["结束标记"].ToString().Trim() == "1")
                        {
                            data.Rows[i]["结束标记"] = "剪切";
                        }
                        else
                        {
                            data.Rows[i]["结束标记"] = "手动";
                        }
                    }
                }
                e.Result = data;//输出结果

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                e.Result = null;
            }
        }

        void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            this.Cursor = Cursors.Default;
            this.tableLayoutPanel1.Enabled = true;

            DataTable data = (DataTable)e.Result;
            dataGrid_coilInfo.DataSource = data;

            ResetCoilInfoDataGridView(dataGrid_coilInfo);
        }

        private void InitalSetting()
        {
            date_Start.Value = SysParam.Instance.searchStartTime;
            date_End.Value = SysParam.Instance.searchEndTime;
            checkBox_alarm.Checked = SysParam.Instance.searchAlarmChecked ? true : false;
            panel5.Visible = false;

            SelectConditions condition = new SelectConditions();
            condition.isSelByDate = true;
            condition.isAlarm = SysParam.Instance.searchAlarmChecked;
            condition.start = date_Start.Value;
            condition.end = date_End.Value;

            DoReadWork(condition);
        }
        //显示钢卷的详细报警信息
        private void dataGridcoilInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            if (e.ColumnIndex == 2)
            {
                if (dataGrid_coilInfo.Columns.Contains("冷卷号"))
                {
                    DataTable dt = DbHelper.GetInstance("").SelAlarmInfoByColdId(dataGrid_coilInfo.CurrentRow.Cells["冷卷号"].Value.ToString());
                    if (dt.Rows.Count > 0)
                    {
                        dataGrid_alarmData.DataSource = dt;
                        for (int i = 0; i < dataGrid_alarmData.Rows.Count; i++)
                        {
                            if (dataGrid_alarmData.Rows[i].Cells[3].Value.ToString() == "0") { dataGrid_alarmData.Rows[i].Cells[3].Value = "低频"; }
                            if (dataGrid_alarmData.Rows[i].Cells[3].Value.ToString() == "1") { dataGrid_alarmData.Rows[i].Cells[3].Value = "中频"; }
                            if (dataGrid_alarmData.Rows[i].Cells[3].Value.ToString() == "2") { dataGrid_alarmData.Rows[i].Cells[3].Value = "高频"; }
                        }
                        ResetAlarmInfoDataGridView(dataGrid_alarmData);
                        panel5.Visible = true;
                    }
                    else
                    {
                        panel5.Visible = false;
                        MessageBox.Show("不存在报警缺陷！");
                    }
                }
            }
            if (e.ColumnIndex == 0)
            {
                if (dataGrid_coilInfo.Columns.Contains("选择"))
                {
                    string cellValue = dataGrid_coilInfo.CurrentRow.Cells["选择"].Value.ToString();
                    if (cellValue == "true")
                    {
                        dataGrid_coilInfo.CurrentRow.Cells["选择"].Value = "false";
                    }
                    else
                    {
                        dataGrid_coilInfo.CurrentRow.Cells["选择"].Value = "true";
                    }
                }
            }
        }

        private void btn_SearchByDate_Click(object sender, EventArgs e)
        {
            SelectConditions condition = new SelectConditions();
            condition.isSelByDate = true;
            condition.isAlarm = SysParam.Instance.searchAlarmChecked;
            condition.start = date_Start.Value;
            condition.end = date_End.Value;

            SysParam.Instance.searchStartTime = date_Start.Value;
            SysParam.Instance.searchEndTime = date_End.Value;

            DoReadWork(condition);
        }

        private void btn_ViewOrignData_Click(object sender, EventArgs e)
        {
            if (this.dataGrid_coilInfo.SelectedRows.Count > 0)
            {
                Dbpath = this.dataGrid_coilInfo.SelectedRows[0].Cells["原始数据文件路径"].Value.ToString();
                if (showdata != null)
                {
                    showdata(sender, Dbpath);
                }
                this.Close();
            }
            else
            {
                MessageBox.Show("请选择要查询的钢卷！");
            }
        }

        private void btn_ViewEnergyData_Click(object sender, EventArgs e)
        {
            if (this.dataGrid_coilInfo.SelectedRows.Count > 0)
            {
                Dbpath = this.dataGrid_coilInfo.SelectedRows[0].Cells["能量数据文件路径"].Value.ToString();
                if (showdata != null)
                {
                    showdata(sender, Dbpath);
                }
            }
            else
            {
                MessageBox.Show("请选择要查询的钢卷！");
            }
        }

        private void btn_SearchByColdId_Click(object sender, EventArgs e)
        {
            SelectConditions condition = new SelectConditions();
            condition.isSelByDate = false;
            condition.coilid = textBox_ColdId.Text.Trim();

            DoReadWork(condition);
        }

        private void checkBox_alarm_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_alarm.Checked)
            {
                SysParam.Instance.searchAlarmChecked = true;
            }
            else
            {
                SysParam.Instance.searchAlarmChecked = false;
            }
        }

        private void ResetCoilInfoDataGridView(DataGridView dgv)
        {
            if (dgv.Columns.Contains("选择"))
            {
                for (int i = 1; i < dgv.Columns.Count; i++)
                {
                    dgv.Columns[i].Width = columnArrayCoilInfoWidth[i - 1];
                    dataGrid_coilInfo.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                    if (i == 5)
                    {
                        dgv.Columns[i].Visible = false;
                    }
                }
            }
            else
            {
                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    dgv.Columns[i].Width = columnArrayCoilInfoWidth[i];
                    dataGrid_coilInfo.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                    if (i == 4)
                    {
                        dgv.Columns[i].Visible = false;
                    }
                }
            }

            if (!dgv.Columns.Contains("选择"))
            {
                DataGridViewCheckBoxColumn addColumn = new DataGridViewCheckBoxColumn();
                addColumn.HeaderText = "选择";
                addColumn.Name = "选择";
                addColumn.Resizable = System.Windows.Forms.DataGridViewTriState.False;
                addColumn.TrueValue = "true";
                //dgv.Columns.Add(addColumn);
                dgv.Columns.Insert(0, addColumn);
                dgv.Columns["选择"].DisplayIndex = 0;
                dgv.Columns["选择"].ReadOnly = false;

                addFullSelect();
            }
            else
            {
                dgv.Columns["选择"].ReadOnly = false;
            }

            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                dgv.Rows[i].Cells["选择"].Value = "false";
            }
        }

        private void ResetAlarmInfoDataGridView(DataGridView dgv)
        {
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                dgv.Columns[i].HeaderText = columnArrayAlarmInfo[i];
                dgv.Columns[i].Name = columnArrayAlarmInfo[i];
                dgv.Columns[i].Width = columnArrayAlarmInfoWidth[i];
                dataGrid_alarmData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            panel5.Visible = false;
            if (tabControl1.SelectedTab.Text == "时间检索")
            {
                btn_SearchByDate_Click(sender, e);
            }
            else
            {
                btn_SearchByColdId_Click(sender, e);
            }
        }

        private void btn_Export_Click(object sender, EventArgs e)
        {
            if (this.dataGrid_coilInfo.SelectedRows.Count <= 0)
            {
                MessageShowForm form = new MessageShowForm("警告", "请选择导出的卷！");
                form.ShowDialog();
                return;
            }

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                string filePath = folderBrowserDialog1.SelectedPath;
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                string filePath_orig = filePath + "\\original data";
                if (!Directory.Exists(filePath_orig))
                {
                    Directory.CreateDirectory(filePath_orig);
                }

                bool flag = false;
                if (dataGrid_coilInfo.Columns.Contains("选择"))
                {
                    for (int i = 0; i < dataGrid_coilInfo.Rows.Count; i++)
                    {
                        string checkValue = dataGrid_coilInfo.Rows[i].Cells["选择"].Value.ToString();

                        if (checkValue == "true")//选中
                        {
                            string coldcoilno = this.dataGrid_coilInfo.Rows[i].Cells["冷卷号"].Value.ToString().Trim();
                            string sourcefileName_orig = this.dataGrid_coilInfo.Rows[i].Cells["原始数据文件路径"].Value.ToString().Trim();

                            if (!File.Exists(sourcefileName_orig))
                            {
                                MessageShowForm form = new MessageShowForm("警告", "原始数据源文件dat不存在！" + sourcefileName_orig);
                                form.ShowDialog();
                                return;
                            }

                            //string destfileName_orig = sourcefileName_orig.Substring(sourcefileName_orig.Length - 18, 18);
                            string destfileName_orig = Path.GetFileName(sourcefileName_orig);
                            File.Copy(sourcefileName_orig, filePath_orig + "\\" + destfileName_orig + "_" + coldcoilno, true);

                            string filePath_energy = filePath + "\\energy data";
                            if (!Directory.Exists(filePath_energy))
                            {
                                Directory.CreateDirectory(filePath_energy);
                            }

                            string sourcefileName_energy = this.dataGrid_coilInfo.Rows[i].Cells["能量数据文件路径"].Value.ToString();

                            if (!File.Exists(sourcefileName_energy))
                            {
                                MessageShowForm form = new MessageShowForm("警告", "能量数据源文件txt不存在！" + sourcefileName_energy);
                                form.ShowDialog();
                                return;
                            }

                            if (!File.Exists(sourcefileName_energy))
                            {
                                MessageShowForm form = new MessageShowForm("警告", "能量数据源文件txt不存在！");
                                form.ShowDialog();
                                return;
                            }
                            //string destfileName_energy = sourcefileName_orig.Substring(sourcefileName_energy.Length - 18, 18);
                            string destfileName_energy = Path.GetFileName(sourcefileName_energy);
                            File.Copy(sourcefileName_energy, filePath_energy + "\\" + destfileName_energy + "_" + coldcoilno, true);

                            flag = true;
                        }
                    }
                }
                if (flag)
                {
                    MessageBox.Show("拷贝成功！");
                }
                else
                {
                    MessageBox.Show("没有需要拷贝的文件！");
                }

            }
        }

        private void btnExportCoilMsg_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string saveDirectory = saveFileDialog1.FileName;
                ExportToCSV export = new ExportToCSV(saveDirectory);

                DataTable data = new DataTable();

                for (int i = 1; i < dataGrid_coilInfo.Columns.Count; i++)
                {
                    DataColumn col = new DataColumn();
                    col.ColumnName = dataGrid_coilInfo.Columns[i].HeaderText;
                    data.Columns.Add(col);

                }

                for (int j = 0; j < dataGrid_coilInfo.Rows.Count; j++)
                {
                    if (dataGrid_coilInfo.Columns.Contains("选择"))
                    {
                        if (dataGrid_coilInfo.Rows[j].Cells["选择"].Value.ToString() == "true")
                        {
                            DataRow row = data.NewRow();
                            for (int i = 0; i < data.Columns.Count; i++)
                            {
                                row[i] = dataGrid_coilInfo.Rows[j].Cells[i + 1].Value;
                            }
                            data.Rows.Add(row);
                        }
                    }

                }

                export.writeProductData(data);

                if (export.writeOK)
                {
                    MessageBox.Show("导出钢卷信息成功!");
                }
                else
                {
                    MessageBox.Show("导出钢卷信息失败!");
                }
            }

        }

        CheckBox ckbox = new CheckBox();
        private void addFullSelect()
        {

            System.Drawing.Rectangle rect = dataGrid_coilInfo.GetCellDisplayRectangle(0, -1, true);
            ckbox.Text = "全选";
            //ckbox.Checked = true;
            ckbox.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            ckbox.Font = dataGrid_coilInfo.Columns[0].DefaultCellStyle.Font;
            ckbox.Size = new System.Drawing.Size(dataGrid_coilInfo.Columns[0].Width, 30);
            ckbox.Location = new System.Drawing.Point(rect.Location.X, rect.Location.Y);
            ckbox.CheckedChanged += ckbox_CheckedChanged;
            dataGrid_coilInfo.Controls.Add(ckbox);
        }

        void ckbox_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGrid_coilInfo.Rows.Count; i++)
            {
                if (dataGrid_coilInfo.Columns.Contains("选择"))
                {
                    if (ckbox.Checked)
                    {
                        dataGrid_coilInfo.Rows[i].Cells["选择"].Value = "true";
                    }
                    else
                    {
                        dataGrid_coilInfo.Rows[i].Cells["选择"].Value = "false";
                    }
                }

            }
        }

    }
}
