using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
namespace FineUIPro.Web.HJGL.HotProcessHard
{
    public partial class HardReport : PageBase
    {
        #region 定义项
        /// 
        /// 硬度委托主键
        /// 
        public string HardTrustID
        {
            get
            {
                return (string)ViewState["HardTrustID"];
            }
            set
            {
                ViewState["HardTrustID"] = value;
            }
        }
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ddlPageSize.SelectedValue = this.Grid1.PageSize.ToString();
                this.HardTrustID = string.Empty;
                this.InitTreeMenu();//加载树
            }
        }
        #endregion
        #region 加载树
        /// 
        /// 加载树
        /// 
        private void InitTreeMenu()
        {
            this.tvControlItem.Nodes.Clear();
            TreeNode rootNode = new TreeNode();
            rootNode.Text = "装置-单位-工作区";
            rootNode.NodeID = "0";
            rootNode.Expanded = true;
            this.tvControlItem.Nodes.Add(rootNode);
            ////装置
            var pInstallation = (from x in Funs.DB.Project_Installation where x.ProjectId == this.CurrUser.LoginProjectId select x).ToList();
            ////区域
            var pWorkArea = (from x in Funs.DB.ProjectData_WorkArea where x.ProjectId == this.CurrUser.LoginProjectId select x).ToList();
            ////单位
            var pUnits = (from x in Funs.DB.Project_ProjectUnit where x.ProjectId == this.CurrUser.LoginProjectId select x).ToList();
            var workAreaIdList = (from x in BLL.Funs.DB.PW_IsoInfo
                                  where x.ProjectId == this.CurrUser.LoginProjectId
                                  orderby x.ISO_IsoNo
                                  select x.WorkAreaId).Distinct().ToList();
            pWorkArea = pWorkArea.Where(x => workAreaIdList.Contains(x.WorkAreaId)).OrderBy(x => x.WorkAreaCode).ToList();
            pInstallation = (from x in pInstallation
                             join y in pWorkArea on x.InstallationId equals y.InstallationId
                             select x).Distinct().ToList();
            pUnits = (from x in pUnits
                      join y in pWorkArea on x.UnitId equals y.UnitId
                      select x).Distinct().ToList();
            this.BindNodes(rootNode, pInstallation, pWorkArea, pUnits);
        }
        /// 
        ///  绑定树节点
        /// 
        /// 
        private void BindNodes(TreeNode node, List pInstallation, List pWorkArea, List pUnits)
        {
            if (string.IsNullOrEmpty(node.ToolTip))
            {
                List installations = pInstallation;
                var pUnit = pUnits.FirstOrDefault(x => x.UnitId == this.CurrUser.UnitId);
                if (pUnit != null && pUnit.UnitType != Const.ProjectUnitType_1 && pUnit.UnitType != Const.ProjectUnitType_5)
                {
                    installations = (from x in pInstallation
                                     join y in pWorkArea on x.InstallationId equals y.InstallationId
                                     where y.UnitId == this.CurrUser.UnitId
                                     orderby x.InstallationId
                                     select x).Distinct().ToList();
                }
                foreach (var q in installations)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.NodeID = q.InstallationId;
                    newNode.Text = q.InstallationName;
                    newNode.ToolTip = "装置";
                    newNode.Expanded = true;
                    node.Nodes.Add(newNode);
                    this.BindNodes(newNode, pInstallation, pWorkArea, pUnits);
                }
            }
            else if (node.ToolTip == "装置")
            {
                List units = null;
                var pUnitDepth = pUnits.FirstOrDefault(x => x.UnitId == this.CurrUser.UnitId);
                if (pUnitDepth == null || pUnitDepth.UnitType == Const.ProjectUnitType_1 || pUnitDepth.UnitType == Const.ProjectUnitType_5)
                {
                    units = (from x in pUnits
                             join y in pWorkArea on x.UnitId equals y.UnitId
                             where y.InstallationId == node.NodeID && x.UnitType == Const.ProjectUnitType_2
                             select x).ToList();
                }
                else
                {
                    units = (from x in pUnits
                             join y in pWorkArea on x.UnitId equals y.UnitId
                             where y.InstallationId == node.NodeID && x.UnitType == Const.ProjectUnitType_2 && x.UnitId == this.CurrUser.UnitId
                             select x).ToList();
                }
                units = units.OrderBy(x => x.InTime).Distinct().ToList();
                foreach (var q in units)
                {
                    var unit = BLL.UnitService.GetUnitByUnitId(q.UnitId);
                    if (unit != null)
                    {
                        TreeNode newNode = new TreeNode();
                        newNode.Text = unit.UnitName;
                        newNode.NodeID = q.UnitId + "|" + node.NodeID;
                        newNode.ToolTip = "单位";
                        node.Nodes.Add(newNode);
                        this.BindNodes(newNode, pInstallation, pWorkArea, pUnits);
                    }
                }
            }
            else if (node.ToolTip == "单位")
            {
                var workAreas = (from x in pWorkArea
                                 where x.InstallationId == node.ParentNode.NodeID && x.UnitId == node.NodeID.Split('|')[0]
                                 select x);
                workAreas = workAreas.OrderByDescending(x => x.WorkAreaCode);
                foreach (var q in workAreas)
                {
                    TreeNode newNode1 = new TreeNode();
                    newNode1.Text = q.WorkAreaCode;
                    newNode1.NodeID = q.WorkAreaId + "|" + node.NodeID;
                    newNode1.EnableExpandEvent = true;
                    newNode1.ToolTip = "区域";
                    node.Nodes.Add(newNode1);
                    this.BindNodes(newNode1, pInstallation, pWorkArea, pUnits);
                }
            }
            else if (node.ToolTip == "区域")
            {
                List trustLists = new List();
                if (!string.IsNullOrEmpty(this.txtSearchNo.Text.Trim()))
                {
                    trustLists = (from x in Funs.DB.HJGL_Hard_Trust where x.HardTrustNo.Contains(this.txtSearchNo.Text.Trim()) && x.InstallationId == node.NodeID.Split('|')[2] && x.HardTrustUnit == node.NodeID.Split('|')[1] && x.WorkAreaId == node.NodeID.Split('|')[0] orderby x.HardTrustNo select x).ToList();
                }
                else
                {
                    trustLists = (from x in Funs.DB.HJGL_Hard_Trust where x.InstallationId == node.NodeID.Split('|')[2] && x.HardTrustUnit == node.NodeID.Split('|')[1] && x.WorkAreaId == node.NodeID.Split('|')[0] orderby x.HardTrustNo select x).ToList();
                }
                foreach (var item in trustLists)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = item.HardTrustNo;
                    newNode.NodeID = item.HardTrustID;
                    newNode.ToolTip = item.HardTrustNo;
                    newNode.CommandName = "委托单号";
                    newNode.EnableClickEvent = true;
                    node.Nodes.Add(newNode);
                }
            }
        }
        #endregion
        #region 点击TreeView
        /// 
        /// 点击TreeView
        /// 
        /// 
        /// 
        protected void tvControlItem_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            this.HardTrustID = tvControlItem.SelectedNodeID;
            this.BindGrid();
        }
        #endregion
        #region 数据绑定
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        /// 
        /// 数据绑定
        /// 
        private void BindGrid()
        {
            this.SetTextTemp();
            this.PageInfoLoad(); ///页面输入提交信息
            string strSql = string.Empty;
            List listStr = new List();
            if (this.tvControlItem.SelectedNode != null && this.tvControlItem.SelectedNode.CommandName == "委托单号")
            {
                strSql = @"SELECT * ,(CASE WHEN IsPass=1 THEN '合格' WHEN IsPass=0 THEN '不合格' WHEN IsPass IS NULL THEN '待检测' END) AS checkResult
                           FROM dbo.View_HJGL_Hard_TrustItem
                           WHERE HardTrustID=@HardTrustID";
                listStr.Add(new SqlParameter("@HardTrustID", this.HardTrustID));
            }
            if (!string.IsNullOrEmpty(this.txtISO_IsoNo.Text.Trim()))
            {
                strSql += @" and ISO_IsoNo like @ISO_IsoNo ";
                listStr.Add(new SqlParameter("@ISO_IsoNo", "%" + this.txtISO_IsoNo.Text.Trim() + "%"));
            }
            if (!string.IsNullOrEmpty(this.txtJOT_JointNo.Text.Trim()))
            {
                strSql += @" and JOT_JointNo like @JOT_JointNo ";
                listStr.Add(new SqlParameter("@JOT_JointNo", "%" + this.txtJOT_JointNo.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();
        }
        #region 加载页面输入提交信息
        /// 
        /// 加载页面输入提交信息
        /// 
        private void PageInfoLoad()
        {
            this.SimpleForm1.Reset(); ///重置所有字段
            var trust = Funs.DB.View_HJGL_Hard_Trust.FirstOrDefault(x => x.HardTrustID == this.HardTrustID);
            if (trust != null)
            {
                this.txtHardnessMethod.Text = trust.HardnessMethod;
                this.txtInspectionNum.Text = trust.InspectionNum;
                this.txtEquipmentModel.Text = trust.EquipmentModel;
            }
        }
        #endregion
        /// 
        /// 情况
        /// 
        private void SetTextTemp()
        {
            this.txtHardnessMethod.Text = string.Empty;
            this.txtInspectionNum.Text = string.Empty;
            this.txtEquipmentModel.Text = string.Empty;
        }
        #endregion
        #region 分页排序
        #region 页索引改变事件
        /// 
        /// 页索引改变事件
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 排序
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 分页选择下拉改变事件
        /// 
        /// 分页选择下拉改变事件
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        #endregion
        #endregion
        #region 关闭弹出窗口及刷新页面
        /// 
        /// 关闭弹出窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            this.HardTrustID = this.hdHardTrustID.Text;
            this.BindGrid();
            //this.InitTreeMenu();
            this.hdHardTrustID.Text = string.Empty;
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void Tree_TextChanged(object sender, EventArgs e)
        {
            this.InitTreeMenu();
            //this.BindGrid();
        }
        #endregion
        protected void btnMenuModify_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_HotHardReportMenuId, Const.BtnSave))
            {
                var trust = Funs.DB.View_HJGL_Hard_Trust.FirstOrDefault(x => x.HardTrustID == tvControlItem.SelectedNodeID);
                if (trust != null)
                {
                    string window = String.Format("HardReportEdit.aspx?HardTrustID={0}", trust.HardTrustID, "编辑 - ");
                    PageContext.RegisterStartupScript(Window1.GetShowReference(window));
                }
                else
                {
                    ShowNotify("请选择要修改的硬度委托记录!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        protected void btnPrinter_Click(object sender, EventArgs e)
        {
            var trust = BLL.Hard_TrustService.GetHardTrustById(this.tvControlItem.SelectedNodeID);
            if (trust != null) {
                var hardReportItems = from x in Funs.DB.HJGL_Hard_Report 
                                          join y in Funs.DB.HJGL_Hard_TrustItem on x.HardTrustItemID equals y.HardTrustItemID
                                          where y.HardTrustID == this.tvControlItem.SelectedNodeID
                                          select x;
                var jotIdItems = (from x in hardReportItems
                                      join y in Funs.DB.HJGL_WeldJoint on x.WeldJointId equals y.WeldJointId
                                      select new { x.WeldJointId }).Distinct();
                int i = 1;
                foreach (var jotIds in jotIdItems)
                {
                    var items = from x in hardReportItems where x.WeldJointId ==jotIds.WeldJointId  select x;
                    foreach (var item in items)
                    {
                        item.Flag= i;
                        BLL.Hard_ReportService.UpdateHard_Report(item);
                    }
                    if (i == 1 || i == 2)
                    {
                        i++;
                    }
                    else
                    {
                        i = 1;
                    }
                }
                if (string.IsNullOrEmpty(trust.InspectionNum))
                {
                    ShowNotify("请先完善硬度报告信息,保存报告编号", MessageBoxIcon.Warning);
                    return;
                }
                List listStr = new List();
                listStr.Add(new SqlParameter("@HardTrustID", this.tvControlItem.SelectedNodeID));
                listStr.Add(new SqlParameter("@Flag", "0"));
                SqlParameter[] parameter = listStr.ToArray();
                DataTable tb = BLL.SQLHelper.GetDataTableRunProc("HJGL_SP_HardReportItem", parameter);
                string varValue = Funs.GetPagesCountByPageSize(18, 24, tb.Rows.Count).ToString();
                if (!string.IsNullOrEmpty(varValue))
                {
                    varValue = HttpUtility.UrlEncodeUnicode(varValue);
                }
                if (tb.Rows.Count <= 18)
                {
                    PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("../../ReportPrint/ExReportPrint.aspx?ispop=1&reportId={0}&replaceParameter={1}&varValue={2}&projectId=0", BLL.Const.HJGL_HardTestReportId, this.tvControlItem.SelectedNodeID, varValue, "打印 - ")));
                }
                else
                {
                    PageContext.RegisterStartupScript(Window3.GetShowReference(String.Format("../../ReportPrint/ExReportPrint.aspx?ispop=1&reportId={0}&replaceParameter={1}&varValue={2}&projectId=0", Const.HJGL_HardTestReportId2, this.tvControlItem.SelectedNodeID, varValue, "打印 - ")));
                    PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("../../ReportPrint/ExReportPrint.aspx?ispop=1&reportId={0}&replaceParameter={1}&varValue={2}&projectId=0", Const.HJGL_HardTestReportId, this.tvControlItem.SelectedNodeID, varValue, "打印 - ")));
                }
            }
            else
            {
                ShowNotify("请选择委托单!", MessageBoxIcon.Warning);
                return;
            }
        }
        protected void WindowHardReport_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
        }
    }
}