using BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.JDGL.SGManPower
{
    public partial class ManPowerPlanIn : PageBase
    {
        #region 定义变量
        /// 
        /// 上传预设的虚拟路径
        /// 
        private string initPath = Const.ExcelUrl;
        /// 
        /// 人力计划集合
        /// 
        public static List SGManPowers = new List();
        /// 
        /// 错误集合
        /// 
        public static List errorInfos = new List();
        /// 
        /// 项目ID
        /// 
        public string ProjectId
        {
            get { return (string)ViewState["ProjectId"]; }
            set { ViewState["ProjectId"] = value; }
        }
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.hdFileName.Text = string.Empty;
                if (SGManPowers != null)
                {
                    SGManPowers.Clear();
                }
                if (errorInfos != null)
                {
                    errorInfos.Clear();
                }
                this.ProjectId = Request.Params["ProjectId"];
                
            }
        }
        #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;
                }
                if (SGManPowers != null)
                {
                    SGManPowers.Clear();
                }
                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;
                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
            {
                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();
                AddDatasetToSQL(ds.Tables[0], 4);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #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)
            {
                Alert.ShowInTop("导入Excel格式错误!Excel只有" + ic.ToString().Trim() + "行", MessageBoxIcon.Warning);
            }
            ir = pds.Rows.Count;
            Model.SGGLDB db = Funs.DB;
            var projectUnits = from x in db.Project_ProjectUnit
                join y in db.Base_Unit on x.UnitId equals y.UnitId
                where x.ProjectId == this.ProjectId
                select new { x.UnitId, y.UnitName, x.UnitType };
            var unitWorks = from x in Funs.DB.WBS_UnitWork
                where x.ProjectId == ProjectId && (x.SuperUnitWork == null || x.SuperUnitWork == "0")
                select new { x.UnitWorkId, x.UnitWorkName };
            var workPosts = from x in Funs.DB.Base_WorkPost
                select new { x.WorkPostId, x.WorkPostName, x.PostType };
            
            if (pds != null && ir > 0)
            {
                var UnitType = string.Empty; //1:总包 2:分包
                var PostType = string.Empty; //1:一般管理岗位 4:特种管理岗位
                string UnitId = null; 
                string UnitWorkId = null; 
                string WorkPostId = null; 
                for (int i = 0; i < ir; i++)
                {
                    string col0 = pds.Rows[i][0].ToString().Trim();
                    if (string.IsNullOrEmpty(col0))
                    {
                        result += $"{i + 2}&单位&不能为空!|";
                    }
                    else
                    {
                        var unit = projectUnits.FirstOrDefault(e => e.UnitName == col0);
                        if (unit == null)
                        {
                            result += $"{i + 2}&单位&不在项目单位中!|";
                        }
                        else
                        {
                            UnitType = unit.UnitType;
                            UnitId = unit.UnitId;
                        }
                    }
                    string col2 = pds.Rows[i][2].ToString().Trim(); //岗位
                    if (string.IsNullOrEmpty(col2))
                    {
                        result += $"{i + 2}&岗位&不能为空!|";
                    }
                    else
                    {
                        var workPost = workPosts.FirstOrDefault(e => e.WorkPostName == col2);
                        if (workPost == null)
                        {
                            result += $"{i + 2}&岗位&不存在此岗位名称!|";
                        }
                        else
                        {
                            PostType = workPost.PostType;
                            WorkPostId = workPost.WorkPostId;
                        }
                    }
                    string col1 = pds.Rows[i][1].ToString().Trim(); //装置
                    if (UnitType == "1" || (UnitType == "2" && (PostType == "1" || PostType == "4")))
                    {
                        //可以不选装置
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(col1))
                        {
                            result += $"{i + 2}&装置&总承包单位不需要区分装置,施工分包单位管理人员不需要区分装置,作业人员需要区分装置!!|";
                        }
                        else
                        {
                            var unitWork = unitWorks.FirstOrDefault(e => e.UnitWorkName == col1);
                            if (unitWork == null)
                            {
                                result += $"{i + 2}&装置&不在项目装置中!|";
                            }else
                            {
                                UnitWorkId = unitWork.UnitWorkId;
                            }
                        }
                    }
                    string col3 = pds.Rows[i][3].ToString().Trim(); //版本
                    if (string.IsNullOrEmpty(col3))
                    {
                        result += $"{i + 2}&版本&不能为空!|";
                    }
                    // 遍历日期列
                    for (int col = 4; col < ic; col++)
                    {
                        string dateStr = pds.Columns[col].ColumnName;
                        string quantityStr = pds.Rows[i][col].ToString().Trim();
                        if (!string.IsNullOrEmpty(dateStr) && !string.IsNullOrEmpty(quantityStr))
                        {
                            DateTime planDate;
                            if (!DateTime.TryParse(dateStr, out planDate))
                            {
                                result += $"{i + 2}&日期&格式错误!|";
                                continue;
                            }
                            int quantity;
                            if (!int.TryParse(quantityStr, out quantity))
                            {
                                result += $"{i + 2}&数量&格式错误!|";
                                continue;
                            }
                            // 检查数据是否重复
                            var lists = (from x in Funs.DB.JDGL_SGManPower
                                where x.ProjectId == this.ProjectId && x.UnitId == UnitId && 
                                      (UnitWorkId == null ? x.UnitWorkId == null : x.UnitWorkId == UnitWorkId) && 
                                      x.WorkPostId == WorkPostId && x.Version == col3 && x.PlanDate.HasValue &&
                                      x.PlanDate.Value == planDate
                                select x).ToList();
                            if (lists.Count > 0)
                            {
                                result += $"{i + 2}&{dateStr}&数据已存在!|";
                            }
                        }
                    }
                }
                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)
                    {
                        this.gvErrorInfo.DataSource = errorInfos;
                        this.gvErrorInfo.DataBind();
                    }
                }
                else
                {
                    ShowNotify("审核完成,请点击导入!", MessageBoxIcon.Success);
                }
            }
            else
            {
                ShowNotify("导入数据为空!", MessageBoxIcon.Warning);
            }
            return true;
        }
        #endregion
        #endregion
        #region 导入
        
        /// 
        /// 导入
        /// 
        /// 
        /// 
        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (errorInfos.Count <= 0)
            {
                if (!string.IsNullOrEmpty(this.hdFileName.Text))
                {
                    string rootPath = Server.MapPath("~/");
                    ImportXlsToData2(rootPath + initPath + this.hdFileName.Text);
                }
                else
                {
                    ShowNotify("请先审核要导入的文件!", MessageBoxIcon.Warning);
                }
            }
            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.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;
            SGManPowers.Clear();
            ic = pds.Columns.Count;
            if (ic < Cols)
            {
                Alert.ShowInTop("导入Excel格式错误!Excel只有" + ic.ToString().Trim() + "列", MessageBoxIcon.Warning);
            }
        
            ir = pds.Rows.Count;
            Model.SGGLDB db = Funs.DB;
            var projectUnits = from x in db.Project_ProjectUnit
                join y in db.Base_Unit on x.UnitId equals y.UnitId
                where x.ProjectId == this.ProjectId
                select new { x.UnitId, y.UnitName };
        
            var unitWorks = from x in Funs.DB.WBS_UnitWork
                where x.ProjectId == ProjectId && (x.SuperUnitWork == null || x.SuperUnitWork == "0")
                select new { x.UnitWorkId, x.UnitWorkName };
        
            var workPosts = from x in Funs.DB.Base_WorkPost
                select new { x.WorkPostId, x.WorkPostName };
        
        
            if (pds != null && ir > 0)
            {
                for (int i = 0; i < ir; i++)
                {
                    string col0 = pds.Rows[i][0].ToString().Trim(); // 单位
                    string col1 = pds.Rows[i][1].ToString().Trim(); // 装置
                    string col2 = pds.Rows[i][2].ToString().Trim(); // 岗位
                    string col3 = pds.Rows[i][3].ToString().Trim(); // 版本
        
                    if (!string.IsNullOrEmpty(col0)) // 单位
                    {
                        var projectUnit = projectUnits.FirstOrDefault(x => x.UnitName == col0);
                        if (projectUnit != null)
                        {
                            // 遍历日期列(从第5列开始)
                            for (int col = 4; col < ic; col++)
                            {
                                string colDate = pds.Columns[col].ColumnName; // 日期列名
                                string colQuantity = pds.Rows[i][col].ToString().Trim(); // 人数
        
                                if (!string.IsNullOrEmpty(colQuantity) && int.TryParse(colQuantity, out int quantity))
                                {
                                    // 确保日期列名是有效的日期格式
                                    if (DateTime.TryParse(colDate, out DateTime planDate))
                                    {
                                        Model.JDGL_SGManPower newManPower = new Model.JDGL_SGManPower
                                        {
                                            UnitId = projectUnit.UnitId,
                                            UnitWorkId = string.IsNullOrEmpty(col1)
                                                ? null
                                                : unitWorks.FirstOrDefault(x => x.UnitWorkName == col1)?.UnitWorkId,
                                            WorkPostId = workPosts.FirstOrDefault(x => x.WorkPostName == col2)
                                                ?.WorkPostId,
                                            Version = col3,
                                            Quantity = quantity,
                                            PlanDate = planDate,
                                            Id = SQLHelper.GetNewID(typeof(Model.JDGL_SGManPower))
                                        };
        
                                        SGManPowers.Add(newManPower);
                                    }
                                }
                            }
                        }
                    }
                }
                int a = SGManPowers.Count();
                for (int i = 0; i < a; i++)
                {
                    Model.JDGL_SGManPower newData = new Model.JDGL_SGManPower();
                    newData.Id = SQLHelper.GetNewID(typeof(Model.JDGL_SGManPower));
                    newData.ProjectId = this.ProjectId;
                    newData.UnitId = SGManPowers[i].UnitId;
                    newData.UnitWorkId = SGManPowers[i].UnitWorkId;
                    newData.WorkPostId = SGManPowers[i].WorkPostId;
                    newData.Version = SGManPowers[i].Version;
                    newData.Quantity = SGManPowers[i].Quantity;
                    newData.PlanDate = SGManPowers[i].PlanDate;
                    newData.CompileMan = this.CurrUser.UserId;
                    newData.CompileTime = DateTime.Now;
                    newData.Remarks = SGManPowers[i].Remarks;
                    BLL.ManPowerPlanService.AddSGManPower(newData);
                }
                
                string rootPath = Server.MapPath("~/");
                string initFullPath = rootPath + initPath;
                string filePath = initFullPath + this.hdFileName.Text;
                if (filePath != string.Empty && System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath); //删除上传的XLS文件
                }
        
                ShowNotify("导入成功!", MessageBoxIcon.Success);
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                ShowNotify("导入数据为空!", MessageBoxIcon.Warning);
            }
        
            return true;
        }
        
        #endregion
        
        #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.SGManPowerTemplateUrl;
                string filePath = Const.SGManPowerTemplateUrl;
                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 根据id获取姓名
        /// 
        /// 
        /// 
        /// 
        /// 
        protected string ConvertUnitName(object UnitId)
        {
            string name = string.Empty;
            if (UnitId != null)
            {
                name = BLL.UnitService.GetUnitNameByUnitId(UnitId.ToString());
            }
            return name;
        }
        protected string ConvertUnitWorkName(object UnitWorkId)
        {
            string name = string.Empty;
            if (UnitWorkId != null)
            {
                name = BLL.UnitWorkService.GetNameById(UnitWorkId.ToString());
            }
            return name;
        }
        protected string ConvertWorkPostName(object WorkPostId)
        {
            string name = string.Empty;
            if (WorkPostId != null)
            {
                name = BLL.WorkPostService.getWorkPostNameById(WorkPostId.ToString());
            }
            return name;
        }
        #endregion
    }
}