using System;
using System.Collections.Generic;
using System.Linq;
using BLL;
using System.Data.SqlClient;
using System.Data;
using System.IO;
namespace FineUIPro.Web.HJGL.HotProcessHard
{
    public partial class HotProessTrust : PageBase
    {
        #region 定义项
        /// 
        /// 热处理委托主键
        /// 
        public string HotProessTrustId
        {
            get
            {
                return (string)ViewState["HotProessTrustId"];
            }
            set
            {
                ViewState["HotProessTrustId"] = value;
            }
        }
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();
                this.ddlPageSize.SelectedValue = this.Grid1.PageSize.ToString();
                this.HotProessTrustId = string.Empty;
                this.InitTreeMenu();//加载树
            }
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            if (Request.Params["value"] == "0")
            {
                return;
            }
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.HJGL_HotProessTrustMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnNew.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnSave))
                {
                    this.btnEdit.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnDelete.Hidden = false;
                }
            }
        }
        #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_HotProess_Trust where x.HotProessTrustNo.Contains(this.txtSearchNo.Text.Trim()) && x.InstallationId == node.NodeID.Split('|')[2] && x.UnitId == node.NodeID.Split('|')[1] && x.WorkAreaId == node.NodeID.Split('|')[0] orderby x.HotProessTrustNo select x).ToList();
                }
                else
                {
                    trustLists = (from x in Funs.DB.HJGL_HotProess_Trust where x.InstallationId == node.NodeID.Split('|')[2] && x.UnitId == node.NodeID.Split('|')[1] && x.WorkAreaId == node.NodeID.Split('|')[0] orderby x.HotProessTrustNo select x).ToList();
                }
                foreach (var item in trustLists)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = item.HotProessTrustNo;
                    newNode.NodeID = item.HotProessTrustId;
                    newNode.ToolTip = item.HotProessTrustNo;
                    newNode.CommandName = "委托单号";
                    newNode.EnableClickEvent = true;
                    node.Nodes.Add(newNode);
                }
            }
        }
        #endregion
        #region 点击TreeView
        /// 
        /// 点击TreeView
        /// 
        /// 
        /// 
        protected void tvControlItem_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.HJGL_HotProessTrustMenuId);
             if (this.tvControlItem.SelectedNode.CommandName == "委托单号")
            {
                if (buttonList.Contains(BLL.Const.BtnSave))
                {
                    this.btnNew.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnSave))
                {
                    this.btnEdit.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnDelete.Hidden = false;
                }
            }
            this.BindGrid();
        }
        #endregion
        #region DropDownList下拉选择事件
        /// 
        /// 项目下拉选择事件
        /// 
        /// 
        /// 
        protected void drpProjectId_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.InitTreeMenu();
        }
        #endregion
        #region 数据绑定
        /// 
        /// 数据绑定
        /// 
        private void BindGrid()
        {
            string strSql = string.Empty;
            List listStr = new List();
            this.SetTextTemp();
            if (this.tvControlItem.SelectedNode != null && this.tvControlItem.SelectedNode.CommandName == "委托单号")
            {
                var hotProessTrust = BLL.HotProess_TrustService.GetHotProessTrustById(this.tvControlItem.SelectedNodeID);
                if (hotProessTrust != null)
                {
                    this.HotProessTrustId = hotProessTrust.HotProessTrustId;
                    strSql = @"SELECT * "
                    + @" FROM dbo.View_HJGL_HotProess_TrustItem AS Trust"
                    + @" WHERE Trust.ProjectId= @ProjectId AND Trust.HotProessTrustId=@HotProessTrustId ";
                    listStr.Add(new SqlParameter("@ProjectId", hotProessTrust != null ? hotProessTrust.ProjectId : this.CurrUser.LoginProjectId));
                    listStr.Add(new SqlParameter("@HotProessTrustId", this.HotProessTrustId));
                    if (!string.IsNullOrEmpty(this.txtIsoNo.Text.Trim()))
                    {
                        strSql += @" and Trust.ISO_IsoNo like '%'+@ISO_IsoNo+'%' ";
                        listStr.Add(new SqlParameter("@ISO_IsoNo", this.txtIsoNo.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();
                    //// 是否合格、是否需硬度检测的绑定
                    //for (int i = 0; i < this.Grid1.Rows.Count; i++)
                    //{
                    //    string hotProessTrustItemId = this.Grid1.Rows[i].DataKeys[0].ToString();
                    //    if (hotProessTrustItemId != null)
                    //    {
                    //        var hotProessFeedback = BLL.HotProessTrustItemService.GetHotProessTrustItemById(hotProessTrustItemId);
                    //        if (hotProessFeedback.IsCompleted == true)
                    //        {
                    //            this.Grid1.Rows[i].Values[6] = BLL.Const._True;//是否完成
                    //        }
                    //    }
                    //}
                }
            }
            this.PageInfoLoad(); ///页面输入提交信息
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        #region 加载页面输入提交信息
        /// 
        /// 加载页面输入提交信息
        /// 
        private void PageInfoLoad()
        {
            var trust = BLL.HotProess_TrustService.GetHotProessTrustById(this.HotProessTrustId);
            if (trust != null)
            {
                this.txtHotProessTrustNo.Text = trust.HotProessTrustNo;
                if (trust.ProessDate.HasValue)
                {
                    this.txtProessDate.Text = string.Format("{0:yyyy-MM-dd}", trust.ProessDate);
                }
                if (!string.IsNullOrEmpty(trust.Tabler))
                {
                    this.txtTabler.Text = BLL.UserService.GetUserNameByUserId(trust.Tabler);
                }
                this.txtRemark.Text = trust.Remark;
            }
        }
        #endregion
        #region 清空文本
        /// 
        /// 清空文本
        /// 
        private void SetTextTemp()
        {
            this.txtHotProessTrustNo.Text = string.Empty;
            this.txtProessDate.Text = string.Empty;
            this.txtTabler.Text = string.Empty;
            this.txtRemark.Text = string.Empty;
        }
        #endregion
        #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 btnNew_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_HotProessTrustMenuId, Const.BtnAdd))
            {
                if (this.tvControlItem.SelectedNode != null && this.tvControlItem.SelectedNode.ToolTip == "区域")
                {
                    this.SetTextTemp();
                    string window = String.Format("HotProessTrustEdit.aspx?WorkAreaId={0}&UnitId={1}&InstallationId={2}", tvControlItem.SelectedNodeID.Split('|')[0], tvControlItem.SelectedNodeID.Split('|')[1], tvControlItem.SelectedNodeID.Split('|')[2], "新增 - ");
                    PageContext.RegisterStartupScript(Window1.GetSaveStateReference(this.hdHotProessTrustId.ClientID)
                      + Window1.GetShowReference(window));
                }
                else
                {
                    ShowNotify("请选择区域!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #region 编辑热处理委托
        /// 
        /// 编辑热处理委托
        /// 
        /// 
        /// 
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_HotProessTrustMenuId, Const.BtnSave))
            {
                var trustManage = BLL.HotProess_TrustService.GetHotProessTrustById(this.HotProessTrustId);
                if (trustManage != null)
                {
                    string window = String.Format("HotProessTrustEdit.aspx?HotProessTrustId={0}", this.HotProessTrustId, "编辑 - ");
                    PageContext.RegisterStartupScript(Window1.GetSaveStateReference(this.hdHotProessTrustId.ClientID)
                      + Window1.GetShowReference(window));
                }
                else
                {
                    ShowNotify("请选择要修改的热处理委托记录!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 删除热处理委托
        /// 
        /// 删除热处理委托
        /// 
        /// 
        /// 
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_HotProessTrustMenuId, Const.BtnDelete))
            {
                var trustManage = BLL.HotProess_TrustService.GetHotProessTrustById(this.HotProessTrustId);
                if (trustManage != null)
                {
                    var hotProessItems = from x in Funs.DB.HJGL_HotProess_TrustItem where x.HotProessTrustId == this.HotProessTrustId select x;
                    foreach (var item in hotProessItems)
                    {
                        if (item.IsCompleted != null)
                        {
                            ShowNotify("已生成热处理报告,不能删除!", MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    BLL.HotProessTrustItemService.DeleteHotProessTrustItemById(this.HotProessTrustId);
                    BLL.HotProess_TrustService.DeleteHotProessTrustById(this.HotProessTrustId);
                    //BLL.Sys_LogService.AddLog(BLL.Const.System_3, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Resources.Lan.DeleteHotProess);
                    Alert.ShowInTop("删除成功!", MessageBoxIcon.Success);
                    this.InitTreeMenu();
                    SetTextTemp();
                    this.Grid1.DataSource = null;
                    this.Grid1.DataBind();
                }
                else
                {
                    ShowNotify("请选择要删除的热处理委托记录!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #endregion
        #region 关闭弹出窗口及刷新页面
        /// 
        /// 关闭弹出窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            this.InitTreeMenu();
            this.HotProessTrustId = this.hdHotProessTrustId.Text;
            this.tvControlItem.SelectedNodeID = this.HotProessTrustId;
            this.BindGrid();
            this.hdHotProessTrustId.Text = string.Empty;
        }
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void Tree_TextChanged(object sender, EventArgs e)
        {
            this.InitTreeMenu();
        }
        #endregion
        #endregion
        #region 右键编辑热处理报告
        /// 
        /// 热处理报告
        /// 
        /// 
        /// 
        protected void btnMenuHotProessReport_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.HJGL_HotProessTrustMenuId, Const.BtnSave))
            {
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("HotProessReport.aspx?HotProessTrustItemId={0}", this.Grid1.SelectedRowID, "编辑热处理报告 - ")));
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        /// 
        /// 打印
        /// 
        /// 
        /// 
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            
            DataTable dt = new DataTable("Table1");
            dt.Columns.Add("ProjectName", typeof(String));
            dt.Columns.Add("WorkAreaName", typeof(String));  
            dt.Columns.Add("HotProessTrustNo", typeof(String)); 
            dt.Columns.Add("CH_TrustMan", typeof(String)); 
            dt.Columns.Add("WorkAreaCode", typeof(String)); 
            dt.Columns.Add("JoinNum", typeof(String)); 
            DataRow dr = dt.NewRow();
            if (string.IsNullOrEmpty(this.HotProessTrustId))
            {
                Alert.ShowInTop("请选择要打印的委托单!", MessageBoxIcon.Warning);
                return;
            }
            var hotProessTrust = BLL.HotProess_TrustService.GetHotProessTrustById(HotProessTrustId);
            if (hotProessTrust != null)
            {
                string varValue = string.Empty;
                var projectName = BLL.ProjectService.GetProjectNameByProjectId(this.CurrUser.LoginProjectId);
                var installation = BLL.Project_InstallationService.GetInstallationByInstallationId(hotProessTrust.InstallationId);
                var PworkArea = Funs.DB.ProjectData_WorkArea.FirstOrDefault(x => x.WorkAreaId == hotProessTrust.WorkAreaId);
                if (PworkArea != null)
                {
                    //var cel = recordSheet.GetRow(3).CreateCell(1);
                    //cel.SetCellValue(PworkArea.WorkAreaCode);
                    //cel.CellStyle = styleCenter;
                    dr["WorkAreaName"] = PworkArea.WorkAreaName;
                    dr["WorkAreaCode"] = PworkArea.WorkAreaCode;
                }
                dr["ProjectName"] = projectName;
                dr["HotProessTrustNo"] = hotProessTrust.HotProessTrustNo;
              string  strSql = @"SELECT ISO_IsoNo,JOT_JointNo,JOT_JointDesc,MaterialCode,JOT_Sch   
                                   FROM dbo.View_HJGL_HotProess_TrustItem AS Trust 
                                   WHERE Trust.HotProessTrustId=@HotProessTrustId ";
                List listStr = new List();
                listStr.Add(new SqlParameter("@ProjectId", hotProessTrust != null ? hotProessTrust.ProjectId : this.CurrUser.LoginProjectId));
                listStr.Add(new SqlParameter("@HotProessTrustId", this.HotProessTrustId));
                
                SqlParameter[] parameter = listStr.ToArray();
                DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
                
                if (tb != null)
                {
                    tb.TableName = "data";
                    dr["JoinNum"] = tb.Rows.Count.ToString();
                }
                dt.Rows.Add(dr);
                Dictionary keyValuePairs = new Dictionary();
                keyValuePairs.Add("HotProessTrustId", HotProessTrustId);
                keyValuePairs.Add("totalUnit", "中国天辰工程有限公司");
                keyValuePairs.Add("ConUnit", "");
                keyValuePairs.Add("supUnit", "");
                var ConUnit=   Funs.DB.Base_Unit.FirstOrDefault(x => x.UnitId == hotProessTrust.UnitId);
                if (ConUnit != null)
                {
                    keyValuePairs["ConUnit"]=ConUnit.UnitName;
                }
                var punit=  ProjectUnitService.GetProjectUnitListByProjectIdUnitType(this.CurrUser.LoginProjectId, Const.ProjectUnitType_3);
                if (punit.Count > 0)
                {
                    var supUnit = Funs.DB.Base_Unit.FirstOrDefault(x=>x.UnitId== punit[0].UnitId);
                    if(supUnit!=null)
                    {
                        keyValuePairs["supUnit"] = supUnit.UnitName;
                    }
                }
                BLL.Common.FastReportService.ResetData();
                BLL.Common.FastReportService.AddFastreportTable(dt);
                BLL.Common.FastReportService.AddFastreportParameter(keyValuePairs);
                
                string initTemplatePath = "";
                string rootPath = Server.MapPath("~/");
                var sysSet = Funs.DB.Project_Sys_Set.Where(x => x.ProjectId == this.CurrUser.LoginProjectId && x.SetId == "3").FirstOrDefault();
                if (sysSet != null && sysSet.IsAuto.HasValue && sysSet.IsAuto.Value)
                {
                    initTemplatePath = "File\\Fastreport\\管道焊口热处理委托单NoPic.frx";
                }
                else
                {
                    initTemplatePath = "File\\Fastreport\\管道焊口热处理委托单.frx";
                }
                 
                if (File.Exists(rootPath + initTemplatePath))
                {
                    PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("../TrustManage/Fastreport.aspx?ReportPath={0}", rootPath + initTemplatePath)));
                }
                
            }
            else
            {
                Alert.ShowInTop("请选择要打印的委托单!", MessageBoxIcon.Warning);
                return;
            }
        }
    }
}