using BLL;
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FineUIPro.Web.DataShow;
namespace FineUIPro.Web.HJGL.WeldingManage
{
    public partial class PmiMaterialDataIn : PageBase
    {
        #region 定义变量
        /// 
        /// 上传预设的虚拟路径
        /// 
        private string initPath = Const.ExcelUrl;
        /// 
        /// 错误集合
        /// 
        public static List errorInfos = new List();
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (errorInfos != null)
                {
                    errorInfos.Clear();
                }
            }
        }
        #endregion
        #region 审核
        /// 
        /// 审核
        /// 
        /// 
        /// 
        protected void btnAudit_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.FileExcel.HasFile == false)
                {
                    Alert.ShowInTop("请您选择Excel文件!", MessageBoxIcon.Warning);
                    return;
                }
                string IsXls = Path.GetExtension(FileExcel.FileName).ToString().Trim().ToLower();
                if (IsXls != ".xls")
                {
                    Alert.ShowInTop("只可以选择Excel文件!", MessageBoxIcon.Warning);
                    return;
                }
                if (errorInfos != null)
                {
                    errorInfos.Clear();
                }
                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;
                FileExcel.PostedFile.SaveAs(filePath);
                ImportXlsToData(filePath);
            }
            catch (Exception ex)
            {
                Alert.ShowInTop(ex.Message);
            }
        }
        #region 读Excel提取数据
        /// 
        /// 从Excel提取数据--》Dataset
        /// 
        /// Excel文件路径名
        private void ImportXlsToData(string fileName)
        {
            try
            {
                string oleDBConnString = String.Empty;
                oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;";
                oleDBConnString += "Data Source=";
                oleDBConnString += fileName;
                oleDBConnString += ";Extended Properties=Excel 8.0;";               
                OleDbConnection oleDBConn = null;
                OleDbDataAdapter oleAdMaster = null;
                DataTable m_tableName = new DataTable();
                DataSet ds = new DataSet();
            
                oleDBConn = new OleDbConnection(oleDBConnString);
                oleDBConn.Open();
                m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (m_tableName != null && m_tableName.Rows.Count > 0)
                {
                    m_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString().Trim();
                }
                string sqlMaster;
                sqlMaster = " SELECT *  FROM [" + m_tableName.TableName + "]";
                oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn);
                oleAdMaster.SelectCommand.CommandTimeout = 1200;
                oleAdMaster.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                oleDBConn.Close();
                oleDBConn.Dispose();
                AddDatasetToSQL(ds.Tables[0]);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region 读Excel提取数据
        /// 
        /// 从Excel提取数据--》Dataset
        /// 
        /// Excel文件路径名
        private void ImportXlsToData2(string fileName)
        {
            try
            {
                string oleDBConnString = String.Empty;
                oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;";
                oleDBConnString += "Data Source=";
                oleDBConnString += fileName;
                oleDBConnString += ";Extended Properties=Excel 8.0;";
                OleDbConnection oleDBConn = null;
                OleDbDataAdapter oleAdMaster = null;
                DataTable m_tableName = new DataTable();
                DataSet ds = new DataSet();
                oleDBConn = new OleDbConnection(oleDBConnString);
                oleDBConn.Open();
                m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (m_tableName != null && m_tableName.Rows.Count > 0)
                {
                    m_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString().Trim();
                }
                string sqlMaster;
                sqlMaster = " SELECT *  FROM [" + m_tableName.TableName + "]";
                oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn);
                oleAdMaster.SelectCommand.CommandTimeout = 30;
                oleAdMaster.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                oleDBConn.Close();
                oleDBConn.Dispose();
                AddDatasetToSQL2(ds.Tables[0]);
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        }
        #endregion
        /// 
        /// 将Dataset的数据导入数据库
        /// 
        /// 数据集
        /// 数据集列数
        /// 
        private bool AddDatasetToSQL(DataTable pds)
        {
            string result = string.Empty;
            int ic, ir;
            ic = pds.Columns.Count;
            ir = pds.Rows.Count;
            if (pds != null && ir > 0)
            {
                //var sPmiMaterialTemplate = from x in Funs.DB.PIM_View_PmiMaterialTemplate where x.ProjectId == this.CurrUser.LoginProjectId select x;
                var installations = from x in Funs.DB.Project_Installation where x.ProjectId == this.CurrUser.LoginProjectId select x;
                var workAreas = from x in Funs.DB.ProjectData_WorkArea where x.ProjectId == this.CurrUser.LoginProjectId select x;
                for (int i = 1; i < ir; i++)
                {
                    string col1 = pds.Rows[i][1].ToString().Trim();
                    if (!string.IsNullOrEmpty(col1))
                    {
                        var Installation = installations.FirstOrDefault(e => e.InstallationName == col1);
                        if (Installation == null)
                        {
                            result += (i + 2).ToString() + "," + "装置" + "," + "[" + col1 + "]错误!" + "|";
                        }
                    }
                    string col2 = pds.Rows[i][2].ToString().Trim();
                    if (!string.IsNullOrEmpty(col2))
                    {
                        var user = workAreas.FirstOrDefault(e => e.WorkAreaName == col2);
                        if (user == null)
                        {
                            result += (i + 2).ToString() + "," + "工区" + "," + "[" + col2 + "]错误!" + "|";
                        }
                    }
                    string col3 = pds.Rows[i][3].ToString().Trim();
                    if (string.IsNullOrEmpty(col3))
                    {
                        result += (i + 2).ToString() + "," + "管线" + "," + "此项为必填项!" + "|";
                    }
                }
                if (!string.IsNullOrEmpty(result))
                {
                    result = result.Substring(0, result.LastIndexOf("|"));
                }
                errorInfos.Clear();
                if (!string.IsNullOrEmpty(result))
                {
                    string results = result;
                    List errorInfoList = results.Split('|').ToList();
                    foreach (var item in errorInfoList)
                    {
                        string[] errors = item.Split(',');
                        Model.ErrorInfo errorInfo = new Model.ErrorInfo();
                        errorInfo.Row = errors[0];
                        errorInfo.Column = errors[1];
                        errorInfo.Reason = errors[2];
                        errorInfos.Add(errorInfo);
                    }
                    if (errorInfos.Count > 0)
                    {
                        Grid1.DataSource = errorInfos;
                        Grid1.DataBind();
                    }
                }
                else
                {
                    ShowNotify("审核完成,请点击保存!", MessageBoxIcon.Success);
                }
            }
            else
            {
                throw new Exception("导入数据为空!");
            }
            return true;
        }
        #endregion
        #region 导入
        /// 
        /// 导入
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (errorInfos.Count <= 0)
            {
                string rootPath = Server.MapPath("~/");
                string initFullPath = rootPath + initPath;
                if (!Directory.Exists(initFullPath))
                {
                    Directory.CreateDirectory(initFullPath);
                }
                string filePath = initFullPath + this.hdfileName.Text;
                ImportXlsToData2(filePath);
            }
            else
            {
                Alert.ShowInTop("请先将错误数据修正,再重新导入保存!", MessageBoxIcon.Warning);
            }
        }
        
        /// 
        /// 将Dataset的数据导入数据库
        /// 
        /// 数据集
        /// 数据集列数
        /// 
        private bool AddDatasetToSQL2(DataTable pds)
        {
            string result = string.Empty;
            //var sPmiMaterialTemplate = from x in Funs.DB.PIM_View_PmiMaterialTemplate where x.ProjectId == this.CurrUser.LoginProjectId select x;
            var installations = from x in Funs.DB.Project_Installation where x.ProjectId == this.CurrUser.LoginProjectId select x;
            var workAreas = from x in Funs.DB.ProjectData_WorkArea where x.ProjectId == this.CurrUser.LoginProjectId select x;
            for (int i = 1; i < pds.Rows.Count; i++)
            {
                //foreach (DataRow row in pds.Rows)
                //{
                var oldTestApplication = BLL.PMI_MaterialTemplateService.GetPMI_MaterialTemplateId(this.CurrUser.LoginProjectId, pds.Rows[i][1].ToString().Trim(), pds.Rows[i][2].ToString().Trim(), pds.Rows[i][3].ToString().Trim());
                if (oldTestApplication == null)
                {
                    Model.PMI_MaterialTemplate newPipeline = new Model.PMI_MaterialTemplate();
                    newPipeline.MaterialId = SQLHelper.GetNewID(typeof(Model.PMI_MaterialTemplate));
                    newPipeline.ProjectId = this.CurrUser.LoginProjectId;
                    string col0 = pds.Rows[i][0].ToString().Trim();
                    string col1 = pds.Rows[i][1].ToString().Trim();
                    var unit = installations.FirstOrDefault(e => e.InstallationName == col1);
                    if (unit != null)
                    {
                        newPipeline.UnitId = unit.InstallationId;
                    }
                    string col2 = pds.Rows[i][2].ToString().Trim();
                    var AreaId = workAreas.FirstOrDefault(e => e.WorkAreaName == col2);
                    if (AreaId != null)
                    {
                        newPipeline.AreaId = unit.UnitId;
                    }
                    string col3 = pds.Rows[i][3].ToString().Trim();
                    string col4 = pds.Rows[i][4].ToString().Trim();
                    string col5 = pds.Rows[i][5].ToString().Trim();
                    string col6 = pds.Rows[i][6].ToString().Trim();
                    string col7 = pds.Rows[i][7].ToString().Trim();
                    string col8 = pds.Rows[i][8].ToString().Trim();
                    string col9 = pds.Rows[i][9].ToString().Trim();
                    string col10 = pds.Rows[i][10].ToString().Trim();
                    string col11 = pds.Rows[i][11].ToString().Trim();
                    string col12 = string.IsNullOrEmpty(pds.Rows[i][12].ToString().Trim()) == true ? "0" : pds.Rows[i][12].ToString().Trim();
                    string col13 = pds.Rows[i][13].ToString().Trim();
                    string col14 = pds.Rows[i][14].ToString().Trim();
                    string col15 = pds.Rows[i][15].ToString().Trim();
                    string col16 = pds.Rows[i][16].ToString().Trim();
                    string col17 = pds.Rows[i][17].ToString().Trim();
                    string col18 = pds.Rows[i][18].ToString().Trim();
                    string col19 = pds.Rows[i][19].ToString().Trim();
                    string col20 = pds.Rows[i][20].ToString().Trim();
                    string col21 = string.IsNullOrEmpty(pds.Rows[i][21].ToString().Trim()) == true ? "0" : pds.Rows[i][21].ToString().Trim();
                    string col22 = pds.Rows[i][22].ToString().Trim();
                    string col23 = pds.Rows[i][23].ToString().Trim();
                  
                    newPipeline.Discpline = col0;
                    newPipeline.UnitId = col1;
                    newPipeline.AreaId = col2;
                 
                    var pIM_View_PmiMaterialTemplateModel= (from x in Funs.DB.PIM_View_PmiMaterialTemplate where x.ProjectId == this.CurrUser.LoginProjectId && x.InstallationName == col1 && x.UnitName == col2 select new { x.UnitId, x.UnitName, x.InstallationId, x.InstallationName }).FirstOrDefault();
                    if (pIM_View_PmiMaterialTemplateModel != null)
                    {
                        newPipeline.UnitIdName = pIM_View_PmiMaterialTemplateModel.InstallationName;
                        newPipeline.AreaIdName = pIM_View_PmiMaterialTemplateModel.UnitName;
                    }
                    newPipeline.Pipeline = col3;
                    newPipeline.ItemRule = col4;
                    newPipeline.CommoidyCode = col5;
                    newPipeline.Size1 = col6;
                    newPipeline.Size2 = col7;
                    newPipeline.IdentCode = col8;
                    newPipeline.TagNumber = col9;
                    newPipeline.IdentName = col10;
                    newPipeline.ShortDescription = col11;
                    newPipeline.Quantity = Convert.ToDecimal(col12);
                    newPipeline.UnitNum = col13;
                    newPipeline.PipeRun = col14;
                    newPipeline.Category = col5;
                    newPipeline.Material = col6;
                    newPipeline.Spec = col17;
                    newPipeline.NominalDiameter = col18;
                    newPipeline.THK = col19;
                    newPipeline.Painting = col20;
                    newPipeline.WeightNum = Convert.ToDecimal(col21);
                    newPipeline.WeightUnit = col22;
                    newPipeline.Remark = col23;
                    newPipeline.CreateTime = DateTime.Now;
                    Funs.DB.PMI_MaterialTemplate.InsertOnSubmit(newPipeline);
                }
                else
                {
                    Funs.DB.PMI_MaterialTemplate.DeleteOnSubmit(oldTestApplication);
                    Model.PMI_MaterialTemplate newPipeline = new Model.PMI_MaterialTemplate();
                    newPipeline.MaterialId = SQLHelper.GetNewID(typeof(Model.PMI_MaterialTemplate));
                    newPipeline.ProjectId = this.CurrUser.LoginProjectId;
                    string col0 = pds.Rows[i][0].ToString().Trim();
                    string col1 = pds.Rows[i][1].ToString().Trim();
                    var unit = installations.FirstOrDefault(e => e.InstallationName == col1);
                    if (unit != null)
                    {
                        newPipeline.UnitId = unit.InstallationId;
                    }
                    string col2 = pds.Rows[i][2].ToString().Trim();
                    var AreaId = workAreas.FirstOrDefault(e => e.WorkAreaName == col2);
                    if (AreaId != null)
                    {
                        newPipeline.AreaId = unit.UnitId;
                    }
                    string col3 = pds.Rows[i][3].ToString().Trim();
                    string col4 = pds.Rows[i][4].ToString().Trim();
                    string col5 = pds.Rows[i][5].ToString().Trim();
                    string col6 = pds.Rows[i][6].ToString().Trim();
                    string col7 = pds.Rows[i][7].ToString().Trim();
                    string col8 = pds.Rows[i][8].ToString().Trim();
                    string col9 = pds.Rows[i][9].ToString().Trim();
                    string col10 = pds.Rows[i][10].ToString().Trim();
                    string col11 = pds.Rows[i][11].ToString().Trim();
                    string col12 = string.IsNullOrEmpty(pds.Rows[i][12].ToString().Trim()) == true ? "0.00" : pds.Rows[i][12].ToString().Trim();
                    string col13 = pds.Rows[i][13].ToString().Trim();
                    string col14 = pds.Rows[i][14].ToString().Trim();
                    string col15 = pds.Rows[i][15].ToString().Trim();
                    string col16 = pds.Rows[i][16].ToString().Trim();
                    string col17 = pds.Rows[i][17].ToString().Trim();
                    string col18 = pds.Rows[i][18].ToString().Trim();
                    string col19 = pds.Rows[i][19].ToString().Trim();
                    string col20 = pds.Rows[i][20].ToString().Trim();
                    string col21 = string.IsNullOrEmpty(pds.Rows[i][21].ToString().Trim()) == true ? "0.00" : pds.Rows[i][21].ToString().Trim();
                    string col22 = pds.Rows[i][22].ToString().Trim();
                    string col23 = pds.Rows[i][23].ToString().Trim();
                    //string col24 = row[24].ToString().Trim();
                    newPipeline.Discpline = col0;
                    newPipeline.UnitId = col1;
                    newPipeline.AreaId = col2;
                    var pIM_View_PmiMaterialTemplateModel = (from x in Funs.DB.PIM_View_PmiMaterialTemplate where x.ProjectId == this.CurrUser.LoginProjectId && x.InstallationName == col1 && x.UnitName == col2 select new { x.UnitId, x.UnitName, x.InstallationId, x.InstallationName }).FirstOrDefault();
                    if (pIM_View_PmiMaterialTemplateModel != null)
                    {
                        newPipeline.UnitIdName = pIM_View_PmiMaterialTemplateModel.InstallationName;
                        newPipeline.AreaIdName = pIM_View_PmiMaterialTemplateModel.UnitName;
                    }
                    newPipeline.Pipeline = col3;
                    newPipeline.ItemRule = col4;
                    newPipeline.CommoidyCode = col5;
                    newPipeline.Size1 = col6;
                    newPipeline.Size2 = col7;
                    newPipeline.IdentCode = col8;
                    newPipeline.TagNumber = col9;
                    newPipeline.IdentName = col10;
                    newPipeline.ShortDescription = col11;
                    newPipeline.Quantity = Convert.ToDecimal(col12);
                    newPipeline.UnitNum = col13;
                    newPipeline.PipeRun = col14;
                    newPipeline.Category = col5;
                    newPipeline.Material = col6;
                    newPipeline.Spec = col17;
                    newPipeline.NominalDiameter = col18;
                    newPipeline.THK = col19;
                    newPipeline.Painting = col20;
                    newPipeline.WeightNum = Convert.ToDecimal(col21);
                    newPipeline.WeightUnit = col22;
                    newPipeline.Remark = col23;
                    newPipeline.CreateTime = DateTime.Now;
                    Funs.DB.PMI_MaterialTemplate.InsertOnSubmit(newPipeline);
                }               
            }
            Funs.DB.SubmitChanges();
            ShowNotify("导入成功!", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            return true;
        }
        #endregion
        #region 导出错误提示
        /// 
        /// 导出错误提示
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            //string strFileName = DateTime.Now.ToString("yyyyMMdd-hhmmss");
            //System.Web.HttpContext HC = System.Web.HttpContext.Current;
            //HC.Response.Clear();
            //HC.Response.Buffer = true;
            //HC.Response.ContentEncoding = System.Text.Encoding.UTF8;//设置输出流为简体中文
            ////---导出为Excel文件
            //HC.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".xls");
            //HC.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
            //System.IO.StringWriter sw = new System.IO.StringWriter();
            //System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
            //this.gvErrorInfo.RenderControl(htw);
            //HC.Response.Write(sw.ToString());
            //HC.Response.End();
        }
        /// 
        /// 重载VerifyRenderingInServerForm方法,否则运行的时候会出现如下错误提示:“类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内”
        /// 
        /// 
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
        #endregion
        #region 下载模板
        /// 
        /// 下载模板按钮
        /// 
        /// 
        /// 
        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Confirm.GetShowReference("确定下载导入模板吗?", String.Empty, MessageBoxIcon.Question, PageManager1.GetCustomEventReference(false, "Confirm_OK"), PageManager1.GetCustomEventReference("Confirm_Cancel")));
        }
        /// 
        /// 下载导入模板
        /// 
        /// 
        /// 
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "Confirm_OK")
            {
                string rootPath = Server.MapPath("~/");
                string uploadfilepath = rootPath + Const.HJGL_PMITemplateUrl;
                string filePath = Const.HJGL_PMITemplateUrl;
                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
    }
}