using BLL;
using BLL.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading;
namespace FineUIPro.Web.HJGL.DataIn
{
    public partial class DataInTable : PageBase
    {
        #region 定义项
        /// <summary>
        /// 是否PDMS
        /// </summary>
        private string IsPDMS
        {
            get
            {
                return (string)ViewState["IsPDMS"];
            }
            set
            {
                ViewState["IsPDMS"] = value;
            }
        }
        #endregion

        #region 加载页面
        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Funs.DropDownPageSize(this.ddlPageSize);
                if (percent == null)
                {
                    percent = new Dictionary<string, int>();
                }
                this.id.Text = this.CurrUser.UserId;
                this.IsPDMS = "0";
                var set = BLL.Project_SysSetService.GetSysSetBySetId("8", this.CurrUser.LoginProjectId);
                if (set != null && set.IsAuto == true)
                {
                    this.IsPDMS = "1";
                    this.FileExcel.EmptyText = "请上传PDMS模板的EXCEl格式文件";
                }

                this.ddlPageSize.SelectedValue = Grid1.PageSize.ToString();
                // 绑定表格
                this.BindGrid();
            }
            else if (GetRequestEventArgument() == "reloadGrid")
            {
                BindGrid();
            }
        }
        #endregion

        #region 绑定数据
        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindGrid()
        {
            string strSql = @"SELECT TempId,ProjectId,UserId,Time,RowNo,ToopValue,Value1,Value2,Value3,Value4,Value5,Value6,Value7,Value8,Value9,Value10"
                + @" ,Value11,Value12,Value13,Value14,Value15,Value16,Value17,Value18,Value19,Value20,Value21,Value22,Value23,Value24,Value25,Value26,Value27,Value28,Value29,Value30"
                + @" ,Value31,Value32,Value33,Value34,Value35,Value36,Value37,Value38,Value39,Value40,Value41,Value42,Value43,Value44,Value45,Value46,Value47,Value48,Value49,Value50,ToopValue,Type"
                + @" FROM Sys_DataInTemp  "
                + @" WHERE ProjectId=@ProjectId AND UserId=@UserId AND Type=@Type";
            List<SqlParameter> listStr = new List<SqlParameter>();
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            listStr.Add(new SqlParameter("@UserId", this.CurrUser.UserId));
            listStr.Add(new SqlParameter("@Type", this.IsPDMS));
            //if (!string.IsNullOrEmpty(this.txtValue1.Text.Trim()))
            //{
            //    strSql += " AND Value1 LIKE @Value1";
            //    listStr.Add(new SqlParameter("@Value1", "%" + this.txtValue1.Text.Trim() + "%"));
            //}
            //if (!string.IsNullOrEmpty(this.txtValue2.Text.Trim()))
            //{
            //    strSql += " AND Value2 LIKE @Value2";
            //    listStr.Add(new SqlParameter("@Value2", "%" + this.txtValue2.Text.Trim() + "%"));
            //}
            //if (!string.IsNullOrEmpty(this.txtValue3.Text.Trim()))
            //{
            //    strSql += " AND Value3 LIKE @Value3";
            //    listStr.Add(new SqlParameter("@Value3", "%" + this.txtValue3.Text.Trim() + "%"));
            //}
            //if (!string.IsNullOrEmpty(this.txtValue4.Text.Trim()))
            //{
            //    strSql += " AND Value4 LIKE @Value4";
            //    listStr.Add(new SqlParameter("@Value4", "%" + this.txtValue4.Text.Trim() + "%"));
            //}
            //if (!string.IsNullOrEmpty(this.txtToopValue.Text.Trim()))
            //{
            //    strSql += " AND ToopValue LIKE @ToopValue";
            //    listStr.Add(new SqlParameter("@ToopValue", "%" + this.txtToopValue.Text.Trim() + "%"));
            //}
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            // 2.获取当前分页数据
            //var table = this.GetPagedDataTable(Grid1, tb1);
            Grid1.RecordCount = tb.Rows.Count;
            //tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();

            var dataInTempAll = from x in Funs.DB.Sys_DataInTemp
                                where x.ProjectId == this.CurrUser.LoginProjectId && x.UserId == this.CurrUser.UserId && x.Type == this.IsPDMS
                                select x;
            for (int i = 0; i < Grid1.Rows.Count; i++)
            {
                var dataInTemp = dataInTempAll.FirstOrDefault(x => x.TempId == Grid1.Rows[i].DataKeys[0].ToString());
                if (dataInTemp != null)
                {
                    if (!string.IsNullOrEmpty(dataInTemp.ToopValue))
                    {
                        Grid1.Rows[i].RowCssClass = "red";
                    }
                }
            }
            if (this.Grid1.Columns.Count() > 0)
            {
                if (this.IsPDMS == "1") ///如果是PDMS
                {
                    this.Grid1.Columns[7].Hidden = true;//材质2
                    this.Grid1.Columns[10].Hidden = true;//焊接区域
                    this.Grid1.Columns[11].Hidden = true;//焊口属性
                    this.Grid1.Columns[12].Hidden = true;//达因数
                    this.Grid1.Columns[13].Hidden = true;//规格
                    this.Grid1.Columns[15].Hidden = true;//焊接方法代码
                    this.Grid1.Columns[17].Hidden = true;//焊条代号
                    this.Grid1.Columns[18].Hidden = true;//焊丝代号
                    this.Grid1.Columns[19].HeaderText = "流水介质";
                    this.Grid1.Columns[23].Hidden = true;//坡口代号
                    this.Grid1.Columns[25].HeaderText = "组件类型";
                    this.Grid1.Columns[26].Hidden = true;//组件二代号
                    this.Grid1.Columns[27].Hidden = true;//炉批号1
                    this.Grid1.Columns[28].Hidden = true;//炉批号2
                    this.Grid1.Columns[30].Hidden = true;//预热温度
                    this.Grid1.Columns[31].Hidden = true;//是否热处理
                    this.Grid1.Columns[32].Hidden = true;//热处理编号
                    this.Grid1.Columns[33].Hidden = true;//焊接位置
                    this.Grid1.Columns[34].Hidden = true;//外径
                    this.Grid1.Columns[35].Hidden = true;//硬度检测比例(数值)
                    this.Grid1.Columns[36].Hidden = true;//焊接气体保护
                }
                else
                {
                    this.Grid1.Columns[37].Hidden = true;//组件数量
                    this.Grid1.Columns[38].Hidden = true;//公称直径
                }
            }
            var errData = from x in dataInTempAll where x.ToopValue != null select x;
            this.lbDataCout.Text = errData.Count().ToString();
        }
        #endregion

        #region 双击事件
        /// <summary>
        /// Grid行双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_DataInMenuId, Const.BtnIn))
            {
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("DataInEdit.aspx?TempId={0}", Grid1.SelectedRowID, "维护 - ")));
            }
            else
            {
                ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 导入信息 维护
        /// <summary>
        /// 导入信息编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMenuEdit_Click(object sender, EventArgs e)
        {
            if (BLL.CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.HJGL_DataInMenuId, BLL.Const.BtnIn))
            {
                if (Grid1.SelectedRowIndexArray.Length == 0)
                {
                    Alert.ShowInTop("请选择一条记录!", MessageBoxIcon.Warning);
                    return;
                }
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("DataInEdit.aspx?TempId={0}", Grid1.SelectedRowID, "维护 - ")));
            }
            else
            {
                ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_DataInMenuId, Const.BtnIn))
            {
                if (Grid1.SelectedRowIndexArray.Length == 0)
                {
                    Alert.ShowInTop("请选择一条记录!", MessageBoxIcon.Warning);
                    return;
                }

                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    BLL.DataInTempService.DeleteDataInTempByDataInTempID(rowID);
                    //BLL.Sys_LogService.AddLog(Const.System_7, this.CurrUser.LoginProjectId, this.CurrUser.UserId, "删除导入信息");
                }

                ShowNotify("删除成功!", MessageBoxIcon.Success);
                this.BindGrid();
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion

        #region 分页 排序
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }

        /// <summary>
        /// 分页显示条数下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_Sort(object sender, FineUIPro.GridSortEventArgs e)
        {
            BindGrid();
        }
        #endregion

        #region 文件上传
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgbtnImport_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.FileExcel.HasFile == false)
                {
                    Response.Write("<script>alert('请您选择Excel文件')</script> ");
                    //for (int i = 0; i < 10; i++)
                    //{
                    //    Response.Flush();
                    //    Response.Write("<script>alert('请您选择Excel文件')</script> ");
                    //    System.Threading.Thread.Sleep(5000);
                    //    Response.Flush();
                    //}


                    return;
                }
                string IsXls = Path.GetExtension(FileExcel.FileName).ToString().Trim().ToLower();
                if (IsXls != ".xls")
                {
                    Response.Write("<script>alert('只可以选择Excel文件')</script>");
                    return;
                }
                string rootPath = Server.MapPath("~/");
                string initFullPath = rootPath + Const.ExcelUrl;
                if (!Directory.Exists(initFullPath))
                {
                    Directory.CreateDirectory(initFullPath);
                }
                string fileUrl = initFullPath + BLL.Funs.GetNewFileName() + IsXls;
                this.FileExcel.PostedFile.SaveAs(fileUrl);

                //string oleDBConnString = String.Empty;
                //oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;";
                //oleDBConnString += "Data Source=";
                //oleDBConnString += fileUrl;
                //oleDBConnString += ";Extended Properties=Excel 8.0;";
                ////oleDBConnString = "Provider=Microsoft.ACE.OLEDB.12.0;";
                ////oleDBConnString += "Data Source=";
                ////oleDBConnString += fileUrl;
                ////oleDBConnString += ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
                //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 = 3600;
                //oleAdMaster.Fill(ds, "m_tableName");
                //oleAdMaster.Dispose();
                //oleDBConn.Close();
                //oleDBConn.Dispose();
                //this.AddDatasetToSQL(ds.Tables[0]);
                DataTable dt = NPOIHelper.ExcelToDataTable1(fileUrl);

                this.AddDatasetToSQL(dt);

                if (!string.IsNullOrEmpty(fileUrl) && System.IO.File.Exists(fileUrl))
                {
                    System.IO.File.Delete(fileUrl);//删除上传的XLS文件
                }

                this.FileExcel.Reset();
            }
            catch (Exception ex)
            {
                ShowNotify(ex.Message, MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion

        #region 导出按钮
        /// 导出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOut_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            string filename = Funs.GetNewFileName();
            Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("管线焊口" + filename, System.Text.Encoding.UTF8) + ".xls");
            Response.ContentType = "application/excel";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Write(GetGridTableHtml(Grid1));
            Response.End();
        }
        #endregion

        #region 将Dataset的数据导入数据库
        /// <summary>
        /// 将Dataset的数据导入数据库
        /// </summary>
        /// <param name="pds">数据集</param>
        /// <param name="Cols">数据集列数</param>
        /// <returns></returns>
        private void AddDatasetToSQL(DataTable pds)
        {
            if (pds != null && pds.Rows.Count > 0)
            {
                int ir = pds.Rows.Count;
                List<Model.Sys_DataInTemp> newDataInTempList = new List<Model.Sys_DataInTemp>();
                for (int i = 0; i < ir; i++)
                {
                    if (!string.IsNullOrEmpty(pds.Rows[i][3].ToString()))
                    {
                        Model.Sys_DataInTemp newDataInTemp = new Model.Sys_DataInTemp();
                        newDataInTemp.TempId = SQLHelper.GetNewID(typeof(Model.Sys_DataInTemp));
                        newDataInTemp.ProjectId = this.CurrUser.LoginProjectId;
                        newDataInTemp.UserId = this.CurrUser.UserId;
                        newDataInTemp.Time = System.DateTime.Now;
                        newDataInTemp.Type = this.IsPDMS;
                        newDataInTemp.RowNo = i + 2;
                        newDataInTemp.Value1 = pds.Rows[i][0].ToString().Trim();
                        newDataInTemp.Value2 = pds.Rows[i][1].ToString().Trim();
                        newDataInTemp.Value3 = pds.Rows[i][2].ToString().Trim();
                        newDataInTemp.Value4 = pds.Rows[i][3].ToString().Trim();
                        newDataInTemp.Value5 = pds.Rows[i][4].ToString().Trim();
                        if (this.IsPDMS == "0") ////非PDMS 模板
                        {
                            newDataInTemp.Value6 = pds.Rows[i][5].ToString().Trim();
                            newDataInTemp.Value7 = pds.Rows[i][6].ToString().Trim();
                            newDataInTemp.Value8 = pds.Rows[i][7].ToString().Trim();
                            newDataInTemp.Value9 = pds.Rows[i][8].ToString().Trim();
                            newDataInTemp.Value10 = pds.Rows[i][9].ToString().Trim();
                            newDataInTemp.Value11 = pds.Rows[i][10].ToString().Trim();
                            newDataInTemp.Value12 = pds.Rows[i][11].ToString().Trim();
                            newDataInTemp.Value13 = pds.Rows[i][12].ToString().Trim();
                            newDataInTemp.Value14 = pds.Rows[i][13].ToString().Trim();
                            newDataInTemp.Value15 = pds.Rows[i][14].ToString().Trim();
                            newDataInTemp.Value16 = pds.Rows[i][15].ToString().Trim();
                            newDataInTemp.Value17 = pds.Rows[i][16].ToString().Trim();
                            newDataInTemp.Value18 = pds.Rows[i][17].ToString().Trim();
                            newDataInTemp.Value19 = pds.Rows[i][18].ToString().Trim();
                            newDataInTemp.Value20 = pds.Rows[i][19].ToString().Trim();
                            newDataInTemp.Value21 = pds.Rows[i][20].ToString().Trim();
                            newDataInTemp.Value22 = pds.Rows[i][21].ToString().Trim();
                            newDataInTemp.Value23 = pds.Rows[i][22].ToString().Trim();
                            newDataInTemp.Value24 = pds.Rows[i][23].ToString().Trim();
                            newDataInTemp.Value25 = pds.Rows[i][24].ToString().Trim();
                            newDataInTemp.Value26 = pds.Rows[i][25].ToString().Trim();
                            newDataInTemp.Value27 = pds.Rows[i][26].ToString().Trim();
                            newDataInTemp.Value28 = pds.Rows[i][27].ToString().Trim();
                            newDataInTemp.Value29 = pds.Rows[i][28].ToString().Trim();
                            newDataInTemp.Value30 = pds.Rows[i][29].ToString().Trim();
                            newDataInTemp.Value31 = pds.Rows[i][30].ToString().Trim();
                            newDataInTemp.Value32 = pds.Rows[i][31].ToString().Trim();
                            newDataInTemp.Value33 = pds.Rows[i][32].ToString().Trim();
                            newDataInTemp.Value34 = pds.Rows[i][33].ToString().Trim();
                            newDataInTemp.Value35 = pds.Rows[i][34].ToString().Trim();
                            newDataInTemp.Value38 = pds.Rows[i][37].ToString().Trim();
                            newDataInTemp.Value39 = pds.Rows[i][36].ToString().Trim();
                            newDataInTemp.Value40 = pds.Rows[i][35].ToString().Trim();
                            newDataInTemp.Value41 = pds.Rows[i][38].ToString().Trim();
                            newDataInTemp.Value42 = pds.Rows[i][39].ToString().Trim();
                            newDataInTemp.Value43 = pds.Rows[i][40].ToString().Trim();
                            newDataInTemp.Value44 = pds.Rows[i][41].ToString().Trim();

                        }
                        else
                        {
                            newDataInTemp.Value7 = pds.Rows[i][5].ToString().Trim();
                            newDataInTemp.Value20 = pds.Rows[i][6].ToString().Trim();
                            newDataInTemp.Value15 = pds.Rows[i][7].ToString().Trim();
                            newDataInTemp.Value21 = pds.Rows[i][8].ToString().Trim();
                            newDataInTemp.Value23 = pds.Rows[i][9].ToString().Trim();//等级
                            newDataInTemp.Value37 = pds.Rows[i][10].ToString().Trim();//公称直径
                            newDataInTemp.Value13 = pds.Rows[i][11].ToString().Trim();//壁厚
                            newDataInTemp.Value18 = pds.Rows[i][12].ToString().Trim();//流体介质
                            newDataInTemp.Value19 = pds.Rows[i][13].ToString().Trim();//单线图号
                            newDataInTemp.Value24 = pds.Rows[i][14].ToString().Trim(); //组件类型
                            newDataInTemp.Value36 = pds.Rows[i][15].ToString().Trim();//数量
                            newDataInTemp.Value8 = pds.Rows[i][14].ToString().Trim();//接头形式
                            newDataInTemp.Value28 = pds.Rows[i][17].ToString().Trim();     //所属管段
                        }
                        newDataInTempList.Add(newDataInTemp);
                    }
                }

                BLL.DataInTempService.AddDataInTemp(newDataInTempList);


                this.BindGrid();
                ShowNotify("数据已导入临时表!", MessageBoxIcon.Success);
            }
            else
            {
                Alert.ShowInTop("导入数据为空!", MessageBoxIcon.Success);
                return;
            }
        }
        #endregion

        #region 保存审核事件
        /// <summary>
        /// 保存审核事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(() => { btnSaveMethod(this.CurrUser.LoginProjectId, this.CurrUser.UserId, this.IsPDMS); }));
            t.Start();
            if (percent.ContainsKey(this.CurrUser.UserId))
            {
                percent[CurrUser.UserId] = 0;
            }
            else
            {
                percent.Add(CurrUser.UserId, 0);

            }
            PageContext.RegisterStartupScript("printX()");

        }
        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            this.BindGrid();
        }

        protected void btnSaveMethod(string LoginProjectId, string UserId, string IsPDMS)
        {
            //beginProgress();
            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 == LoginProjectId
                        select x;
            var workAreas = from x in Funs.DB.ProjectData_WorkArea where x.ProjectId == LoginProjectId select x;
            var steels = from x in Funs.DB.Base_Material select x;
            var materialTypes = from x in Funs.DB.Base_MaterialType select x;
            var rates = from x in Funs.DB.Base_DetectionRate select x;
            var types = from x in Funs.DB.Base_WeldType select x;
            var methods = from x in Funs.DB.Base_WeldingMethod select x;
            var materials = from x in Funs.DB.Base_Consumables select x;
            var services = from x in Funs.DB.Base_TestMedium select x;
            var slopeTypes = from x in Funs.DB.Base_GrooveType select x;
            var isoClasss = from x in Funs.DB.Base_PipingClass select x;
            var components = from x in Funs.DB.Base_Components select x;
            var dns = from x in Funs.DB.Base_DNCompare select x;
            var dataInTemp = from x in Funs.DB.Sys_DataInTemp
                             where x.ProjectId == LoginProjectId && x.UserId == UserId && x.Type == IsPDMS
                             select x;
            int okCount = 0;
            int i = 0;
            int ir = dataInTemp.Count();
            string erreMessage = "";
            foreach (var tempData in dataInTemp)
            {

                //if (i % (ir / 100 + 1) == 0 && i < ir && i > 0)
                //{
                //    setProgress(i / (ir / 100 + 1));

                //    //此处用线程休眠代替实际的操作,如加载数据等
                //    //System.Threading.Thread.Sleep(50);
                //}
                //i++;
                if (tempData != null)
                {
                    i++;
                    percent[UserId] = (int)(100 * i / ir);
                    string errInfo = string.Empty;
                    var isExitValue = Funs.DB.View_JointInfoAndIsoInfo.FirstOrDefault(x => x.ProjectId == this.CurrUser.LoginProjectId && x.UnitCode == tempData.Value1
                        && x.WorkAreaCode == tempData.Value2 && x.ISO_IsoNo == tempData.Value3 && x.JOT_JointNo == tempData.Value4);
                    if (isExitValue == null || this.ckUpdate.Checked)
                    {
                        Model.PW_IsoInfo isoInfo = new Model.PW_IsoInfo(); ///管线
                        Model.PW_JointInfo jointInfo = new Model.PW_JointInfo();  ///焊口
                        jointInfo.JOT_JointStatus = "100";
                        isoInfo.Is_Standard = false;
                        if (!string.IsNullOrEmpty(tempData.Value1))
                        {
                            var unit = units.FirstOrDefault(x => x.UnitCode == tempData.Value1);
                            if (unit == null)
                            {
                                errInfo += "单位代码[" + tempData.Value1 + "]不存在;";
                            }
                            else
                            {
                                isoInfo.UnitId = unit.UnitId;
                            }
                        }
                        else
                        {
                            errInfo += "单位代码为必填项;";
                        }

                        if (!string.IsNullOrEmpty(tempData.Value2) && !string.IsNullOrEmpty(isoInfo.UnitId))
                        {
                            var workArea = workAreas.FirstOrDefault(x => x.WorkAreaCode == tempData.Value2 && x.UnitId == isoInfo.UnitId);
                            if (workArea == null)
                            {
                                errInfo += "工区编号[" + tempData.Value2 + "]该单位下不存在;";
                            }
                            else
                            {
                                isoInfo.WorkAreaId = workArea.WorkAreaId;
                            }
                        }
                        else
                        {
                            errInfo += "工区编号为必填项;";
                        }

                        if (string.IsNullOrEmpty(tempData.Value3))
                        {
                            errInfo += "管线代号此项为必填项!";
                        }
                        else
                        {
                            isoInfo.ISO_IsoNo = tempData.Value3;
                        }
                        if (string.IsNullOrEmpty(tempData.Value4))
                        {
                            errInfo += "焊口代号此项为必填项!";
                        }
                        else
                        {
                            jointInfo.JOT_JointNo = tempData.Value4;
                        }

                        #region 通用

                        if (!string.IsNullOrEmpty(tempData.Value5))
                        {
                            var materialType = materialTypes.FirstOrDefault(x => x.MaterialTypeCode == tempData.Value5);
                            if (materialType == null)
                            {
                                errInfo += "材质类型代号[" + tempData.Value5 + "]不存在;";
                            }
                            else
                            {
                                jointInfo.MaterialType = materialType.MaterialTypeId;
                            }
                        }

                        if (!string.IsNullOrEmpty(tempData.Value8))
                        {
                            jointInfo.Material1 = tempData.Value8;
                        }
                        if (!string.IsNullOrEmpty(tempData.Value9))
                        {
                            jointInfo.Material2 = tempData.Value9;
                        }
                        if (!string.IsNullOrEmpty(tempData.Value6))
                        {
                            var steel = steels.FirstOrDefault(x => x.MaterialCode == tempData.Value6);
                            if (steel == null)
                            {
                                errInfo += "材质1代号[" + tempData.Value6 + "]不存在;";
                            }
                            else
                            {
                                isoInfo.MaterialId = steel.MaterialId;
                                jointInfo.MaterialId = steel.MaterialId;
                            }
                        }
                        else
                        {
                            errInfo += "材质1代号为必填项;";
                        }

                        if (!string.IsNullOrEmpty(tempData.Value10))
                        {
                            var rate = rates.FirstOrDefault(x => x.DetectionRateCode == tempData.Value10);
                            if (rate == null)
                            {
                                errInfo += "探伤比例[" + tempData.Value10 + "]不存在;";
                            }
                            else
                            {
                                isoInfo.DetectionRateId = rate.DetectionRateId;
                                jointInfo.DetectionRateId = rate.DetectionRateId;
                            }
                        }
                        else
                        {
                            errInfo += "探伤比例为必填项;";
                        }
                        if (!string.IsNullOrEmpty(tempData.Value41))
                        {
                            if (tempData.Value41.Trim() == "是")
                            {
                                isoInfo.Is_Standard = true;
                                jointInfo.Extend_Length = tempData.Value43;
                                
                            }
                            else
                            {
                                isoInfo.Is_Standard = false;
                                
                            }
                        }

                        if (!string.IsNullOrEmpty(tempData.Value43))
                        {
                            isoInfo.ISO_Length = tempData.Value43;
                        }
                        //if (!string.IsNullOrEmpty(tempData.Value15))
                        //{
                        //    try
                        //    {
                        //        decimal testPress = Convert.ToDecimal(tempData.Value15);
                        //        isoInfo.ISO_TestPress = testPress;
                        //    }
                        //    catch (Exception)
                        //    {
                        //        errInfo += "试验压力[" + tempData.Value15 + "]错误;";
                        //    }
                        //}
                        isoInfo.ISO_TestPress = tempData.Value18;

                        //if (!string.IsNullOrEmpty(tempData.Value20))
                        //{
                        //    try
                        //    {
                        //        decimal testPress = Convert.ToDecimal(tempData.Value20);
                        //        isoInfo.ISO_DesignPress = testPress;
                        //    }
                        //    catch (Exception)
                        //    {
                        //        errInfo += "设计压力[" + tempData.Value20 + "]错误;";
                        //    }
                        //}
                        isoInfo.ISO_DesignPress = tempData.Value23;
                        if (!string.IsNullOrEmpty(tempData.Value24))
                        {
                            try
                            {

                                isoInfo.ISO_DesignTemperature = tempData.Value24;
                            }
                            catch (Exception)
                            {
                                errInfo += "设计温度[" + tempData.Value24 + "]错误;";
                            }
                        }
                        if (!string.IsNullOrEmpty(tempData.Value26))
                        {
                            var isoClass = isoClasss.FirstOrDefault(x => x.PipingClassCode == tempData.Value26);
                            if (isoClass == null)
                            {
                                errInfo += "管线等级代号[" + tempData.Value26 + "]不存在;";
                            }
                            else
                            {
                                isoInfo.PipingClassId = isoClass.PipingClassId;
                            }
                        }
                        if (string.IsNullOrEmpty(tempData.Value16))
                        {
                            errInfo += "壁厚此项为必填项!";
                        }
                        else
                        {
                            jointInfo.JOT_Sch = tempData.Value16;
                        }
                        if (!string.IsNullOrEmpty(tempData.Value21))
                        {
                            var service = services.FirstOrDefault(x => x.MediumCode == tempData.Value21);
                            if (service == null)
                            {
                                errInfo += "介质代号[" + tempData.Value21 + "]不存在;";
                            }
                            else
                            {
                                isoInfo.TestMediumId = service.TestMediumId;
                            }
                        }
                        isoInfo.ISO_IsoNumber = tempData.Value22;
                        jointInfo.JOT_BelongPipe = tempData.Value31;
                        jointInfo.WallBoard = tempData.Value42;
                        #endregion

                        if (this.IsPDMS == "0") ////非PDMS 模板
                        {
                            #region 非PDMS 模板
                            if (!string.IsNullOrEmpty(tempData.Value7))
                            {
                                var steel = steels.FirstOrDefault(x => x.MaterialCode == tempData.Value7);
                                if (steel == null)
                                {
                                    errInfo += "材质2代号[" + tempData.Value7 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.MaterialId = steel.MaterialId;
                                }
                            }
                            if (!string.IsNullOrEmpty(tempData.Value11))
                            {
                                var type = types.FirstOrDefault(x => x.WeldTypeCode == tempData.Value11);
                                if (type == null)
                                {
                                    errInfo += "焊缝类型代号[" + tempData.Value11 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.JOTY_ID = type.WeldTypeId;
                                }
                            }
                            else
                            {
                                errInfo += "焊缝类型代号为必填项;";
                            }
                            if (!string.IsNullOrEmpty(tempData.Value12))
                            {
                                if (tempData.Value12 != "安装" && tempData.Value12 != "预制")
                                {
                                    errInfo += "焊接区域[" + tempData.Value12 + "]不存在;";
                                }
                                else
                                {
                                    if (tempData.Value12 == "安装")
                                    {
                                        jointInfo.WLO_Code = "F";
                                    }
                                    else
                                    {
                                        jointInfo.WLO_Code = "S";
                                    }
                                }
                            }
                            //else
                            //{
                            //    errInfo += "焊接区域为必填项;";
                            //}
                            if (!string.IsNullOrEmpty(tempData.Value13))
                            {
                                if (tempData.Value13 != "固定" && tempData.Value13 != "活动")
                                {
                                    errInfo += "焊口属性[" + tempData.Value13 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.JOT_JointAttribute = tempData.Value13;
                                }
                            }
                            //else
                            //{
                            //    errInfo += "焊口属性为必填项;";
                            //}
                            if (!string.IsNullOrEmpty(tempData.Value14))
                            {
                                try
                                {
                                    decimal doneDin = Convert.ToDecimal(tempData.Value14);
                                    jointInfo.JOT_Size = doneDin;
                                    isoInfo.ISO_Specification = doneDin.ToString();
                                }
                                catch (Exception)
                                {
                                    errInfo += "达因数[" + tempData.Value14 + "]错误;";
                                }
                            }
                            else
                            {
                                errInfo += "达因数为必填项;";
                            }
                            if (string.IsNullOrEmpty(tempData.Value15))
                            {
                                errInfo += "规格此项为必填项!";
                            }
                            else
                            {
                                jointInfo.JOT_JointDesc = tempData.Value15;
                            }

                            if (!string.IsNullOrEmpty(tempData.Value17))
                            {
                                var method = methods.FirstOrDefault(x => x.WeldingMethodCode == tempData.Value17);
                                if (method == null)
                                {
                                    errInfo += "焊接方法代号[" + tempData.Value17 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.WME_ID = method.WeldingMethodId;
                                }
                            }
                            else
                            {
                                errInfo += "焊接方法代号为必填项;";
                            }
                            if (!string.IsNullOrEmpty(tempData.Value19))
                            {
                                var material = materials.FirstOrDefault(x => x.ConsumablesCode == tempData.Value19 && x.ConsumablesType == "2");
                                if (material == null)
                                {
                                    errInfo += "焊条代号[" + tempData.Value19 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.JOT_WeldMat = material.ConsumablesId;
                                }
                            }
                            if (!string.IsNullOrEmpty(tempData.Value20))
                            {
                                var material = materials.FirstOrDefault(x => x.ConsumablesCode == tempData.Value20 && x.ConsumablesType == "1");
                                if (material == null)
                                {
                                    errInfo += "焊丝代号[" + tempData.Value20 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.JOT_WeldSilk = material.ConsumablesId;
                                }
                            }
                            if (!string.IsNullOrEmpty(tempData.Value25))
                            {
                                var slopeType = slopeTypes.FirstOrDefault(x => x.GrooveTypeCode == tempData.Value25);
                                if (slopeType == null)
                                {
                                    errInfo += "坡口代号[" + tempData.Value25 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.JST_ID = slopeType.GrooveTypeId;
                                }
                            }
                            else
                            {
                                errInfo += "坡口代号必填项;";
                            }
                            if (!string.IsNullOrEmpty(tempData.Value27))
                            {
                                var component = components.FirstOrDefault(x => x.ComponentsCode == tempData.Value27);
                                if (component == null)
                                {
                                    errInfo += "组件一代号[" + tempData.Value27 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.JOT_Component1 = component.ComponentsId;
                                }
                            }
                            if (!string.IsNullOrEmpty(tempData.Value28))
                            {
                                var component = components.FirstOrDefault(x => x.ComponentsCode == tempData.Value28);
                                if (component == null)
                                {
                                    errInfo += "组件二代号[" + tempData.Value28 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.JOT_Component2 = component.ComponentsId;
                                }
                            }
                            jointInfo.JOT_HeartNo1 = tempData.Value29;
                            jointInfo.JOT_HeartNo2 = tempData.Value30;
                            if (!string.IsNullOrEmpty(tempData.Value32))
                            {
                                try
                                {
                                    decimal testPress = Convert.ToDecimal(tempData.Value32);
                                    jointInfo.JOT_PrepareTemp = testPress;
                                }
                                catch (Exception)
                                {
                                    errInfo += "预热温度[" + tempData.Value32 + "]错误;";
                                }
                            }
                            if (!string.IsNullOrEmpty(tempData.Value30))
                            {
                                if (tempData.Value33 != "是" && tempData.Value33 != "否")
                                {
                                    errInfo += "是否热处理[" + tempData.Value33 + "]错误;";
                                }
                                else
                                {
                                    if (tempData.Value33 == "是")
                                    {
                                        jointInfo.IS_Proess = "1";
                                    }
                                    else
                                    {
                                        jointInfo.IS_Proess = "0";
                                    }
                                }
                            }
                            jointInfo.JOT_HotRpt = tempData.Value34;
                            if (!string.IsNullOrEmpty(tempData.Value35))
                            {
                                if (tempData.Value35 != "1G" && tempData.Value35 != "2G" && tempData.Value35 != "3G" && tempData.Value35 != "4G" && tempData.Value35 != "5G" && tempData.Value35 != "6G" && tempData.Value35 != "1F" && tempData.Value35 != "2F" && tempData.Value35 != "2FR"
                                    && tempData.Value35 != "4F" && tempData.Value35 != "5F" && tempData.Value35 != "5FG" && tempData.Value35 != "6FG" && tempData.Value35 != "2FG" && tempData.Value35 != "4FG")
                                {
                                    errInfo += "焊接位置[" + tempData.Value35 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.JOT_Location = tempData.Value35;
                                }
                            }
                            //else
                            //{
                            //    errInfo += "焊接位置必填项;";
                            //}
                            if (!string.IsNullOrEmpty(tempData.Value36))
                            {
                                try
                                {
                                    decimal testPress = Convert.ToDecimal(tempData.Value36);
                                    jointInfo.JOT_Dia = testPress;
                                }
                                catch (Exception)
                                {
                                    errInfo += "外径[" + tempData.Value36 + "]错误;";
                                }
                            }
                            if (!string.IsNullOrEmpty(tempData.Value37))
                            {
                                try
                                {
                                    decimal testPress = Convert.ToDecimal(tempData.Value37);
                                    isoInfo.ISO_HardnessRate = Convert.ToDecimal(testPress) / Convert.ToDecimal(1.0 * 100);
                                }
                                catch (Exception)
                                {
                                    errInfo += "硬度检测比例[" + tempData.Value37 + "]错误;";
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            #region PDMS模板
                            if (!string.IsNullOrEmpty(tempData.Value40))
                            {
                                //var dn = dns.FirstOrDefault(x => x.DN.ToString() == tempData.Value40);
                                //if (dn == null)
                                //{
                                //    errInfo += "公称直径[" + tempData.Value40 + "]基础表中不存在;";
                                //}
                                //else
                                //{
                                //    try
                                //    {
                                //        int count = Convert.ToInt32(tempData.Value40);
                                //    }
                                //    catch (Exception)
                                //    {
                                //        errInfo += "公称直径[" + tempData.Value40 + "]错误;";
                                //    }
                                //}
                            }
                            if (!string.IsNullOrEmpty(tempData.Value27))
                            {
                                var component = components.FirstOrDefault(x => x.ComponentsCode == tempData.Value27);
                                if (component == null)
                                {
                                    errInfo += "组件类型[" + tempData.Value27 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.JOT_Component1 = component.ComponentsId;
                                }
                            }
                            if (string.IsNullOrEmpty(tempData.Value39))
                            {
                                errInfo += "数量(组件)必填项;";
                            }
                            else
                            {
                                jointInfo.ComponentNum = tempData.Value39;
                            }
                            if (!string.IsNullOrEmpty(tempData.Value11))
                            {
                                var type = types.FirstOrDefault(x => x.WeldTypeCode == tempData.Value11);
                                if (type == null)
                                {
                                    errInfo += "接头形式[" + tempData.Value11 + "]不存在;";
                                }
                                else
                                {
                                    jointInfo.JOTY_ID = type.WeldTypeId;
                                }
                            }
                            else
                            {
                                errInfo += "接头形式为必填项;";
                            }
                            jointInfo.WLO_Code = "S";
                            jointInfo.JOT_JointAttribute = "活动";
                            jointInfo.JOT_Location = "1G";
                            jointInfo.JOT_Size = BLL.Base_DNCompareService.GetSizeByDn(tempData.Value40); // 生成尺寸
                            if (Funs.GetNewIntOrZero(tempData.Value40) <= 50)  // 生成焊接方法
                            {
                                var m = methods.FirstOrDefault(x => x.WeldingMethodCode.Contains("GTAW"));
                                if (m != null)
                                {
                                    jointInfo.WME_ID = m.WeldingMethodId;
                                }
                            }
                            else
                            {
                                var m = methods.FirstOrDefault(x => x.WeldingMethodCode.Contains("GTAW") && x.WeldingMethodCode.Contains("SMAW"));
                                if (m != null)
                                {
                                    jointInfo.WME_ID = m.WeldingMethodId;
                                }
                            }
                            if (!string.IsNullOrEmpty(tempData.Value40) && !string.IsNullOrEmpty(tempData.Value16))
                            {
                                jointInfo.JOT_JointDesc = tempData.Value40 + "×" + tempData.Value16;
                            }
                            if (!string.IsNullOrEmpty(tempData.Value16))
                            {
                                jointInfo.JOT_Sch = tempData.Value16;
                            }
                            if (!string.IsNullOrEmpty(tempData.Value27))
                            {
                                var component = components.FirstOrDefault(x => x.ComponentsName.Contains(tempData.Value27));
                                if (component != null)
                                {
                                    jointInfo.JOT_Component1 = component.ComponentsId;
                                    jointInfo.JOT_Component2 = jointInfo.JOT_Component1;
                                }
                            }
                            #endregion
                        }

                        if (string.IsNullOrEmpty(errInfo)) ////所有信息正确的话 这插入管线焊口
                        {
                            isoInfo.ProjectId = this.CurrUser.LoginProjectId;
                            jointInfo.ProjectId = this.CurrUser.LoginProjectId;
                            var isExitISOValue = Funs.DB.View_JointInfoAndIsoInfo.FirstOrDefault(x => x.ProjectId == this.CurrUser.LoginProjectId && x.UnitCode == tempData.Value1
                                                 && x.WorkAreaCode == tempData.Value2 && x.ISO_IsoNo == tempData.Value3);
                            if (isExitISOValue != null) ///管线已存在
                            {
                                isoInfo.ISO_ID = isExitISOValue.ISO_ID;
                                jointInfo.ISO_ID = isExitISOValue.ISO_ID;
                                BLL.PW_IsoInfoService.UpdateIsoInfo(isoInfo);
                            }
                            else
                            {
                                isoInfo.ISO_ID = SQLHelper.GetNewID(typeof(Model.PW_IsoInfo));
                                jointInfo.ISO_ID = isoInfo.ISO_ID;
                                BLL.PW_IsoInfoService.AddIsoInfo(isoInfo);
                            }
                            var isExitJotNoValue = Funs.DB.View_JointInfoAndIsoInfo.FirstOrDefault(x => x.ProjectId == this.CurrUser.LoginProjectId && x.UnitCode == tempData.Value1
                                                   && x.WorkAreaCode == tempData.Value2 && x.ISO_IsoNo == tempData.Value3 && x.JOT_JointNo == tempData.Value4 && x.JOT_JointStatus != "104");
                            if (isExitJotNoValue == null)
                            {
                                BLL.PW_JointInfoService.AddJointInfo(jointInfo);
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(isExitJotNoValue.DReportID))
                                {
                                    jointInfo.JOT_ID = isExitJotNoValue.JOT_ID;
                                    BLL.PW_JointInfoService.UpdateJointInfo(jointInfo);
                                }
                            }
                            BLL.DataInTempService.DeleteDataInTempByDataInTempID(tempData.TempId);
                            okCount++;
                        }
                    }
                    else
                    {
                        errInfo = "该条记录已存在于管线、焊口信息表中。";
                    }

                    if (!string.IsNullOrEmpty(errInfo))
                    {
                        tempData.ToopValue = errInfo;
                        BLL.DataInTempService.UpdateDataInTemp(tempData);
                        erreMessage += errInfo + ";";

                    }

                }
            }

            //if (!string.IsNullOrEmpty(erreMessage))
            //{
            //  //  ShowNotify(erreMessage, MessageBoxIcon.Error);

            //    Alert n = new Alert
            //    {
            //        Target = Target.Top,
            //        Message = erreMessage,
            //        MessageBoxIcon = MessageBoxIcon.Error, 
            //        ShowHeader = false
            //    };
            //    n.Show();
            //}
            //else
            //{
            //    ShowNotify("保存操作已完成,成功保存" + okCount.ToString() + "条数据到管线焊口表!", MessageBoxIcon.Success);

            //}

            //this.BindGrid();
        }
        #endregion

        #region 删除所有数据事件
        /// <summary>
        /// 删除所有数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAllDelete_Click(object sender, EventArgs e)
        {
            ////先删除临时表中 该人员以前导入的数据
            BLL.DataInTempService.DeleteDataInTempByProjectIdUserId(this.CurrUser.LoginProjectId, this.CurrUser.UserId, this.IsPDMS);
            this.BindGrid();
            ShowNotify("删除成功!", MessageBoxIcon.Success);
            this.lbDataCout.Text = string.Empty;
        }
        #endregion

        #region 模版导入说明 下载
        /// <summary>
        /// 下载模版
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgbtnUpload_Click(object sender, EventArgs e)
        {
            if (this.IsPDMS == "0")
            {
                this.TemplateUpload(BLL.Const.HJGL_DataInTemplateUrl);
            }
            else
            {
                this.TemplateUpload(BLL.Const.HJGL_DataIn_PDMSTemplateUrl);
            }
        }

        /// <summary>
        /// 导入说明
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lkAchievements_Click(object sender, EventArgs e)
        {
            this.TemplateUpload(Const.HJGL_DataInHelpUrl);
        }

        /// <summary>
        /// 模板下载方法
        /// </summary>
        /// <param name="initTemplatePath"></param>
        protected void TemplateUpload(string initTemplatePath)
        {
            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

        public static Dictionary<string, int> percent { get; set; }
        public static Dictionary<string, string> url { get; set; }

        [System.Web.Services.WebMethod]
        public static int getPercent(string id)
        {
            return percent[id];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnD_Click(object sender, EventArgs e)
        {
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                int count = 0;
                var getD = db.Sys_DataInTemp.Where(x => x.ProjectId == this.CurrUser.LoginProjectId && x.ToopValue == "该条记录已存在于管线、焊口信息表中。");
                if (getD.Count() > 0)
                {
                    count = getD.Count();
                    db.Sys_DataInTemp.DeleteAllOnSubmit(getD);
                    db.SubmitChanges();
                }

                this.BindGrid();
                ShowNotify("删除成功!"+count.ToString(), MessageBoxIcon.Success);
            }
        }
    }
}