using BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace FineUIPro.Web.HJGL.WeldingManage
{
    public partial class PointShowSearch : PageBase
    {
        #region 定义变量
        /// 
        /// 单位ID
        /// 
        public string UnitId
        {
            get
            {
                return (string)ViewState["UnitId"];
            }
            set
            {
                ViewState["UnitId"] = value;
            }
        }
        /// 
        /// 装置ID
        /// 
        public string InstallationId
        {
            get
            {
                return (string)ViewState["InstallationId"];
            }
            set
            {
                ViewState["InstallationId"] = value;
            }
        }
        public string selectedList
        {
            get
            {
                return (string)ViewState["selectedList"];
            }
            set
            {
                ViewState["selectedList"] = value;
            }
        }
        /// 
        /// 已焊接未点口的焊工
        /// 
        private static List personManageLists = new List();
        #endregion
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UnitId = Request.Params["unitId"];
                InstallationId = Request.Params["installationId"];
                var unit = BLL.UnitService.GetUnitByUnitId(this.CurrUser.UnitId);
                if (BLL.WorkAreaService.IsSupervisor(this.CurrUser.UnitId, this.CurrUser.LoginProjectId))
                {
                    BLL.WorkAreaService.GetWorkAreaListByInstallSupervisorUnit(this.drpWorkArea, this.CurrUser.LoginProjectId, InstallationId, UnitId, this.CurrUser.UnitId, true);
                }
                else
                {
                    BLL.WorkAreaService.GetWorkAreaListByInstallUnit(this.drpWorkArea, this.CurrUser.LoginProjectId, InstallationId, UnitId, true);
                }
                BLL.Base_DetectionRateService.InitDetectionRateDropDownList(this.drpNDTR_Id, true);
            }
        }
        #endregion
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (this.drpWorkArea.SelectedValue != BLL.Const._Null && !string.IsNullOrEmpty(this.drpWorkArea.SelectedValue))
            {
                this.InitTreeMenu(this.drpWorkArea.SelectedValue);//加载树  
            }
            else
            {
                Alert.ShowInTop("请选择施工区域!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #region 加载树
        /// 
        /// 加载树节点
        /// 
        /// 
        private void InitTreeMenu(string workAreaId)
        {
            if (!string.IsNullOrEmpty(workAreaId))
            {
                this.tvControlItem.Nodes.Clear();
                TreeNode rootNode = new TreeNode();
                rootNode.Text = BLL.WorkAreaService.GetWorkAreaCodeByWorkAreaId(workAreaId);
                rootNode.NodeID = workAreaId;
                rootNode.Expanded = true;
                this.tvControlItem.Nodes.Add(rootNode);
                var isoInfos = from x in Funs.DB.PW_JointInfo
                               where x.PW_PointID == null && x.DReportID != null && x.JOT_CellWelder != null && x.JOT_FloorWelder != null
                               && x.JOT_JointStatus == "100"
                               join y in Funs.DB.PW_IsoInfo on x.ISO_ID equals y.ISO_ID
                               where y.WorkAreaId == workAreaId
                               select new { x.ISO_ID, y.ISO_IsoNo, y.DetectionRateId };
                if (!string.IsNullOrEmpty(this.txtISO_ID.Text.Trim()))
                {
                    isoInfos = isoInfos.Where(x => x.ISO_IsoNo.Contains(this.txtISO_ID.Text.Trim()));
                }
                if (this.drpNDTR_Id.SelectedValue != BLL.Const._Null && !string.IsNullOrEmpty(this.drpNDTR_Id.SelectedValue))
                {
                    isoInfos = isoInfos.Where(x => x.DetectionRateId == this.drpNDTR_Id.SelectedValue);
                }
                if (isoInfos.Count() > 0)
                {
                    isoInfos = isoInfos.Distinct();
                    foreach (var item in isoInfos)
                    {
                        string rate = string.Empty;
                        if (!string.IsNullOrEmpty(item.DetectionRateId))
                        {
                            var ndtr = BLL.Base_DetectionRateService.GetDetectionRateByDetectionRateId(item.DetectionRateId);
                            if (ndtr != null)
                            {
                                rate = ndtr.DetectionRateCode;
                            }
                        }
                        TreeNode newNode = new TreeNode();
                        newNode.Text = item.ISO_IsoNo + "【" + rate + "%】";
                        newNode.NodeID = item.ISO_ID;
                        newNode.Expanded = true;
                        newNode.EnableClickEvent = true;
                        rootNode.Nodes.Add(newNode);
                    }
                }
            }
        }
        #endregion
        #region 树点击事件
        /// 
        /// Tree点击事件
        /// 
        /// 
        /// 
        protected void tvControlItem_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            HashSet set = new HashSet();
            foreach (var id in Grid1.SelectedRowIDArray)
            {
                set.Add(id);
            }
            if (!string.IsNullOrEmpty(selectedList))
            {
                foreach (var id in selectedList.Split(','))
                {
                    set.Add(id);
                }
            }
            selectedList = string.Join(",", set.ToArray());
            string isoId = this.tvControlItem.SelectedNodeID;
            int num = BLL.PW_JointInfoService.GetJointCountByIsoIdPoint(isoId);
            int gnum = BLL.PW_JointInfoService.GetJointCountByIsoIdJointAttribute(isoId, "固定");
            int hnum = BLL.PW_JointInfoService.GetJointCountByIsoIdJointAttribute(isoId, "活动");
            var total = from x in Funs.DB.PW_JointInfo where x.ISO_ID == isoId select x;
            this.lblPointNum.Text = num.ToString();
            if (total.Count() > 0)
            {
                this.lblPonitRate.Text = (((double)num / total.Count()) * 100).ToString("##.0") + "%";
            }
            else
            {
                this.lblPonitRate.Text = "0%";
            }
            this.lblGdk.Text = gnum.ToString();
            this.lblGdkRate.Text = (((double)gnum / total.Count()) * 100).ToString("##.0") + "%";
            this.lblHdk.Text = hnum.ToString();
            this.lblHdkRate.Text = (((double)hnum / total.Count()) * 100).ToString("##.0") + "%";
            string strSql = @"select * from (
                            select JOTY_ID ,count(*)  as num  from  PW_JointInfo 
                            where ISO_ID ='"+ isoId + @"'
                            group by JOTY_ID ) a  left join Base_WeldType b on a.JOTY_ID=b.WeldTypeId ";
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, null);
            int total1 = 0;
            int total2 = 0;
            if (tb != null)
            {
                foreach(DataRow row in tb.Rows)
                {
                    if ("对接" == row["WeldTypeName"].ToString())
                    {
                        total1 += Funs.GetNewIntOrZero(row["num"].ToString());
                    }
                    else if ("管与管件对接" == row["WeldTypeName"].ToString())
                    {
                        total1 += Funs.GetNewIntOrZero(row["num"].ToString());
                    }
                    else if ("承插" == row["WeldTypeName"].ToString())
                    {
                        total2 += Funs.GetNewIntOrZero(row["num"].ToString());
                    }
                    else if ("搭接" == row["WeldTypeName"].ToString())
                    {
                        total2 += Funs.GetNewIntOrZero(row["num"].ToString());
                    }
                    else if ("T型焊缝" == row["WeldTypeName"].ToString())
                    {
                        total2 += Funs.GetNewIntOrZero(row["num"].ToString());
                    }
                    else if ("角焊缝" == row["WeldTypeName"].ToString())
                    {
                        total2 += Funs.GetNewIntOrZero(row["num"].ToString());
                    }
                    else if ("角接焊缝(支管台)" == row["WeldTypeName"].ToString())
                    {
                        total2 += Funs.GetNewIntOrZero(row["num"].ToString());
                    }
                    
                }
            }
            this.lblTotalPoint.Text = "对接焊缝"+ total1+ ",承插或角焊缝" + total2;
           
            cbJOTDia.Checked = false;
            try
            {
                var maxJOTDia = BLL.PW_JointInfoService.GetMaxJOTDiaByIsoIdPoint(this.CurrUser.LoginProjectId, isoId);
                if (maxJOTDia.HasValue && maxJOTDia.Value >= 500)
                {
                    cbJOTDia.Checked = true;
                }
                else
                {
                    cbJOTDia.Checked = false;
                }
            } catch (Exception ex)  { }
            BindGrid(isoId);
            //未点口的焊工
            personManageLists.Clear();
            personManageLists = BLL.WelderService.GetWelderList(this.CurrUser.LoginProjectId, UnitId, isoId);
            this.Grid2.DataSource = personManageLists;
            this.Grid2.DataBind();
            this.Grid3.DataSource = BLL.WelderService.GetNoCheckWelderList(this.CurrUser.LoginProjectId, UnitId, isoId);
            this.Grid3.DataBind();
        }
        #endregion
        #region 数据绑定
        /// 
        /// 数据绑定
        /// 
        private void BindGrid(string isoId)
        {
            string strSql = @"SELECT 0 [index], jointInfo.JOT_ID,jointInfo.JOT_Sch,
                                     jointInfo.ProjectId,
                                     jointInfo.ISO_ID,
                                     jointInfo.JOT_JointNo,
                                     jointInfo.DReportID,
                                     jointInfo.JOT_Dia,
                                     isoInfo.ISO_IsoNo,
                                     reportMain.JOT_WeldDate,
                                    (select top 1 ProessDate from HJGL_HotProess_Report where WeldJointId = jointInfo.JOT_ID )     JOT_ProessDate,--热处理日期
                                     cellWelder.WED_Code AS CellWelderCode,
                                     weldType.WeldTypeName,
                                     case when isoInfo.[Is_Standard] = 0 then
                                     (detectionRate.DetectionRate+'%') else (detectionRate1.DetectionRate+'%') end AS DetectionRate"
							+ @" FROM PW_JointInfo AS jointInfo "
                            + @" LEFT JOIN PW_IsoInfo AS isoInfo ON isoInfo.ISO_ID = jointInfo.ISO_ID "
                            + @" LEFT JOIN BO_WeldReportMain AS reportMain ON reportMain.DReportID = jointInfo.DReportID "
                            + @" LEFT JOIN BS_Welder AS cellWelder ON cellWelder.WED_ID = jointInfo.JOT_CellWelder "
                            + @" LEFT JOIN Base_WeldType AS weldType ON weldType.WeldTypeId = jointInfo.JOTY_ID"
                            + @" LEFT JOIN Base_DetectionRate AS detectionRate ON detectionRate.DetectionRateId = isoInfo.DetectionRateId"
                            + @" LEFT JOIN Base_DetectionRate AS detectionRate1 ON detectionRate1.DetectionRateId = jointInfo.DetectionRateId"
                            + @" WHERE jointInfo.PW_PointID IS NULL AND jointInfo.DReportID IS NOT NULL AND jointInfo.JOT_JointStatus!='104'"
                            + @" AND jointInfo.ProjectId= @projectId AND jointInfo.ISO_ID=@isoId";
            List listStr = new List
            {
                new SqlParameter("@projectId", this.CurrUser.LoginProjectId),
                new SqlParameter("@isoId", isoId),
            };
            if (cbJOTDia.Checked)
            {
                strSql += " and jointInfo.JOT_Dia  >=500 ";
            }
            if (!string.IsNullOrEmpty(txtJOTJointNo.Text))
            {
                strSql += " and jointInfo.JOT_JointNo like '%"+ txtJOTJointNo.Text + "%'";
            }
            strSql += " order by jointInfo.JOT_JointNo asc";
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            if (tb != null)
            { 
                foreach (DataRow row in tb.Rows)
                {
                    try
                    {
                        row["index"] = int.Parse(System.Text.RegularExpressions.Regex.Replace(row["JOT_JointNo"].ToString(), @"[^0-9]+", ""));
                    }
                    catch (Exception e)
                    {
                        
                    }
                }
            }
            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = tb;  
            Grid1.DataBind();
            if (!string.IsNullOrEmpty(selectedList))
            {
                string[] selectedIds = selectedList.Split(',');
                List selectId = new List();
                foreach(var id in selectedIds)
                {
                    foreach(DataRow row in tb.Rows)
                    {
                        if(id == row["JOT_ID"].ToString())
                        {
                            selectId.Add(id);
                        }
                    }
                }
                Grid1.SelectedRowIDArray = selectId.ToArray();
            }
          
        }
        #endregion
        protected void txtJOTJointNo_OnTextChanged(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIDArray.Length > 0)
            {
                selectedList += string.Join(",", Grid1.SelectedRowIDArray);
            }
            BindGrid(this.tvControlItem.SelectedNodeID);
        }
        #region 确定
        /// 
        /// 确定按钮
        /// 
        /// 
        /// 
        protected void btnSure_Click(object sender, EventArgs e)
        {
            HashSet set = new HashSet();
            foreach (var id in Grid1.SelectedRowIDArray)
            {
                set.Add(id);
            }
            if (!string.IsNullOrEmpty(selectedList))
            {
                foreach (var id in selectedList.Split(','))
                {
                    set.Add(id);
                }
            }
            selectedList = string.Join(",", set.ToArray());
            PageContext.RegisterStartupScript(ActiveWindow.GetWriteBackValueReference(selectedList)
                   + ActiveWindow.GetHidePostBackReference());
        }
        #endregion
        protected void cbJOTDia_CheckedChanged(object sender, CheckedEventArgs e)
        {
            if (Grid1.SelectedRowIDArray.Length > 0)
            {
                selectedList += string.Join(",", Grid1.SelectedRowIDArray);
            }
            BindGrid(this.tvControlItem.SelectedNodeID);
        }
    }
}