using BLL;
using BLL.Common;
using Model;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;

namespace FineUIPro.Web.EditorManage
{
    public partial class LessonsLearnedEditorIn : PageBase
    {
        #region 定义项
        /// <summary>
        /// 上传预设的虚拟路径
        /// </summary>
        private string initPath = Const.ExcelUrl;

        /// <summary>
        /// 错误集合
        /// </summary>
        public static string errorInfos = string.Empty;
        #endregion

        #region 加载
        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }
        #endregion

        #region 模板下载
        /// <summary>
        /// 模板下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Confirm.GetShowReference("Are you sure to download the import template?", String.Empty, MessageBoxIcon.Question, PageManager1.GetCustomEventReference(false, "Confirm_OK"), PageManager1.GetCustomEventReference("Confirm_Cancel")));
        }

        /// <summary>
        /// 下载导入模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "Confirm_OK")
            {
                string rootPath = Server.MapPath("~/");
                string uploadfilepath = rootPath + Const.LessonsLearnedTemplateUrl;
                string filePath = Const.LessonsLearnedTemplateUrl;
                string fileName = Path.GetFileName(filePath);
                FileInfo info = new FileInfo(uploadfilepath);
                long fileSize = info.Length;
                Response.ClearContent();
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                Response.ContentType = "excel/plain";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.AddHeader("Content-Length", fileSize.ToString().Trim());
                Response.TransmitFile(uploadfilepath, 0, fileSize);
                Response.End();
            }
        }
        #endregion

        #region 导入
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnImport_Click(object sender, EventArgs e)
        {
            string message = string.Empty;
            errorInfos = string.Empty;
            List<Editor_LessonsLearned> lessonsLearneds = new List<Editor_LessonsLearned>();
            try
            {
                if (this.fuAttachUrl.HasFile == false)
                {
                    ShowNotify("Please select Excel file!", MessageBoxIcon.Warning);
                    return;
                }
                string IsXls = Path.GetExtension(this.fuAttachUrl.FileName).ToString().Trim().ToLower();
                if (IsXls != ".xls" && IsXls != ".xlsx")
                {
                    ShowNotify("Only Excel files can be selected!", MessageBoxIcon.Warning);
                    return;
                }
                if (lessonsLearneds != null)
                {
                    lessonsLearneds.Clear();
                }
                if (!string.IsNullOrEmpty(errorInfos))
                {
                    errorInfos = string.Empty;
                }
                string rootPath = Server.MapPath("~/");
                string initFullPath = rootPath + initPath;
                if (!Directory.Exists(initFullPath))
                {
                    Directory.CreateDirectory(initFullPath);
                }
                //指定上传文件名称
                this.hdFileName.Text = BLL.Funs.GetNewFileName() + IsXls;
                //上传文件路径
                string filePath = initFullPath + this.hdFileName.Text;
                //文件上传服务器
                this.fuAttachUrl.PostedFile.SaveAs(filePath);
                //文件上传服务器后的名称
                string fileName = rootPath + initPath + this.hdFileName.Text;
                //读取Excel
                DataSet ds = NPOIHelper.ExcelToDataSet(fileName, out errorInfos, true);
                //验证Excel读取是否有误
                if (!string.IsNullOrEmpty(errorInfos))
                {
                    ShowNotify(errorInfos, MessageBoxIcon.Warning);
                    return;
                }
                //导入数据库
                if (ds.Tables.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        Editor_LessonsLearned lessonsLearned = new Editor_LessonsLearned();

                        #region 数据验证和赋值
                        string lessonsId = ds.Tables[0].Rows[i]["Lessons ID"].ToString();
                        if (lessonsId != null && !string.IsNullOrEmpty(lessonsId))
                        {
                            lessonsLearned.Id = lessonsId;
                        }
                        else
                        {
                            errorInfos += (i + 2) + "Line, [Lessons ID] cannot be empty</br>";
                        }
                        if (ds.Tables[0].Rows[i]["Entry Date"] != null && !string.IsNullOrEmpty(ds.Tables[0].Rows[i]["Entry Date"].ToString()))
                        {
                            try
                            {
                                lessonsLearned.EntryDate = Funs.GetNewDateTime(ds.Tables[0].Rows[i]["Entry Date"].ToString());
                            }
                            catch (Exception)
                            {
                                errorInfos += (i + 2) + "line,[Entry Date]Must be in datetime format</br>";
                            }
                        }
                        lessonsLearned.AppliedDiscip = ds.Tables[0].Rows[i]["Applied Discip"].ToString();
                        lessonsLearned.Stage = ds.Tables[0].Rows[i]["Stage"].ToString();
                        lessonsLearned.Keyword = ds.Tables[0].Rows[i]["KeyWord"].ToString();
                        lessonsLearned.PostBy = ds.Tables[0].Rows[i]["Post By"].ToString();
                        lessonsLearned.Description = ds.Tables[0].Rows[i]["Description"].ToString();
                        lessonsLearned.RootCause = ds.Tables[0].Rows[i]["Root Cause"].ToString();
                        lessonsLearned.LessonLearned = ds.Tables[0].Rows[i]["Best Practise & Lesson Learned"].ToString();
                        string eprojectId = Request.Params["eProjectId"];
                        if (eprojectId != null)
                        {
                            lessonsLearned.EProjectId = eprojectId;
                            var eproject = BLL.EProjectService.GeteProjectById(eprojectId);
                            if (eproject != null)
                            {
                                lessonsLearned.JobNo = eproject.ProjectControl_JobNo;
                            }
                        }
                        lessonsLearned.LessonsLearnedId = SQLHelper.GetNewID(typeof(Model.Editor_LessonsLearned));
                        lessonsLearneds.Add(lessonsLearned);
                        #endregion
                    }
                    if (!string.IsNullOrEmpty(errorInfos))
                    {
                        ShowNotify(errorInfos, MessageBoxIcon.Warning, 10000);
                        return;
                    }
                    //去除集合中重复的数据
                    for (int i = 0; i < lessonsLearneds.Count; i++)
                    {
                        for (int j = lessonsLearneds.Count - 1; j > i; j--)
                        {
                            if (lessonsLearneds[i].Id == lessonsLearneds[j].Id)
                            {
                                lessonsLearneds.RemoveAt(j);
                            }
                        }
                    }
                    //判断数据库是否有相同日期和项目的数据
                    var lists = new List<Editor_LessonsLearned>();
                    for (int i = 0; i < lessonsLearneds.Count; i++)
                    {
                        var newlessons = BLL.LessonsLearnedService.GetLessonsLearnedByEprojectIdAndId(lessonsLearneds[i].EProjectId, lessonsLearneds[i].Id);
                        if (newlessons == null)
                        {
                            lists.Add(lessonsLearneds[i]);
                        }
                    }
                    if (lists.Count > 0)
                    {
                        Funs.DB.Editor_LessonsLearned.InsertAllOnSubmit(lists);
                        Funs.DB.SubmitChanges();
                    }

                    #region 邮件发送    
                    string eproId = Request.Params["eProjectId"];
                    var ep = BLL.EProjectService.GeteProjectById(eproId);
                    if (ep != null)
                    {
                        if (Funs.GetNewDecimal(ep.ProjectControl_OrginalBudget.ToString()) > 10000000)
                        {
                            NameValueCollection nameValue = new NameValueCollection();
                            nameValue.Add("projectName", ep.ProjectControl_JobTitle.ToString().Trim());
                            nameValue.Add("projectNo", ep.ProjectControl_JobNo.ToString().Trim());
                            nameValue.Add("projectBUCode", ep.ProjectControl_BUCode);
                            EmailSendMessage(ep, BLL.Const.LLPString, nameValue, BLL.Const.CustomString, BLL.Const.NoprojectString);
                        }
                    }
                    #endregion

                    ShowNotify("Import success!", MessageBoxIcon.Success);
                    PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
                }
                else
                {
                    ShowAlert("No data!", MessageBoxIcon.Warning);
                    return;
                }
            }
            catch (Exception ex)
            {
                ShowAlert("'" + ex.Message + "'", MessageBoxIcon.Warning);
            }
        }
        #endregion
    }
}