using BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WIA;
namespace FineUIPro.Web.CQMS.Foreign
{
    public partial class ITPListProjectDataIn : PageBase
    {
        #region 定义变量
        /// 
        /// 上传预设的虚拟路径
        /// 
        private string initPath = Const.ExcelUrl;
        /// 
        /// 人员集合
        /// 
        public static List ITPList = new List();
        /// 
        /// 错误集合
        /// 
        public static string errorInfos = string.Empty;
        #endregion
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.hdCheckResult.Text = string.Empty;
                this.hdFileName.Text = string.Empty;
                if (ITPList != null)
                {
                    ITPList.Clear();
                }
                errorInfos = "";
            }
        }
        #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 (ITPList != null)
                {
                    ITPList.Clear();
                }
                errorInfos = "";
                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)
        {
            //支持.xls和.xlsx,即包括office2010等版本的   HDR=Yes代表第一行是标题,不是数据;
            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;
            try
            {
                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]);
            }
            catch (Exception exc)
            {
                Response.Write(exc);
                //return null;
                // return dt;
            }
            finally
            {
                oleDBConn.Close();
                oleDBConn.Dispose();
            }
        }
        #endregion
        #region 将Dataset的数据导入数据库
        /// 
        /// 将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 oldViewInfos = from x in Funs.DB.Comprehensive_InspectionMachine
                                   where x.ProjectId == this.CurrUser.LoginProjectId
                                   select x;
                var units = from x in Funs.DB.Base_Unit
                            join y in Funs.DB.Project_ProjectUnit on x.UnitId equals y.UnitId
                            where y.ProjectId == this.CurrUser.LoginProjectId
                            select x;
                var unitWorks = from x in Funs.DB.WBS_UnitWork
                            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 cns = from x in Funs.DB.Base_CNProfessional select x;
                for (int i = 0; i < ir; i++)
                {
                    Model.CQMS_Foreign_ITPListProject oldViewInfo = null;
                    oldViewInfo = Funs.DB.CQMS_Foreign_ITPListProject.Where(x => x.DocCode == pds.Rows[i][5].ToString().Trim()
                                                     ).FirstOrDefault();
                    if (oldViewInfo == null)
                    {
                        oldViewInfo = new Model.CQMS_Foreign_ITPListProject();
                    }
                    oldViewInfo.ProjectId = CurrUser.LoginProjectId;
                    oldViewInfo.CompileDate = DateTime.Now;
                    oldViewInfo.CompileMan = CurrUser.UserId;
                    string row1 = pds.Rows[i][1].ToString().Trim();
                    if (string.IsNullOrEmpty(row1))
                    {
                        result += (i + 2).ToString() + "," + "单位名称" + "," + "[]必填!" + "|";
                    }
                    else
                    {
                        var unitInfo = units.Where(y => y.UnitName == row1).FirstOrDefault();
                        if (unitInfo == null)
                        {
                            result += (i + 2).ToString() + "," + "单位名称" + "," + "[" + row1 + "]不存在!" + "|";
                        }
                        else
                        {
                            oldViewInfo.UnitId = unitInfo.UnitId;
                        }
                    }
                    string row2 = pds.Rows[i][2].ToString().Trim();
                    if (string.IsNullOrEmpty(row2))
                    {
                        result += (i + 2).ToString() + "," + "装置" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        var installation = installations.Where(u => u.InstallationName == row2).FirstOrDefault();
                        if (installation == null)
                        {
                            result += (i + 2).ToString() + "," + "装置" + "," + "[" + row2 + "]不存在!" + "|";
                        }
                        else
                        {
                            oldViewInfo.InstallationId = installation.InstallationId;
                        }
                    }
                    string row3 = pds.Rows[i][3].ToString().Trim();
                    if (string.IsNullOrEmpty(row3))
                    {
                        result += (i + 2).ToString() + "," + "专业" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        var CNProfessional = cns.Where(u => u.ProfessionalName == row3).FirstOrDefault();
                        if (CNProfessional == null)
                        {
                            result += (i + 2).ToString() + "," + "专业" + "," + "[" + row2 + "]不存在!" + "|";
                        }
                        else
                        {
                            oldViewInfo.CNProfessionalCode = CNProfessional.CNProfessionalId;
                        }
                    }
                    string row4 = pds.Rows[i][4].ToString().Trim();
                    if (string.IsNullOrEmpty(row4))
                    {
                        result += (i + 2).ToString() + "," + "单位工程" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        var WorkArea = unitWorks.Where(u => u.UnitWorkName == row4).FirstOrDefault();
                        if (WorkArea == null)
                        {
                            result += (i + 2).ToString() + "," + "单位工程" + "," + "[" + row4 + "]不存在!" + "|";
                        }
                        else
                        {
                            oldViewInfo.UnitWorkId = WorkArea.UnitWorkId;
                        }
                    }
                    string row5 = pds.Rows[i][5].ToString().Trim();
                    if (string.IsNullOrEmpty(row5))
                    {
                        result += (i + 2).ToString() + "," + "报验编号" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        oldViewInfo.DocCode = row5;
                    }
                    string row6 = pds.Rows[i][6].ToString().Trim();
                    if (string.IsNullOrEmpty(row6))
                    {
                        result += (i + 2).ToString() + "," + "报验文件类别" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        oldViewInfo.FileType = row6;
                    }
                    string row7 = pds.Rows[i][7].ToString().Trim();
                    if (string.IsNullOrEmpty(row7))
                    {
                        result += (i + 2).ToString() + "," + "报验内容" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        oldViewInfo.CheckContent = row7;
                    }
                    string row8 = pds.Rows[i][8].ToString().Trim();
                    if (string.IsNullOrEmpty(row7))
                    {
                        result += (i + 2).ToString() + "," + "检查等级" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        if (row8 == "A" || row8 == "B" || row8 == "C")
                        {
                            oldViewInfo.CheckLevel = row8;
                        }
                        else
                        {
                            result += (i + 2).ToString() + "," + "检查等级" + "," + "[" + row4 + "]不为A、B、C!" + "|";
                        }
                    }
                    string row9 = pds.Rows[i][9].ToString().Trim();
                    if (string.IsNullOrEmpty(row7))
                    {
                        result += (i + 2).ToString() + "," + "报验日期" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        try
                        {
                            DateTime date = Convert.ToDateTime(row9.Trim());
                            oldViewInfo.CheckDate = date;
                        }
                        catch (Exception)
                        {
                            result += (i + 2).ToString() + "," + "报验日期" + "," + "[" + row9 + "]错误!" + "|";
                        }
                    }
                    oldViewInfo.Memo = pds.Rows[i][10].ToString().Trim();
                    ITPList.Add(oldViewInfo);
                }
                if (!string.IsNullOrEmpty(result))
                {
                    result = result.Substring(0, result.LastIndexOf("|"));
                }
               
                if (!string.IsNullOrEmpty(result))
                {
                    ITPList.Clear();
                   // result = result.Substring(0, result.LastIndexOf("|"));
                    errorInfos = result;
                    Alert alert = new Alert
                    {
                        Message = result,
                        Target = Target.Self
                    };
                    alert.Show();
                }
                else
                {
                    result = "";
                    this.Grid1.Hidden = false;
                    this.Grid1.DataSource = ITPList;
                    this.Grid1.DataBind();
                    ShowNotify("审核完成,请点击导入!", MessageBoxIcon.Success);
                }
            }
            else
            {
                ShowNotify("导入数据为空!", MessageBoxIcon.Warning);
            }
            return true;
        }
        #endregion
        #endregion
        #region 导入
        /// 
        /// 导入
        /// 
        /// 
        /// 
        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(errorInfos))
            {
                int a = ITPList.Count();
                int insertCount = 0;
                for (int i = 0; i < a; i++)
                {
                    Model.CQMS_Foreign_ITPListProject newUser = new Model.CQMS_Foreign_ITPListProject
                    {
                        ITPListId = Guid.NewGuid().ToString(),
                        ProjectId = ITPList[i].ProjectId,
                        CompileMan = ITPList[i].CompileMan,
                        CompileDate = ITPList[i].CompileDate,
                        UnitId = ITPList[i].UnitId,
                        InstallationId = ITPList[i].InstallationId,
                        UnitWorkId = ITPList[i].UnitWorkId,
                        CNProfessionalCode = ITPList[i].CNProfessionalCode,
                        DocCode = ITPList[i].DocCode,
                        CheckLevel = ITPList[i].CheckLevel,
                        CheckContent = ITPList[i].CheckContent,
                        CheckDate = ITPList[i].CheckDate,
                        FileType = ITPList[i].FileType,
                        Memo = ITPList[i].Memo
                    };
                    Funs.DB.CQMS_Foreign_ITPListProject.InsertOnSubmit(newUser);
                    //newUser.UserId = getUser.UserId;
                    insertCount++;
                }
                Funs.DB.SubmitChanges();
                string rootPath = Server.MapPath("~/");
                string initFullPath = rootPath + initPath;
                string filePath = initFullPath + this.hdFileName.Text;
                if (filePath != string.Empty && File.Exists(filePath))
                {
                    File.Delete(filePath);//删除上传的XLS文件
                }
                ShowNotify("导入完成!插入" + insertCount.ToString() + "条。", MessageBoxIcon.Success);
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                ShowNotify("请先将错误数据修正,再重新导入提交!", MessageBoxIcon.Warning);
            }
        }
        #region Excel提取数据
        /// 
        /// 从Excel提取数据--》Dataset
        /// 
        /// Excel文件路径名
        private void ImportXlsToData2(string fileName)
        {
            //支持.xls和.xlsx,即包括office2010等版本的   HDR=Yes代表第一行是标题,不是数据;
            string cmdText = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
            //建立连接
            OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileName));
            try
            {
                //打开连接
                if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                OleDbDataAdapter oleAdMaster = null;
                DataTable m_tableName = new DataTable();
                DataSet ds = new DataSet();
                m_tableName = conn.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, conn);
                oleAdMaster.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                conn.Close();
                conn.Dispose();
                AddDatasetToSQL2(ds.Tables[0], 13);
            }
            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)
            {
                var oldViewInfos = from x in Funs.DB.CQMS_Foreign_ITPListProject
                                   where x.ProjectId == this.CurrUser.LoginProjectId
                                   select x;
                var units = from x in Funs.DB.Base_Unit
                            join y in Funs.DB.Project_ProjectUnit on x.UnitId equals y.UnitId
                            where y.ProjectId == this.CurrUser.LoginProjectId
                            select x;
                var installtion = from x in Funs.DB.Project_Installation
                                  where x.ProjectId == this.CurrUser.LoginProjectId
                                  select x;
                var workarea= from x in Funs.DB.ProjectData_WorkArea
                              where x.ProjectId == this.CurrUser.LoginProjectId
                              select x;
                var cns = from x in Funs.DB.Base_CNProfessional select x;
                for (int i = 0; i < ir; i++)
                {
                    Model.CQMS_Foreign_ITPListProject oldViewInfo = new Model.CQMS_Foreign_ITPListProject();
                    string row0 = pds.Rows[i][1].ToString().Trim();
                    var unitInfo = units.Where(y => y.UnitName == row0).FirstOrDefault();
                    if (unitInfo != null && !string.IsNullOrEmpty(row0))
                    {
                        oldViewInfo = oldViewInfos.Where(x => x.UnitId == unitInfo.UnitId
                                                           && x.InstallationId == pds.Rows[i][1].ToString().Trim() && x.UnitWorkId == pds.Rows[i][2].ToString().Trim()
                                                         ).FirstOrDefault();
                        if (oldViewInfo == null)
                        {
                            Model.CQMS_Foreign_ITPListProject Ins = new Model.CQMS_Foreign_ITPListProject();
                            Ins.ProjectId = this.CurrUser.LoginProjectId;
                            Ins.UnitId = unitInfo.UnitId;
                            Ins.CheckContent = pds.Rows[i][1].ToString().Trim();
                            Ins.FileType = pds.Rows[i][2].ToString().Trim();
                            if (!string.IsNullOrEmpty(pds.Rows[i][3].ToString().Trim()))
                            {
                                Ins.CNProfessionalCode = Funs.DB.Base_CNProfessional.First(e => e.ProfessionalName == pds.Rows[i][3].ToString().Trim()).CNProfessionalId;
                            }
                            if (!string.IsNullOrEmpty(pds.Rows[i][9].ToString().Trim()))
                            {
                                Ins.CheckContent =pds.Rows[i][9].ToString().Trim();
                            }
                            if (!string.IsNullOrEmpty(pds.Rows[i][10].ToString().Trim()))
                            {
                                Ins.Memo = pds.Rows[i][10].ToString().Trim();
                            }
                            if (!string.IsNullOrEmpty(pds.Rows[i][11].ToString().Trim()))
                            {
                                Ins.CheckDate = Convert.ToDateTime(pds.Rows[i][9].ToString().Trim());
                            }
                            Ins.ITPListId = SQLHelper.GetNewID(typeof(Model.Comprehensive_InspectionMachine));
                            Ins.CompileMan = this.CurrUser.UserId;
                            Ins.CompileDate = DateTime.Now.Date;
                            BLL.ITPListProjectService.AddITPListProject(Ins);
                        }
                        else
                        {
                            result += (i + 2).ToString() + "," + "报验编号" + "," + "该单位报验编号已存在!" + "|";
                        }
                    }
                    else
                    {
                        result += (i + 2).ToString() + "," + "单位名称" + "," + "[" + row0 + "]不存在!" + "|";
                    }
                }
                
            }
            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.ITPDataInUrl;
                string filePath = Const.ITPDataInUrl;
                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
        protected string ConvertType(object state)
        {
            if (state != null)
            {
                if (state.ToString() == "1")
                {
                    return "建筑工程";
                }
                else if (state.ToString() == "2")
                {
                    return "安装工程";
                }
            }
            return "";
        }
        protected string ConvertUnitName(object UnitId)
        {
            if (UnitId != null)
            {
                var unit = Funs.DB.Base_Unit.Where(u => u.UnitId == UnitId.ToString()).FirstOrDefault();
                if (unit != null)
                {
                    return unit.UnitName;
                }
            }
            return "";
        }
        protected string ConvertInstallationName(object installationId)
        {
            if (installationId != null)
            {
                var installation = Funs.DB.Project_Installation.Where(u => u.InstallationId == installationId.ToString()).FirstOrDefault();
                if (installation != null)
                {
                    return installation.InstallationName;
                }
            }
            return "";
        }
        protected string ConvertWorkAreaName(object workAreaId)
        {
            if (workAreaId != null)
            {
                var WorkArea = Funs.DB.WBS_UnitWork.Where(u => u.UnitWorkId == workAreaId.ToString()).FirstOrDefault();
                if (WorkArea != null)
                {
                    return WorkArea.UnitWorkName;
                }
            }
            return "";
        }
        protected string ConvertCNProfessionalName(object CNProfessionalId)
        {
            if (CNProfessionalId != null)
            {
                var CNProfessional = Funs.DB.Base_CNProfessional.Where(u => u.CNProfessionalId == CNProfessionalId.ToString()).FirstOrDefault();
                if (CNProfessional != null)
                {
                    return CNProfessional.ProfessionalName;
                }
            }
            return "";
        }
       
    }
}