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.WebControls;
namespace FineUIPro.Web.HJGL.WeldingManage
{
    public partial class CheckManageDataIn : PageBase
    {
        #region 定义变量
        /// 
        /// 检测方法
        /// 
        public string DetectionTypeId
        {
            get
            {
                return (string)ViewState["DetectionTypeId"];
            }
            set
            {
                ViewState["DetectionTypeId"] = value;
            }
        }
        /// 
        /// 检测方法代号
        /// 
        public string DetectionTypeCode
        {
            get
            {
                return (string)ViewState["DetectionTypeCode"];
            }
            set
            {
                ViewState["DetectionTypeCode"] = value;
            }
        }
        /// 
        /// 上传预设的虚拟路径
        /// 
        private string initPath = Const.ExcelUrl;
        /// 
        /// 导入模版文件原始的虚拟路径
        /// 
        private string initTemplatePath = string.Empty; 
        /// 
        /// 错误集合
        /// 
        public static List errorInfos = new List();
        #endregion
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.DetectionTypeId = Request.Params["detectionTypeId"];
                if (!string.IsNullOrEmpty(this.DetectionTypeId))
                {
                    var deectionType = BLL.Base_DetectionTypeService.GetDetectionTypeByDetectionTypeId(this.DetectionTypeId);
                    if (deectionType != null)
                    {
                        this.DetectionTypeCode = deectionType.DetectionTypeCode;
                    }
                }
                if (errorInfos != null)
                {
                    errorInfos.Clear();
                }
            }
        }
        #endregion 
        #region 模板下载
        /// 
        /// 模板下载
        /// 
        /// 
        /// 
        protected void imgbtnUpload_Click(object sender, EventArgs e)
        {
            var detectionType = BLL.Base_DetectionTypeService.GetDetectionTypeByDetectionTypeId(this.DetectionTypeId);
            if (detectionType != null)
            {
                if (detectionType.DetectionTypeCode == "RT")
                {
                    initTemplatePath = Const.RTCheckManageDataInTemplateUrl;
                }
                else if (detectionType.DetectionTypeCode == "PT")
                {
                    initTemplatePath = Const.PTCheckManageDataInTemplateUrl;
                }
            }
            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();
                if (this.DetectionTypeCode == "RT")
                {
                    AddDatasetToSQL(ds.Tables[0], 35);
                }
                else if (this.DetectionTypeCode == "PT")
                {
                    AddDatasetToSQL(ds.Tables[0], 34);
                }
            }
            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;
            if (ic < Cols)
            {
                throw new Exception("导入Excel格式错误!Excel只有" + ic.ToString().Trim() + "列");
            }
            //委托单位
            var trustUnits = from x in Funs.DB.Project_ProjectUnit
                             join y in Funs.DB.Base_Unit on x.UnitId equals y.UnitId
                             where x.ProjectId == this.CurrUser.LoginProjectId //&& x.UnitType == "2"
                             select y;
            //装置
            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;
            //委托
            var trusts = from x in Funs.DB.CH_Trust
                         where x.ProjectId == this.CurrUser.LoginProjectId
                         select x;
            //管线
            var isoInfos = from x in Funs.DB.PW_IsoInfo
                           where x.ProjectId == this.CurrUser.LoginProjectId
                           select x;
            //焊口
            var jointInfos = from x in Funs.DB.PW_JointInfo where x.ProjectId == this.CurrUser.LoginProjectId select x;
            //焊工号
            var welders = from x in Funs.DB.BS_Welder where x.ProjectId == this.CurrUser.LoginProjectId select x;
            //材质
            var materials = from x in Funs.DB.Base_Material select x;
            //检测比例
            var detectionRates = from x in Funs.DB.Base_DetectionRate select x;
            //焊接方法
            var weldingMotheds = from x in Funs.DB.Base_WeldingMethod select x;
            //坡口形式
            var grooveTypes = from x in Funs.DB.Base_GrooveType select x;
            ir = pds.Rows.Count;
            if (pds != null && ir > 0)
            {
                for (int i = 0; i < ir; i++)
                {
                    //string unitId = string.Empty;
                    string installationId = string.Empty;
                    string workareaId = string.Empty;
                    string isoid = string.Empty;
                    if (string.IsNullOrEmpty(pds.Rows[i][0].ToString().Trim()))
                    {
                        result += (i + 2).ToString() + "," + "委托单位" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        var unit = trustUnits.FirstOrDefault(e => e.UnitName == pds.Rows[i][0].ToString().Trim());
                        if (unit == null)
                        {
                            result += (i + 2).ToString() + "," + "委托单位[" + pds.Rows[i][0].ToString().Trim() + "],不存在|";
                        }
                        //else
                        //{
                        //    unitId = unit.UnitId;
                        //}
                    }
                    if (string.IsNullOrEmpty(pds.Rows[i][1].ToString()))
                    {
                        result += (i + 2).ToString() + "," + "承包单位" + "," + "此项为必填项!" + "|";
                    }
                    if (string.IsNullOrEmpty(pds.Rows[i][2].ToString().Trim()))
                    {
                        result += (i + 2).ToString() + "," + "单元/装置名称" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        var installation = installations.FirstOrDefault(e => e.InstallationName == pds.Rows[i][2].ToString().Trim());
                        if (installation == null)
                        {
                            result += (i + 2).ToString() + "," + "单元/装置名称[" + pds.Rows[i][2].ToString().Trim() + "],不存在|";
                        }
                        else
                        {
                            installationId = installation.InstallationId;
                        }
                    }
                    if (string.IsNullOrEmpty(pds.Rows[i][3].ToString().Trim()))
                    {
                        result += (i + 2).ToString() + "," + "区号" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        var workarea = workareas.FirstOrDefault(e =>  e.InstallationId == installationId && e.WorkAreaCode == pds.Rows[i][3].ToString().Trim());
                        if (workarea == null)
                        {
                            result += (i + 2).ToString() + "," + "区号[" + pds.Rows[i][3].ToString().Trim() + "],该装置下不存在|";
                        }
                        else
                        {
                            workareaId = workarea.WorkAreaId;
                        }
                    }
                    if (string.IsNullOrEmpty(pds.Rows[i][4].ToString().Trim()))
                    {
                        result += (i + 2).ToString() + "," + "委托编号" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        var trust = trusts.FirstOrDefault(e => e.CH_TrustCode == pds.Rows[i][4].ToString().Trim());
                        if (trust == null)
                        {
                            result += (i + 2).ToString() + "," + "委托编号[" + pds.Rows[i][4].ToString().Trim() + "],不存在|";
                        }
                    }
                    if (string.IsNullOrEmpty(pds.Rows[i][5].ToString()))
                    {
                        result += (i + 2).ToString() + "," + "委托日期" + "," + "此项为必填项!" + "|";
                    }
                    else
                    {
                        try
                        {
                        }
                        catch (Exception)
                        {
                            result += (i + 2).ToString() + "," + "委托日期" + "," + "格式不正确!" + "|";
                        }
                    }
                    if (string.IsNullOrEmpty(pds.Rows[i][6].ToString()))
                    {
                        result += (i + 2).ToString() + "," + "检件名称" + "," + "此项为必填项!" + "|";
                    }
                    if (this.DetectionTypeCode == "RT")
                    {
                        //if (string.IsNullOrEmpty(pds.Rows[i][7].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "检测批号" + "," + "此项为必填项!" + "|";
                        //}
                        if (string.IsNullOrEmpty(pds.Rows[i][8].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "检件编号(管线号)" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var iso = isoInfos.FirstOrDefault(e => e.WorkAreaId == workareaId && e.ISO_IsoNo == pds.Rows[i][8].ToString().Trim());
                            if (iso == null)
                            {
                                result += (i + 2).ToString() + "," + "检件编号(管线号)[" + pds.Rows[i][8].ToString().Trim() + "],该区域下不存在|";
                            }
                            else
                            {
                                isoid = iso.ISO_ID;
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][9].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "焊口号" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var joint = jointInfos.FirstOrDefault(e => e.ISO_ID == isoid && e.JOT_JointNo == pds.Rows[i][9].ToString().Trim());
                            if (joint == null)
                            {
                                result += (i + 2).ToString() + "," + "焊口号[" + pds.Rows[i][9].ToString().Trim() + "],该管线下不存在|";
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][10].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "焊工号" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var welder = welders.FirstOrDefault(e => e.WED_Code == pds.Rows[i][11].ToString().Trim());
                            if (welder == null)
                            {
                                result += (i + 2).ToString() + "," + "焊工号[" + pds.Rows[i][11].ToString().Trim() + "],不存在|";
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][12].ToString()))
                        {
                            result += (i + 2).ToString() + "," + "检件规格" + "," + "此项为必填项!" + "|";
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][13].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "检件材质" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var material = materials.FirstOrDefault(e => e.MaterialCode == pds.Rows[i][13].ToString().Trim());
                            if (material == null)
                            {
                                result += (i + 2).ToString() + "," + "检件材质[" + pds.Rows[i][13].ToString().Trim() + "],不存在|";
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][14].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "比例(%)" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var rate = detectionRates.FirstOrDefault(e => e.DetectionRate == pds.Rows[i][14].ToString());
                            if (rate == null)
                            {
                                result += (i + 2).ToString() + "," + "比例(%)[" + pds.Rows[i][14].ToString().Trim() + "],不存在|";
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][15].ToString()))
                        {
                            result += (i + 2).ToString() + "," + "合格级别" + "," + "此项为必填项!" + "|";
                        }
                        //if (string.IsNullOrEmpty(pds.Rows[i][15].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "焊口数" + "," + "此项为必填项!" + "|";
                        //}
                        if (string.IsNullOrEmpty(pds.Rows[i][17].ToString()))
                        {
                            result += (i + 2).ToString() + "," + "拍片性质" + "," + "此项为必填项!" + "|";
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][18].ToString()))
                        {
                            result += (i + 2).ToString() + "," + "片位号" + "," + "此项为必填项!" + "|";
                        }
                        //if (string.IsNullOrEmpty(pds.Rows[i][18].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "缺陷性质" + "," + "此项为必填项!" + "|";
                        //}
                        //if (string.IsNullOrEmpty(pds.Rows[i][19].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "缺陷定量" + "," + "此项为必填项!" + "|";
                        //}
                        //if (string.IsNullOrEmpty(pds.Rows[i][20].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "评定级别" + "," + "此项为必填项!" + "|";
                        //}
                        if (string.IsNullOrEmpty(pds.Rows[i][22].ToString()))
                        {
                            result += (i + 2).ToString() + "," + "是否合格" + "," + "此项为必填项!" + "|";
                        }
                        //if (string.IsNullOrEmpty(pds.Rows[i][22].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "备注" + "," + "此项为必填项!" + "|";
                        //}
                        if (string.IsNullOrEmpty(pds.Rows[i][24].ToString()))
                        {
                            result += (i + 2).ToString() + "," + "拍片日期" + "," + "此项为必填项!" + "|";
                        }
                        //if (string.IsNullOrEmpty(pds.Rows[i][24].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "拍片人" + "," + "此项为必填项!" + "|";
                        //}
                        //if (string.IsNullOrEmpty(pds.Rows[i][25].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "源种类" + "," + "此项为必填项!" + "|";
                        //}
                        //if (string.IsNullOrEmpty(pds.Rows[i][26].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "底片规格" + "," + "此项为必填项!" + "|";
                        //}
                        //if (string.IsNullOrEmpty(pds.Rows[i][27].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "结果单编号" + "," + "此项为必填项!" + "|";
                        //}
                        //if (string.IsNullOrEmpty(pds.Rows[i][28].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "结果单日期" + "," + "此项为必填项!" + "|";
                        //}
                        //if (string.IsNullOrEmpty(pds.Rows[i][29].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "报告编号" + "," + "此项为必填项!" + "|";
                        //}
                        //if (string.IsNullOrEmpty(pds.Rows[i][30].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "报告日期" + "," + "此项为必填项!" + "|";
                        //}
                        //if (string.IsNullOrEmpty(pds.Rows[i][31].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "合格数量" + "," + "此项为必填项!" + "|";
                        //}
                        //if (string.IsNullOrEmpty(pds.Rows[i][32].ToString()))
                        //{
                        //    result += (i + 2).ToString() + "," + "不合格数" + "," + "此项为必填项!" + "|";
                        //}
                        if (string.IsNullOrEmpty(pds.Rows[i][34].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "焊接方法" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var weldthoed = weldingMotheds.FirstOrDefault(e => e.WeldingMethodCode == pds.Rows[i][34].ToString().Trim());
                            if (weldthoed == null)
                            {
                                result += (i + 2).ToString() + "," + "焊接方法[" + pds.Rows[i][34].ToString().Trim() + "],不存在|";
                            }
                        }
                    }
                    else if (this.DetectionTypeCode == "PT")
                    {
                        if (string.IsNullOrEmpty(pds.Rows[i][9].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "检件编号(管线号)" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var iso = isoInfos.FirstOrDefault(e => e.WorkAreaId == workareaId && e.ISO_IsoNo == pds.Rows[i][9].ToString().Trim());
                            if (iso == null)
                            {
                                result += (i + 2).ToString() + "," + "检件编号(管线号)[" + pds.Rows[i][9].ToString().Trim() + "],该区域下不存在|";
                            }
                            else
                            {
                                isoid = iso.ISO_ID;
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][10].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "焊口号" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var joint = jointInfos.FirstOrDefault(e => e.ISO_ID == isoid && e.JOT_JointNo == pds.Rows[i][10].ToString().Trim());
                            if (joint == null)
                            {
                                result += (i + 2).ToString() + "," + "焊口号[" + pds.Rows[i][10].ToString().Trim() + "],该管线下不存在|";
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][12].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "焊工号" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var welder = welders.FirstOrDefault(e => e.WED_Code == pds.Rows[i][12].ToString().Trim());
                            if (welder == null)
                            {
                                result += (i + 2).ToString() + "," + "焊工号[" + pds.Rows[i][12].ToString().Trim() + "],不存在|";
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][14].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "检件材质" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var material = materials.FirstOrDefault(e => e.MaterialCode == pds.Rows[i][14].ToString().Trim());
                            if (material == null)
                            {
                                result += (i + 2).ToString() + "," + "检件材质[" + pds.Rows[i][14].ToString().Trim() + "],不存在|";
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][15].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "比例(%)" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var rate = detectionRates.FirstOrDefault(e => e.DetectionRate == pds.Rows[i][15].ToString());
                            if (rate == null)
                            {
                                result += (i + 2).ToString() + "," + "比例(%)[" + pds.Rows[i][15].ToString().Trim() + "],不存在|";
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][16].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "焊接方法" + "," + "此项为必填项!" + "|";
                        }
                        else
                        {
                            var weldthoed = weldingMotheds.FirstOrDefault(e => e.WeldingMethodCode == pds.Rows[i][16].ToString().Trim());
                            if (weldthoed == null)
                            {
                                result += (i + 2).ToString() + "," + "焊接方法[" + pds.Rows[i][16].ToString().Trim() + "],不存在|";
                            }
                        }
                        if (!string.IsNullOrEmpty(pds.Rows[i][17].ToString().Trim()))
                        {
                            var groove = grooveTypes.FirstOrDefault(e => e.GrooveTypeCode == pds.Rows[i][17].ToString().Trim());
                            if (groove == null)
                            {
                                result += (i + 2).ToString() + "," + "坡口形式[" + pds.Rows[i][17].ToString().Trim() + "],不存在|";
                            }
                        }
                        if (string.IsNullOrEmpty(pds.Rows[i][28].ToString().Trim()))
                        {
                            result += (i + 2).ToString() + "," + "结果" + "," + "此项为必填项!" + "|";
                        }
                    }
                    //a++;
                }
                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();
                if (this.DetectionTypeCode == "RT")
                {
                    AddDatasetToSQL2(ds.Tables[0], 35);
                }
                else if (this.DetectionTypeCode == "PT")
                {
                    AddDatasetToSQL2(ds.Tables[0], 34);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        /// 
        /// 将Dataset的数据导入数据库
        /// 
        /// 数据集
        /// 数据集列数
        /// 
        private bool AddDatasetToSQL2(DataTable pds, int Cols)
        {
            string result = string.Empty;
            string dReportID = string.Empty;
            string dateStr = string.Empty;
            int ic, ir;
            ic = pds.Columns.Count;
            if (ic < Cols)
            {
                throw new Exception("导入Excel格式错误!Excel只有" + ic.ToString().Trim() + "列");
            }
            List checkStaticList = new List();
            //委托单位
            var trustUnits = from x in Funs.DB.Project_ProjectUnit
                             join y in Funs.DB.Base_Unit on x.UnitId equals y.UnitId
                             where x.ProjectId == this.CurrUser.LoginProjectId //&& x.UnitType == "2"
                             select y;
            //装置
            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;
            //委托
            var trusts = from x in Funs.DB.CH_Trust
                         where x.ProjectId == this.CurrUser.LoginProjectId
                         select x;
            //管线
            var isoInfos = from x in Funs.DB.PW_IsoInfo
                           where x.ProjectId == this.CurrUser.LoginProjectId
                           select x;
            //焊口
            var jointInfos = from x in Funs.DB.PW_JointInfo where x.ProjectId == this.CurrUser.LoginProjectId select x;
            //焊工号
            var welders = from x in Funs.DB.BS_Welder where x.ProjectId == this.CurrUser.LoginProjectId select x;
            //材质
            var materials = from x in Funs.DB.Base_Material select x;
            //检测比例
            var detectionRates = from x in Funs.DB.Base_DetectionRate select x;
            //焊接方法
            var weldingMotheds = from x in Funs.DB.Base_WeldingMethod select x;
            //坡口形式
            var grooveTypes = from x in Funs.DB.Base_GrooveType select x;
            ir = pds.Rows.Count;
            if (pds != null && ir > 0)
            {
                for (int i = 0; i < ir; i++)
                {
                    string row8 = string.Empty;
                    string row9 = string.Empty;
                    string row10 = string.Empty;
                    string row11 = string.Empty;
                    string row12 = string.Empty;
                    string row13 = string.Empty;
                    string row14 = string.Empty;
                    string row15 = string.Empty;
                    string row16 = string.Empty;
                    string row17 = string.Empty;
                    string row18 = string.Empty;
                    string row19 = string.Empty;
                    string row20 = string.Empty;
                    string row21 = string.Empty;
                    string row22 = string.Empty;
                    string row23 = string.Empty;
                    string row24 = string.Empty;
                    string row25 = string.Empty;
                    string row26 = string.Empty;
                    string row27 = string.Empty;
                    string row28 = string.Empty;
                    string row29 = string.Empty;
                    string row30 = string.Empty;
                    string row31 = string.Empty;
                    string row32 = string.Empty;
                    string row33 = string.Empty;
                    string row34 = string.Empty;
                    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();//检测批号
                    if (this.DetectionTypeCode == "RT")
                    {
                        row8 = pds.Rows[i][8].ToString().Trim();//检件编号(管线号)
                        row9 = pds.Rows[i][9].ToString().Trim();//焊口号
                        row10 = pds.Rows[i][10].ToString().Trim();//焊口标志
                        row11 = pds.Rows[i][11].ToString().Trim();//焊工号
                        row12 = pds.Rows[i][12].ToString().Trim();//检件规格
                        row13 = pds.Rows[i][13].ToString().Trim();//检件材质
                        row14 = pds.Rows[i][14].ToString().Trim();//比例(%)
                        row15 = pds.Rows[i][15].ToString().Trim();//合格级别
                        row16 = pds.Rows[i][16].ToString().Trim();//焊口数
                        row17= pds.Rows[i][17].ToString().Trim();//拍片性质
                        row18 = pds.Rows[i][18].ToString().Trim();//片位号
                        row19 = pds.Rows[i][19].ToString().Trim();//缺陷性质
                        row20 = pds.Rows[i][20].ToString().Trim();//缺陷定量
                        row21 = pds.Rows[i][21].ToString().Trim();//评定级别
                        row22 = pds.Rows[i][22].ToString().Trim();//是否合格
                        row23 = pds.Rows[i][23].ToString().Trim();//备注
                        row24 = pds.Rows[i][24].ToString().Trim();//拍片日期
                        row25 = pds.Rows[i][25].ToString().Trim();//拍片人
                        row26 = pds.Rows[i][26].ToString().Trim();//源种类
                        row27 = pds.Rows[i][27].ToString().Trim();//底片规格
                        row28 = pds.Rows[i][28].ToString().Trim();//结果单编号
                        row29 = pds.Rows[i][29].ToString().Trim();//结果单日期
                        row30 = pds.Rows[i][30].ToString().Trim();//报告编号
                        row31 = pds.Rows[i][31].ToString().Trim();//报告日期
                        row32 = pds.Rows[i][32].ToString().Trim();//合格数量
                        row33 = pds.Rows[i][33].ToString().Trim();//不合格数
                        row34 = pds.Rows[i][34].ToString().Trim();//焊接方法
                    }
                    else if (this.DetectionTypeCode=="PT")
                    {
                        row8 = pds.Rows[i][8].ToString().Trim();//检测时机
                        row9 = pds.Rows[i][9].ToString().Trim();//检件编号(管线号)
                        row10 = pds.Rows[i][10].ToString().Trim();//焊口号
                        row11 = pds.Rows[i][11].ToString().Trim();//焊口标志
                        row12 = pds.Rows[i][12].ToString().Trim();//焊工号
                        row13 = pds.Rows[i][13].ToString().Trim();//检件规格
                        row14 = pds.Rows[i][14].ToString().Trim();//检件材质
                        row15 = pds.Rows[i][15].ToString().Trim();//比例(%)
                        row16 = pds.Rows[i][16].ToString().Trim();//焊接方法
                        row17 = pds.Rows[i][17].ToString().Trim();//坡口形式
                        row18 = pds.Rows[i][18].ToString().Trim();//级别
                        row19 = pds.Rows[i][19].ToString().Trim();//工艺卡序号
                        row20 = pds.Rows[i][20].ToString().Trim();//工作量米
                        row21 = pds.Rows[i][21].ToString().Trim();//工作量道
                        row22 = pds.Rows[i][22].ToString().Trim();//检测日期
                        row23 = pds.Rows[i][23].ToString().Trim();//检测面
                        row24 = pds.Rows[i][24].ToString().Trim();//检测人
                        row25 = pds.Rows[i][25].ToString().Trim();//缺陷情况或缺陷示意图编号
                        row26 = pds.Rows[i][26].ToString().Trim();//评定级别
                        row27 = pds.Rows[i][27].ToString().Trim();//结果
                        row28 = pds.Rows[i][28].ToString().Trim();//结果单编号
                        row29 = pds.Rows[i][29].ToString().Trim();//结果单日期
                        row30 = pds.Rows[i][30].ToString().Trim();//报告编号
                        row31 = pds.Rows[i][31].ToString().Trim();//报告日期
                        row32 = pds.Rows[i][32].ToString().Trim();//工作量
                        row33 = pds.Rows[i][33].ToString().Trim();//工程进度款
                    }
                    Model.CH_CheckStatic checkStatic = new Model.CH_CheckStatic();
                    checkStatic.CheckStaticId = Guid.NewGuid().ToString();
                    checkStatic.ProjectId = this.CurrUser.LoginProjectId;
                    checkStatic.ProjectName = BLL.ProjectService.GetProjectNameByProjectId(this.CurrUser.LoginProjectId);
                    checkStatic.DetectionTypeCode = this.DetectionTypeCode;
                    checkStatic.CreateDate = DateTime.Now;
                    var trustUnit = trustUnits.FirstOrDefault(e => e.UnitName == row0);//委托单位
                    if (trustUnit != null)
                    {
                        checkStatic.TrustUnitId = trustUnit.UnitId;
                        checkStatic.TrustUnitName = trustUnit.UnitName;
                    }
                    checkStatic.UnitName= row1;//承包单位
                    var unit = BLL.UnitService.getUnitByUnitName(row1);
                    if (unit != null)
                    {
                        checkStatic.UnidId = unit.UnitId;
                    }
                    //单元/装置名称
                    var insta = installations.FirstOrDefault(e => e.InstallationName == row2);
                    if (insta!=null)
                    {
                        checkStatic.InstallationName = row2;
                        checkStatic.Installation_ID = insta.InstallationId;
                    }
                    //区域
                    var workarea = workareas.FirstOrDefault(e => e.WorkAreaCode == row3);
                    if (workarea!=null)
                    {
                        checkStatic.WorkAreaCode = row3;
                        checkStatic.WorkAreaId = workarea.WorkAreaId;
                    }
                    var trust = trusts.FirstOrDefault(e => e.CH_TrustCode == row4);
                    if (trust != null)
                    {
                        checkStatic.CH_TrustCode = row4;
                        checkStatic.CH_TrustID = trust.CH_TrustID;
                        if (!string.IsNullOrEmpty(row5))
                        {
                            checkStatic.Trust_Date = Funs.GetNewDateTime(row5);
                        }
                        else
                        {
                            checkStatic.Trust_Date = trust.CH_TrustDate;
                        }
                    }
                    checkStatic.ItemName = row6;//检件名称
                    checkStatic.BatchNum = row7;//检测批号
                    if (this.DetectionTypeCode == "RT")
                    {
                        var iso = isoInfos.FirstOrDefault(e => e.ISO_IsoNo == row8);
                        if (iso != null)
                        {
                            checkStatic.ISO_IsoNo = row8;
                            checkStatic.ISO_ID = iso.ISO_ID;
                        }
                        var joint = jointInfos.FirstOrDefault(e => e.JOT_JointNo == row9);
                        if (joint != null)
                        {
                            checkStatic.JOT_JointNo = row9;
                            checkStatic.JOT_ID = joint.JOT_ID;
                        }
                        checkStatic.JointNoFlag = row10;//焊口标志
                        var welder = welders.FirstOrDefault(e => e.WED_Code == row11);
                        if (welder != null)
                        {
                            checkStatic.WED_ID = welder.WED_ID;
                            checkStatic.WED_Code = row11;
                        }
                        checkStatic.JOT_JointDesc = row12;//检件规格
                         //检件材质
                        var material = materials.FirstOrDefault(e => e.MaterialCode == row13);
                        if (material != null)
                        {
                            checkStatic.MaterialId = material.MaterialId;
                            checkStatic.MaterialCode = row13;
                        }
                        //比例(%)
                        var rate = detectionRates.FirstOrDefault(e => e.DetectionRate == row14);
                        if (rate != null)
                        {
                            checkStatic.DetectionRateId = rate.DetectionRateId;
                            checkStatic.DetectionRateCode = row14;
                        }
                        checkStatic.QualificationLevel = row15;//合格级别
                        checkStatic.JointCount = Funs.GetNewInt(row16);//焊口数
                        checkStatic.FilmingNature = row17;//拍片性质
                        checkStatic.FilmNum = row18;//片位号
                        checkStatic.DefectType = row19;//缺陷性质
                        checkStatic.DefectNum = row20;//缺陷定量
                        checkStatic.EvaluateLevel = row21;//评定级别
                        checkStatic.CheckResult = row22;//是否合格
                        checkStatic.Remark = row23;//备注
                        checkStatic.CheckDate = Funs.GetNewDateTime(row24);//拍片日期
                        checkStatic.FilmMan = row25;//拍片人
                        checkStatic.SourceCategory = row26;//源种类
                        checkStatic.FilmSpecifications = row27;//底片规格
                        checkStatic.CheckResultNum = row28;//结果单编号
                        checkStatic.CheckResultDate = Funs.GetNewDateTime(row29);//结果单日期
                        checkStatic.ReportNo = row30;//报告编号
                        if (!string.IsNullOrEmpty(row31))
                        {
                            checkStatic.ReportDate = Funs.GetNewDateTime(row31);//报告日期
                        }
                        else
                        {
                            checkStatic.ReportDate = DateTime.Now;
                        }
                        checkStatic.PassCount = Funs.GetNewInt(row32);//合格数量
                        checkStatic.NoPassCount = Funs.GetNewInt(row33);//不合格数
                        //焊接方法
                        var weldingMethod = weldingMotheds.FirstOrDefault(e => e.WeldingMethodCode == row34);
                        if (weldingMethod != null)
                        {
                            checkStatic.WME_ID = weldingMethod.WeldingMethodId;
                            checkStatic.WeldingMethodCode = row34;
                        }
                    }
                    else if (this.DetectionTypeCode=="PT")
                    {
                        checkStatic.DetectionTime = row8;
                        var iso = isoInfos.FirstOrDefault(e => e.ISO_IsoNo == row9);
                        if (iso != null)
                        {
                            checkStatic.ISO_IsoNo = row9;
                            checkStatic.ISO_ID = iso.ISO_ID;
                        }
                        var joint = jointInfos.FirstOrDefault(e => e.JOT_JointNo == row10);
                        if (joint != null)
                        {
                            checkStatic.JOT_JointNo = row10;
                            checkStatic.JOT_ID = joint.JOT_ID;
                        }
                        checkStatic.JointNoFlag = row11;//焊口号标志
                        var welder = welders.FirstOrDefault(e => e.WED_Code == row12);
                        if (welder != null)
                        {
                            checkStatic.WED_ID = welder.WED_ID;
                            checkStatic.WED_Code = row12;
                        }
                        checkStatic.JOT_JointDesc = row13;//检件规格
                         //检件材质
                        var material = materials.FirstOrDefault(e => e.MaterialCode == row14);
                        if (material != null)
                        {
                            checkStatic.MaterialId = material.MaterialId;
                            checkStatic.MaterialCode = row14;
                        }
                        //比例(%)
                        var rate = detectionRates.FirstOrDefault(e => e.DetectionRate == row15);
                        if (rate != null)
                        {
                            checkStatic.DetectionRateId = rate.DetectionRateId;
                            checkStatic.DetectionRateCode = row15;
                        }
                        //焊接方法
                        var weldingMethod = weldingMotheds.FirstOrDefault(e => e.WeldingMethodCode == row16);
                        if (weldingMethod != null)
                        {
                            checkStatic.WME_ID = weldingMethod.WeldingMethodId;
                            checkStatic.WeldingMethodCode = row16;
                        }
                        //坡口形式
                        var grooveType = grooveTypes.FirstOrDefault(e => e.GrooveTypeCode == row17);
                        if (grooveType!=null)
                        {
                            checkStatic.GrooveTypeId = grooveType.GrooveTypeId;
                            checkStatic.GrooveTypeCode = row17;
                        }
                        checkStatic.QualificationLevel = row18;//级别
                        checkStatic.ProcessCardNum = row19;//工艺卡序号
                        checkStatic.WorkMeter = row20;//工作量米
                        checkStatic.WorkloadTrack = row21;//工作量道
                        checkStatic.CheckDate = Funs.GetNewDateTime(row22);//检测日期
                        checkStatic.DetectionSurface = row23;//检测面
                        checkStatic.FilmMan = row24;//检测人
                        checkStatic.DefectCode = row25;//缺陷情况或缺陷示意图编号
                        checkStatic.EvaluateLevel = row26;//评定级别
                        checkStatic.CheckResult = row27;//结果
                        checkStatic.CheckResultNum = row28;//结果单编号
                        checkStatic.CheckResultDate = Funs.GetNewDateTime(row29);//结果单日期
                        checkStatic.ReportNo = row30;//报告编号
                        if (!string.IsNullOrEmpty(row31))
                        {
                            checkStatic.ReportDate = Funs.GetNewDateTime(row31);//报告日期
                        }
                        else
                        {
                            checkStatic.ReportDate = DateTime.Now;
                        }
                        checkStatic.Workloads = row32;//工作量
                        checkStatic.ProgressMoney = row33;//工程进度款
                    }
                    checkStaticList.Add(checkStatic);
                }
                Funs.DB.CH_CheckStatic.InsertAllOnSubmit(checkStaticList);
                Funs.DB.SubmitChanges();
                ShowNotify("导入成功!", MessageBoxIcon.Success);
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                throw new Exception("导入数据为空!");
            }
            return true;
        }
        #endregion
    }
}