using BLL;
using FineUIPro.Web.SysManage;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.HSSE.Hazard
{
    public partial class ConstructionRiskDataIn : PageBase
    {
        #region 定义变量
        /// 
        /// 上传预设的虚拟路径
        /// 
        private string initPath = Const.ExcelUrl;
        /// 
        /// 导入模版文件原始的虚拟路径
        /// 
        private string initTemplatePath = Const.ConstructionRiskTemplateUrl;
        /// 
        /// 错误集合
        /// 
        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 imgbtnUpload_Click(object sender, EventArgs e)
        {
            string uploadfilepath = Server.MapPath("~/") + initTemplatePath;
            string fileName = Path.GetFileName(initTemplatePath);
            FileInfo info = new FileInfo(uploadfilepath);
            if (info.Exists)
            {
                long fileSize = info.Length;
                Response.Clear();
                Response.ContentType = "application/x-zip-compressed";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                Response.AddHeader("Content-Length", fileSize.ToString());
                Response.TransmitFile(uploadfilepath, 0, fileSize);
                Response.Flush();
                Response.Close();
            }
            else
            {
                ShowNotify("文件不存在!", MessageBoxIcon.Warning);
            }
        }
        #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], 14);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #endregion
        /// 
        /// 将Dataset的数据导入数据库
        /// 
        /// 数据集
        /// 数据集列数
        /// 
        private bool AddDatasetToSQL(DataTable pds, int Cols)
        {
            string result = string.Empty;
            int ic, ir;
            ic = pds.Columns.Count;
           
            ir = pds.Rows.Count;
            if (pds != null && ir > 0)
            {
                var units = from x in Funs.DB.Base_Unit select x;
                var unitWorks = from x in Funs.DB.WBS_UnitWork where x.ProjectId == CurrUser.LoginProjectId select x;
                for (int i = 0; i < ir; i++)
                {
                    string row0 = pds.Rows[i][0].ToString().Trim();
                    string row1 = pds.Rows[i][1].ToString().Trim();
                    string row2 = pds.Rows[i][2].ToString().Trim();
                    string row3 = pds.Rows[i][3].ToString().Trim();
                    string row4 = pds.Rows[i][4].ToString().Trim();
                    string row5 = pds.Rows[i][5].ToString().Trim();
                    string row6 = pds.Rows[i][6].ToString().Trim();
                    string row7 = pds.Rows[i][7].ToString().Trim();
                    string row8 = pds.Rows[i][8].ToString().Trim();
                    if (string.IsNullOrEmpty(row0))
                    {
                        result += (i + 2).ToString() + "," + "本周开始时间" + "," + "此项为必填项!" + "|";
                    }
                    if (string.IsNullOrEmpty(row1))
                    {
                        result += (i + 2).ToString() + "," + "本周结束时间" + "," + "此项为必填项!" + "|";
                    }
                    if (string.IsNullOrEmpty(row2))
                    {
                        result += (i + 2).ToString() + "," + "单位工程" + "," + "此项为必填项!" + "|";                        
                    }
                    else
                    {
                        var unitWork = unitWorks.Where(x => x.UnitWorkName == row2.Trim()).FirstOrDefault();
                        if (unitWork == null)
                        {
                            result += (i + 2).ToString() + "," + "单位工程" + "," + "此项目不存在!" + "|";
                        }
                    }
                    if (string.IsNullOrEmpty(row3))
                    {
                        result += (i + 2).ToString() + "," + "单位工程" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        var unit  = units.Where(x => x.UnitName == row3.Trim()).FirstOrDefault();
                        if (unit == null)
                        {
                            result += (i + 2).ToString() + "," + "单位" + "," + "此项目不存在!" + "|";
                        }
                    }
                    if (string.IsNullOrEmpty(row4))
                    {
                        result += (i + 2).ToString() + "," + "施工内容" + "," + "此项为必填项!" + "|";
                    }
                    if (string.IsNullOrEmpty(row5))
                    {
                        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;
        }
        #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);
            }
        }
        #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 = 1200;
                oleAdMaster.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                oleDBConn.Close();
                oleDBConn.Dispose();
                AddDatasetToSQL2(ds.Tables[0]);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        /// 
        /// 将Dataset的数据导入数据库
        /// 
        /// 数据集
        /// 数据集列数
        /// 
        private bool AddDatasetToSQL2(DataTable pds)
        {
            string result = string.Empty;
            string dReportID = string.Empty;
            string dateStr = string.Empty;
            int  ir;
            string des = "";
            ir = pds.Rows.Count;
            if (pds != null && ir > 0)
            {
                Model.HSSE_ConstructionRisk newConstructionRisk = null;
                var units = from x in Funs.DB.Base_Unit select x;
                var unitWorks = from x in Funs.DB.WBS_UnitWork where x.ProjectId == CurrUser.LoginProjectId select x;
                int index = 1;
                for (int i = 0; i < ir; i++)
                {
                    string row0 = pds.Rows[i][0].ToString().Trim();
                    string row1 = pds.Rows[i][1].ToString().Trim();
                    string row2 = pds.Rows[i][2].ToString().Trim();
                    string row3 = pds.Rows[i][3].ToString().Trim();
                    string row4 = pds.Rows[i][4].ToString().Trim();
                    string row5 = pds.Rows[i][5].ToString().Trim();
                    string row6 = pds.Rows[i][6].ToString().Trim();
                    string row7 = pds.Rows[i][7].ToString().Trim();
                    string row8 = pds.Rows[i][8].ToString().Trim();
                    var unit = units.Where(x => x.UnitName == row3).FirstOrDefault();
                    var unitWork = unitWorks.Where(x => x.UnitWorkName == row2).FirstOrDefault();
                    if (des != row4)
                    {
                        index = 1;
                        newConstructionRisk = new Model.HSSE_ConstructionRisk();
                        newConstructionRisk.ConstructionRiskId = SQLHelper.GetNewID(typeof(Model.HSSE_ConstructionRisk));
                        newConstructionRisk.ProjectId = this.CurrUser.LoginProjectId;
                        newConstructionRisk.UnitId = unit.UnitId;
                        newConstructionRisk.WorkAreaId = unitWork.UnitWorkId;
                        try
                        {
                            newConstructionRisk.DateA = Funs.GetNewDateTime(row0);
                            newConstructionRisk.DateWeek = newConstructionRisk.DateA.Value.ToString("yyyy年") + Funs.GetWeekOfYear(newConstructionRisk.DateA.Value)+"周";
                        }
                        catch (Exception e) { }
                        try
                        {
                            newConstructionRisk.DateZ = Funs.GetNewDateTime(row1);
                        }
                        catch (Exception e) { }
                        newConstructionRisk.ConstructionContent = row4;
                        newConstructionRisk.RefLicense = row5;
                        newConstructionRisk.LicenseDes = row6;
                        newConstructionRisk.RiskLevel = row7;
                        Funs.DB.HSSE_ConstructionRisk.InsertOnSubmit(newConstructionRisk);
                        des = row4;
                    }
                    Model.HSSE_ConstructionRiskControl constructionRiskControl = new Model.HSSE_ConstructionRiskControl();
                    constructionRiskControl.ControlId = SQLHelper.GetNewID(typeof(Model.HSSE_ConstructionRiskControl));
                    constructionRiskControl.ConstructionRiskId = newConstructionRisk.ConstructionRiskId;
                    constructionRiskControl.Measures = row8;
                    constructionRiskControl.ShowIndex = index;
                    Funs.DB.HSSE_ConstructionRiskControl.InsertOnSubmit(constructionRiskControl);
                }
                Funs.DB.SubmitChanges();
                ShowNotify("导入成功!", MessageBoxIcon.Success);
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                throw new Exception("导入数据为空!");
            }
            return true;
        }
        #endregion
    }
}