using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
namespace FineUIPro.Web.CQMS.WBS
{
    public partial class WBSIn : PageBase
    {
        #region 定义变量
        /// 
        /// 列数量
        /// 
        public int ColumnNum
        {
            get
            {
                return (int)ViewState["ColumnNum"];
            }
            set
            {
                ViewState["ColumnNum"] = value;
            }
        }
        /// 
        /// 上传预设的虚拟路径
        /// 
        private string initPath = Const.ExcelUrl;
        /// 
        /// 错误集合
        /// 
        public static string errorInfos = string.Empty;
        #endregion
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                errorInfos = string.Empty;
                this.hdFileName.Text = string.Empty;
                this.hdCheckResult.Text = string.Empty;
                //DataTable table = BLL.WorkloadStatisticsService.GetAllTreeDataTable(this.CurrUser.LoginProjectId, string.Empty, string.Empty);
                //Grid1.DataSource = table;
                //Grid1.DataBind();
            }
        }
        #endregion
        private static int rowCount;
        #region 导出按钮
        /// 导出按钮
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            Model.SGGLDB db = Funs.DB;
            var cNProfessionals = from x in db.Base_CNProfessional select x;
            var unitWorks = from x in db.WBS_UnitWork where x.ProjectId == this.CurrUser.LoginProjectId orderby x.UnitWorkCode select x;
            var divisionProjects = (from x in db.WBS_DivisionProject where x.ProjectId == this.CurrUser.LoginProjectId select x).ToList();
            var breakdownProjects = (from x in db.WBS_BreakdownProject where x.ProjectId == this.CurrUser.LoginProjectId select x).ToList();
            if (unitWorks.Count() > 0)
            {
                try
                {
                    string projectNmae = BLL.ProjectService.GetProjectNameByProjectId(this.CurrUser.LoginProjectId);
                    if (!string.IsNullOrEmpty(projectNmae))
                    {
                        projectNmae = "(" + projectNmae + ")";
                    }
                    string rootPath = Server.MapPath("~/");
                    string initTemplatePath = string.Empty;
                    string uploadfilepath = string.Empty;
                    string newUrl = string.Empty;
                    string filePath = string.Empty;
                    initTemplatePath = Const.WBSOutTemplateUrl;
                    uploadfilepath = rootPath + initTemplatePath;
                    newUrl = uploadfilepath.Replace(".xls", projectNmae + ".xls");
                    File.Copy(uploadfilepath, newUrl);
                    // 第一步:读取文件流
                    NPOI.SS.UserModel.IWorkbook workbook;
                    using (FileStream stream = new FileStream(newUrl, FileMode.Open, FileAccess.Read))
                    {
                        workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(stream);
                    }
                    // 创建单元格样式
                    NPOI.SS.UserModel.ICellStyle cellStyle0 = workbook.CreateCellStyle();
                    cellStyle0.BorderTop = NPOI.SS.UserModel.BorderStyle.None;
                    cellStyle0.BorderRight = NPOI.SS.UserModel.BorderStyle.None;
                    cellStyle0.BorderBottom = NPOI.SS.UserModel.BorderStyle.None;
                    cellStyle0.BorderLeft = NPOI.SS.UserModel.BorderStyle.None;
                    cellStyle0.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                    cellStyle0.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                    var font = workbook.CreateFont();
                    font.FontHeightInPoints = 12;
                    font.IsBold = true;
                    //font.FontHeightInPoints = (short)8.5;字号为小数时要转为short
                    cellStyle0.SetFont(font);
                    // 第二步:创建新数据行
                    NPOI.SS.UserModel.ISheet sheet = workbook.GetSheet("Sheet1");
                    NPOI.SS.UserModel.IRow row1 = sheet.CreateRow(1);
                    NPOI.SS.UserModel.ICell cell2;
                    // 添加测试数据
                    //cell2 = row1.CreateCell(14);
                    //cell2.CellStyle = cellStyle0;
                    //cell2.SetCellValue("123");
                    //var font2 = workbook.CreateFont();
                    //font2.FontHeightInPoints = 10;
                    // 创建单元格样式
                    NPOI.SS.UserModel.ICellStyle cellStyle1 = workbook.CreateCellStyle();
                    cellStyle1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                    cellStyle1.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                    var font3 = workbook.CreateFont();
                    font3.FontHeightInPoints = 14;
                    cellStyle1.SetFont(font3);
                    NPOI.SS.UserModel.ICellStyle cellStyle2 = workbook.CreateCellStyle();
                    cellStyle2.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle2.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle2.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle2.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
                    cellStyle2.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                    cellStyle2.SetFont(font3);
                    rowCount = 1;
                    NPOI.SS.UserModel.IRow row;
                    NPOI.SS.UserModel.ICell cell;
                    string pre1 = "....";
                    #region 填充内容
                    foreach (var unitWork in unitWorks)
                    {
                        row = sheet.CreateRow(rowCount);
                        cell = row.CreateCell(0);
                        cell.CellStyle = cellStyle2;
                        cell.SetCellValue(unitWork.UnitWorkName);
                        var CV = (from x in cNProfessionals where x.CNProfessionalId == Const.CNProfessionalCVId orderby x.SortIndex select x).FirstOrDefault();
                        rowCount++;
                        row = sheet.CreateRow(rowCount);
                        cell = row.CreateCell(0);
                        cell.CellStyle = cellStyle2;
                        cell.SetCellValue(pre1 + CV.ProfessionalName);
                        var cvDivisionProjects = from x in divisionProjects
                                                 where x.CNProfessionalId == BLL.Const.CNProfessionalCVId && x.ProjectId == this.CurrUser.LoginProjectId && x.SuperDivisionId == null && x.UnitWorkId == unitWork.UnitWorkId
                                                 orderby x.SortIndex
                                                 select x;
                        rowCount++;
                        foreach (var cvDivisionProject in cvDivisionProjects)
                        {
                            row = sheet.CreateRow(rowCount);
                            cell = row.CreateCell(0);
                            cell.CellStyle = cellStyle2;
                            cell.SetCellValue(pre1 + "...." + cvDivisionProject.DivisionName);
                            rowCount++;
                            AddDetail(divisionProjects, breakdownProjects, cvDivisionProject.DivisionProjectId, pre1 + "....", row, cell, cellStyle2, sheet);
                        }
                        var azCNProfessionals = from x in cNProfessionals where x.CNProfessionalId != Const.CNProfessionalConstructId && x.CNProfessionalId != Const.CNProfessionalCVId orderby x.SortIndex select x;
                        foreach (var azCNProfessional in azCNProfessionals)
                        {
                            row = sheet.CreateRow(rowCount);
                            cell = row.CreateCell(0);
                            cell.CellStyle = cellStyle2;
                            cell.SetCellValue(pre1 + azCNProfessional.ProfessionalName);
                            var azDivisionProjects = from x in divisionProjects
                                                     where x.CNProfessionalId == azCNProfessional.CNProfessionalId && x.ProjectId == this.CurrUser.LoginProjectId && x.SuperDivisionId == null && x.UnitWorkId == unitWork.UnitWorkId
                                                     orderby x.SortIndex
                                                     select x;
                            rowCount++;
                            foreach (var azDivisionProject in azDivisionProjects)
                            {
                                row = sheet.CreateRow(rowCount);
                                cell = row.CreateCell(0);
                                cell.CellStyle = cellStyle2;
                                cell.SetCellValue(pre1 + "...." + azDivisionProject.DivisionName);
                                rowCount++;
                                AddDetail(divisionProjects, breakdownProjects, azDivisionProject.DivisionProjectId, pre1 + "....", row, cell, cellStyle2, sheet);
                            }
                        }
                    }
                    #endregion
                    // 第三步:写入文件流
                    using (FileStream stream = new FileStream(newUrl, FileMode.Create, FileAccess.Write))
                    {
                        workbook.Write(stream);
                        workbook.Close();
                    }
                    string fileName = Path.GetFileName(newUrl);
                    FileInfo info = new FileInfo(newUrl);
                    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(newUrl, 0, fileSize);
                    Response.Flush();
                    Response.Close();
                    File.Delete(newUrl);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                ShowNotify("没有数据,无法导出!", MessageBoxIcon.Warning);
            }
        }
        private void AddDetail(List divisionProjects, List breakdownProjects, string id, string prefix, NPOI.SS.UserModel.IRow row, NPOI.SS.UserModel.ICell cell, NPOI.SS.UserModel.ICellStyle cellStyle2, NPOI.SS.UserModel.ISheet sheet)
        {
            var childDivisionProjects = divisionProjects.Where(x => x.SuperDivisionId == id && x.IsSelected == true).OrderBy(x => x.SortIndex);
            if (childDivisionProjects.Count() > 0)
            {
                foreach (var childDivisionProject in childDivisionProjects)
                {
                    row = sheet.CreateRow(rowCount);
                    cell = row.CreateCell(0);
                    cell.CellStyle = cellStyle2;
                    cell.SetCellValue(prefix + "...." + childDivisionProject.DivisionName);
                    rowCount++;
                    AddDetail(divisionProjects, breakdownProjects, childDivisionProject.DivisionProjectId, prefix + "....", row, cell, cellStyle2, sheet);
                }
            }
            else
            {
                var breakdownProjectList = breakdownProjects.Where(x => x.DivisionProjectId == id && x.IsSelected == true).OrderBy(x => x.BreakdownCode);
                foreach (var breakdownProject in breakdownProjectList)
                {
                    row = sheet.CreateRow(rowCount);
                    cell = row.CreateCell(0);
                    cell.CellStyle = cellStyle2;
                    cell.SetCellValue(prefix + "...." + breakdownProject.BreakdownName);
                    cell = row.CreateCell(1);
                    cell.CellStyle = cellStyle2;
                    cell.SetCellValue(breakdownProject.RecordAndCode);
                    cell = row.CreateCell(2);
                    cell.CellStyle = cellStyle2;
                    cell.SetCellValue(breakdownProject.Class);
                    cell = row.CreateCell(3);
                    cell.CellStyle = cellStyle2;
                    cell.SetCellValue(breakdownProject.BreakdownProjectId);
                    rowCount++;
                }
            }
        }
        #endregion
        #region 审核
        /// 
        /// 审核
        /// 
        /// 
        /// 
        protected void btnAudit_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.fuAttachUrl.HasFile == false)
                {
                    ShowNotify("请您选择Excel文件!", MessageBoxIcon.Warning);
                    return;
                }
                string IsXls = Path.GetExtension(this.fuAttachUrl.FileName).ToString().Trim().ToLower();
                if (IsXls != ".xls")
                {
                    ShowNotify("只可以选择Excel文件!", MessageBoxIcon.Warning);
                    return;
                }
                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);
                ImportXlsToData(rootPath + initPath + this.hdFileName.Text);
            }
            catch (Exception ex)
            {
                ShowNotify("'" + ex.Message + "'", MessageBoxIcon.Warning);
            }
        }
        #region 读Excel提取数据
        /// 
        /// 从Excel提取数据--》Dataset
        /// 
        /// Excel文件路径名
        private void ImportXlsToData(string fileName)
        {
            try
            {
                //strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + 
                //    "data source=" + Server.MapPath("ExcelFiles/MyExcelFile.xls") + 
                //    ";Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'"; //此连接只能操作Excel2003或之前版本(.xls)文件
                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.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                oleDBConn.Close();
                oleDBConn.Dispose();
                hdCheckResult.Text = "1";
                AddDatasetToSQL(ds.Tables[0], 4);
            }
            catch (Exception exc)
            {
                Response.Write(exc);
            }
        }
        #endregion
        #region 将Dataset的数据导入数据库
        /// 
        /// 将Dataset的数据导入数据库
        /// 
        /// 数据集
        /// 数据集行数
        /// 
        private bool AddDatasetToSQL(DataTable pds, int Cols)
        {
            string result = string.Empty;
            int ic, ir;
            ic = pds.Columns.Count;
            if (ic < Cols)
            {
                ShowNotify("导入Excel格式错误!Excel只有" + ic.ToString().Trim() + "列", MessageBoxIcon.Warning);
                return false;
            }
            ir = pds.Rows.Count;
            if (pds != null && ir > 0)
            {
                var oldViewInfos = from x in Funs.DB.WBS_BreakdownProject
                                   where x.ProjectId == this.CurrUser.LoginProjectId
                                   select x;
                var units = from x in Funs.DB.Base_Unit
                            select x;
                for (int i = 0; i < ir; i++)
                {
                    string id = pds.Rows[i][3].ToString();
                    if (!string.IsNullOrEmpty(id))
                    {
                        Model.WBS_BreakdownProject oldViewInfo = oldViewInfos.FirstOrDefault(x => x.BreakdownProjectId == id);
                        if (oldViewInfo == null)
                        {
                            result += "第" + (i + 2).ToString() + "行," + "质量控制点不存在!" + "|";
                        }
                    }
                }
                if (!string.IsNullOrEmpty(result))
                {
                    result = result.Substring(0, result.LastIndexOf("|"));
                    errorInfos = result;
                    Alert alert = new Alert
                    {
                        Message = result,
                        Target = Target.Self
                    };
                    alert.Show();
                }
                else
                {
                    ShowNotify("审核完成,请点击导入!", MessageBoxIcon.Success);
                }
            }
            else
            {
                ShowNotify("导入数据为空!", MessageBoxIcon.Warning);
            }
            return true;
        }
        #endregion
        #endregion
        #region 导入
        /// 
        /// 导入
        /// 
        /// 
        /// 
        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(hdCheckResult.Text))
            {
                if (string.IsNullOrEmpty(errorInfos))
                {
                    string rootPath = Server.MapPath("~/");
                    ImportXlsToData2(rootPath + initPath + this.hdFileName.Text);
                    hdCheckResult.Text = string.Empty;
                    ShowNotify("导入成功!", MessageBoxIcon.Success);
                }
                else
                {
                    ShowNotify("请先将错误数据修正,再重新导入提交!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("请先审核要导入的文件!", 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.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                oleDBConn.Close();
                oleDBConn.Dispose();
                AddDatasetToSQL2(ds.Tables[0], 4);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        #region 将Dataset的数据导入数据库
        /// 
        /// 将Dataset的数据导入数据库
        /// 
        /// 数据集
        /// 数据集列数
        /// 
        private bool AddDatasetToSQL2(DataTable pds, int Cols)
        {
            int ic, ir;
            ic = pds.Columns.Count;
            if (ic < Cols)
            {
                ShowNotify("导入Excel格式错误!Excel只有" + ic.ToString().Trim() + "列", MessageBoxIcon.Warning);
            }
            string result = string.Empty;
            ir = pds.Rows.Count;
            if (pds != null && ir > 0)
            {
                Model.SGGLDB db = Funs.DB;
                var oldViewInfos = from x in db.WBS_BreakdownProject
                                   where x.ProjectId == this.CurrUser.LoginProjectId
                                   select x;
                for (int i = 0; i < ir; i++)
                {
                    string id = pds.Rows[i][3].ToString();
                    if (!string.IsNullOrEmpty(id))
                    {
                        Model.WBS_BreakdownProject breakdownProject = oldViewInfos.FirstOrDefault(x => x.BreakdownProjectId == id);
                        if (breakdownProject != null)
                        {
                            breakdownProject.RecordAndCode= pds.Rows[i][1].ToString();
                            breakdownProject.Class = pds.Rows[i][2].ToString();
                        }
                    }
                }
                db.SubmitChanges();
                ShowNotify("导入成功!", MessageBoxIcon.Success);
            }
            else
            {
                ShowNotify("导入数据为空!", MessageBoxIcon.Warning);
            }
            return true;
        }
        #endregion
        #endregion
    }
}