using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICSharpCode.Core;
using Mesnac.Action.Base;
using Mesnac.Codd.Session;
using Mesnac.Controls.Base;
using System.Data;
using System.Windows.Forms;

namespace Mesnac.Action.ChemicalWeighing.Alarm.LRAlarmLog
{
    /// <summary>
    /// 报警日志导出业务
    /// </summary>
    public class ExportAction : ChemicalWeighingAction, IAction
    {
        public void Run(RuntimeParameter runtime)
        {
            base.RunIni(runtime);        //必须要调用的
            ICSharpCode.Core.LoggingService<ExportAction>.Debug("报警日志-导出...");

            StringBuilder sbSql = new StringBuilder("SELECT Alarm_PLC, Alarm_Cn_Info, Alarm_OccurTime, Alarm_Other_Info FROM LR_Alarmlog, Pmt_Alarm WHERE Pmt_Alarm.Alarm_ID=LR_Alarmlog.Alarm_ID ");

            List<DbMCControl> mcControllist = GetAllDbMCControlsByOption(DbOptionTypes.Query);//获取所有待初始化控件
            IBaseControl startdate = mcControllist.Where(t => t.BaseControl.MCKey != null && t.BaseControl.MCKey.ToLower() == "startdate").FirstOrDefault().BaseControl;
            IBaseControl starttime = mcControllist.Where(t => t.BaseControl.MCKey != null && t.BaseControl.MCKey.ToLower() == "starttime").FirstOrDefault().BaseControl;
            if (startdate != null && starttime != null)
            {
                sbSql.AppendLine(@"AND LR_Alarmlog.Alarm_OccurTime>='" + Convert.ToDateTime(startdate.MCValue).ToString("yyyy-MM-dd") + " " + Convert.ToDateTime(starttime.MCValue).ToShortTimeString() + "' ");
            }
            else
            {
                ICSharpCode.Core.LoggingService<SelectAction>.Debug("{报警记录} 缺少key值为startdate或者starttime的时间查询条件...");
                return;
            }
            IBaseControl enddate = mcControllist.Where(t => t.BaseControl.MCKey != null && t.BaseControl.MCKey.ToLower() == "enddate").FirstOrDefault().BaseControl;
            IBaseControl endtime = mcControllist.Where(t => t.BaseControl.MCKey != null && t.BaseControl.MCKey.ToLower() == "endtime").FirstOrDefault().BaseControl;
            if (enddate != null && endtime != null)
            {
                sbSql.AppendLine(@"AND LR_Alarmlog.Alarm_OccurTime<='" + Convert.ToDateTime(enddate.MCValue).ToString("yyyy-MM-dd") + " " + Convert.ToDateTime(endtime.MCValue).ToShortTimeString() + "' ");
            }
            else
            {
                ICSharpCode.Core.LoggingService<SelectAction>.Debug("{报警记录} 缺少key值为enddate或者enddate的时间查询条件...");
                return;
            }
            sbSql.Append(" ORDER BY Alarm_OccurTime desc");

            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);
            if (dbHelper == null)
            {
                ICSharpCode.Core.LoggingService<ExportAction>.Error("获取本地数据连接失败...");
                return;
            }
            dbHelper.CommandText = sbSql.ToString();
            dbHelper.CommandType = System.Data.CommandType.Text;
            DataTable dt = dbHelper.ToDataTable();

            if (dt.Rows.Count == 0)
            {
                string msg3 = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Alarm_LRAlarmLog_ExportAction_msg3"));     //查询结果为空,请重新查询!
                MessageBox.Show(msg3, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "xls files(*.xls)|*.xls";
            sfd.FileName = String.Format("LRAlarmlog_{0:yyyyMMdd}", DateTime.Now);
            sfd.AddExtension = true;
            DialogResult result = sfd.ShowDialog();
            if (result == DialogResult.OK)
            {
                string fileName = sfd.FileName;
                if (!String.IsNullOrEmpty(fileName))
                {
                    try
                    {
                        System.IO.Stream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite);
                        Mesnac.Basic.DataToFileHandler.Instance.ToExcel(dt, ref fs);
                        fs.Close();
                        string msg1 = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Alarm_LRAlarmLog_ExportAction_msg1"));       //导出报警日志至Excel成功!
                        ICSharpCode.Core.LoggingService<ExportAction>.Info(msg1);

                        #region 记录操作日志

                        base.DBLog(msg1);

                        #endregion

                        MessageBox.Show(msg1, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        string msg2 = StringParser.Parse(ResourceService.GetString("Mesnac_Action_ChemicalWeighing_Alarm_LRAlarmLog_ExportAction_msg2"));       //导出报警日志至Excel失败:{0}!
                        msg2 = String.Format(msg2, ex.Message);
                        ICSharpCode.Core.LoggingService<ExportAction>.Error(msg2);

                        #region 记录操作日志

                        base.DBLog(msg2);

                        #endregion

                        MessageBox.Show(msg2, Mesnac.Basic.LanguageHelper.WarnCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        runtime.IsReturn = true;
                        return;
                    }
                }
            }
        }
    }
}