using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.HJGL.HotProessManage
{
    public partial class HotProessManageByPipe : PageBase
    {
        #region 定义项
        /// 
        /// 热处理主键
        /// 
        public string HotProessId
        {
            get
            {
                return (string)ViewState["HotProessId"];
            }
            set
            {
                ViewState["HotProessId"] = value;
            }
        }
        /// 
        /// 管线Id
        /// 
        public string ISO_ID
        {
            get
            {
                return (string)ViewState["ISO_ID"];
            }
            set
            {
                ViewState["ISO_ID"] = value;
            }
        }
        /// 
        /// 热处理明细集合
        /// 
        private static List viewHotProessItems = new List();
        #endregion
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //单位、装置
                //if (BLL.UnitService.GetUnitByUnitId(this.CurrUser.UnitId) == null || BLL.UnitService.GetUnitByUnitId(this.CurrUser.UnitId).UnitTypeId == BLL.Const.ProjectUnitType_1)
                //{
                //    BLL.UnitService.InitUnitNameByUnitTypeDropDownList(this.drpUnit, this.CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_2, true);
                //    BLL.Project_InstallationService.InitInstallationDropDownList(this.drpInstallationId, this.CurrUser.LoginProjectId, true);
                //}
                //else
                //{
                //    BLL.UnitService.InitSubUnitNameDownList(this.drpUnit, this.CurrUser.LoginProjectId, this.CurrUser.UnitId, true);
                //    BLL.Project_InstallationService.InitInstallationListDownList(this.drpInstallationId, this.CurrUser.LoginProjectId, this.CurrUser.UnitId, true);
                //}
                var pUnit = BLL.UnitService.GetUnitByProjectIdUnitTypeList(this.CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_2);
                if (pUnit != null)
                {
                    this.drpUnit.DataTextField = "UnitName";
                    this.drpUnit.DataValueField = "UnitId";
                    this.drpUnit.DataSource = pUnit;
                    this.drpUnit.DataBind();
                    this.drpUnit.SelectedValue = this.CurrUser.UnitId;
                    BLL.Project_InstallationService.InitInstallationListDownList(this.drpInstallationId, this.CurrUser.LoginProjectId, this.drpUnit.SelectedValue, true);
                    this.drpInstallationId.SelectedIndex = 0;
                }
                BLL.UserService.InitUserDropDownList(this.drpTabler, this.CurrUser.LoginProjectId, true);//制单人
                
                this.txtProessDate.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
                this.drpTabler.SelectedValue = this.CurrUser.UserId;
                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);
            List units = null;
            var unit = BLL.UnitService.GetUnitByUnitId(this.CurrUser.UnitId);
            if (unit == null || unit.UnitTypeId == BLL.Const.ProjectUnitType_1)
            {
                units = BLL.UnitService.GetUnitByProjectIdUnitTypeList(this.CurrUser.LoginProjectId, "2");
            }
            else
            {
                units = (from x in Funs.DB.Base_Unit where x.UnitId == this.CurrUser.UnitId select x).ToList();
            }
            
            List hotProessLists = new List(); ///热处理              
            hotProessLists = (from x in Funs.DB.View_HotProessTreeMenu
                              where //x.HotType == "1" && 
                              x.ProjectId == this.CurrUser.LoginProjectId //&& x.ProessDate >= startTime && x.ProessDate < endTime
                              select x).Distinct().ToList();
            if (units != null)
            {
                foreach (var item in units)
                {
                    TreeNode rootUnitNode = new TreeNode();//定义根节点
                    rootUnitNode.Text = item.UnitName;
                    rootUnitNode.NodeID = item.UnitId;
                    rootUnitNode.Expanded = true;
                    rootUnitNode.ToolTip = "施工单位";
                    rootNode.Nodes.Add(rootUnitNode);
                    var lists = hotProessLists.Where(x => x.UnitId == item.UnitId).ToList();
                    this.BindNodes(rootUnitNode, lists);
                }
            }
            else
            {
                Alert.ShowInTop("请先增加施工单位!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #region 绑定树节点
        /// 
        ///  绑定树节点
        /// 
        /// 
        private void BindNodes(TreeNode node, List hotProessLists)
        {
            if (node.ToolTip == "施工单位")
            {
                var installId = (from x in hotProessLists select x.InstallationId).Distinct();
                if (installId.Count() > 0)
                {
                    var install = from x in Funs.DB.Project_Installation where installId.Contains(x.InstallationId) orderby x.InstallationCode select x;
                    foreach (var q in install)
                    {
                        TreeNode newNode = new TreeNode();
                        newNode.Text = q.InstallationCode + q.InstallationName;
                        newNode.NodeID = q.InstallationId + "|" + node.NodeID; ;
                        newNode.ToolTip = "装置";
                        newNode.Expanded = true;
                        node.Nodes.Add(newNode);
                        this.BindNodes(newNode, hotProessLists);
                    }
                }
            }
            else if (node.ToolTip == "装置")
            {
                string installationId = Funs.GetStrListByStr(node.NodeID, '|')[0];
                var workAreaLists = (from x in Funs.DB.ProjectData_WorkArea
                                     where x.InstallationId == installationId && x.UnitId == node.ParentNode.NodeID
                                     select x).Distinct();
                foreach (var item in workAreaLists)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = item.WorkAreaCode;
                    newNode.NodeID = item.WorkAreaId + "|" + node.NodeID;
                    newNode.ToolTip = "区域";
                    node.Nodes.Add(newNode);
                    this.BindNodes(newNode, hotProessLists);
                }
            }
            else if (node.ToolTip == "区域")
            {
                string installationId = Funs.GetStrListByStr(node.ParentNode.NodeID, '|')[0];
                if (!string.IsNullOrEmpty(this.txtIsoNo.Text.Trim()))
                {
                    var hotMenus = (from x in Funs.DB.View_HotProessTreeMenu
                                    where x.InstallationId == installationId
                                    && x.UnitId == node.ParentNode.ParentNode.NodeID
                                    //&& x.HotType == "1"
                                    && x.ISO_IsoNo.Contains(this.txtIsoNo.Text.Trim())
                                    select x);
                    if (hotMenus.Count() > 0)
                    {
                        foreach (var item in hotMenus)
                        {
                            TreeNode newNode = new TreeNode();
                            newNode.Text = item.ISO_IsoNo;
                            newNode.NodeID = item.ISO_ID;
                            newNode.Expanded = true;
                            newNode.EnableClickEvent = true;
                            node.Nodes.Add(newNode);
                        }
                    }
                }
                else
                {
                    var hotMenus = (from x in Funs.DB.View_HotProessTreeMenu
                                    where x.InstallationId == installationId
                                    && x.UnitId == node.ParentNode.ParentNode.NodeID
                                    //&& x.HotType == "1"
                                    select x);
                    if (hotMenus.Count() > 0)
                    {
                        foreach (var item in hotMenus)
                        {
                            TreeNode newNode = new TreeNode();
                            newNode.Text = item.ISO_IsoNo;
                            newNode.NodeID = item.ISO_ID;
                            newNode.EnableClickEvent = true;
                            node.Nodes.Add(newNode);
                        }
                    }
                }
            }
        }
        #endregion
        #region 查询树节点
        protected void Tree_TextChanged(object sender, EventArgs e)
        {
            this.InitTreeMenu();
        }
        #endregion
        #region 点击树节点
        /// 
        /// 点击树节点
        /// 
        /// 
        /// 
        protected void tvControlItem_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            viewHotProessItems = new List();
            this.ISO_ID = this.tvControlItem.SelectedNodeID;
            if (!string.IsNullOrEmpty(this.ISO_ID))
            {
                var hotProess = BLL.HotProessManageEditService.GetViewHotProessByIsoId(this.ISO_ID);
                if (hotProess != null)
                {
                    if (!string.IsNullOrEmpty(hotProess.UnitId))
                    {
                        this.drpUnit.SelectedValue = hotProess.UnitId;
                    }
                    if (!string.IsNullOrEmpty(hotProess.InstallationId))
                    {
                        this.drpInstallationId.SelectedValue = hotProess.InstallationId;
                    }
                    this.txtHotProessNo.Text = hotProess.HotProessNo;
                    this.txtProessDate.Text = hotProess.ProessDate.HasValue ? string.Format("{0:yyyy-MM-dd}", hotProess.ProessDate) : string.Format("{0:yyyy-MM-dd}", DateTime.Now);
                    this.txtProessMethod.Text = hotProess.ProessMethod;
                    this.txtProessEquipment.Text = hotProess.ProessEquipment;
                    if (!string.IsNullOrEmpty(hotProess.Tabler))
                    {
                        this.drpTabler.SelectedValue = hotProess.Tabler;
                    }
                    else
                    {
                        this.drpTabler.SelectedValue = this.CurrUser.UserId;
                    }
                    this.txtRemark.Text = hotProess.Remark;
                    viewHotProessItems.Clear();
                    viewHotProessItems = BLL.HotProessManageEditService.GetHotProessListByIsoId(this.ISO_ID);
                    if (viewHotProessItems.Count > 0)
                    {
                        this.Grid1.DataSource = viewHotProessItems;
                        this.Grid1.DataBind();
                    }
                }
            }
            else
            {
                this.ISO_ID = string.Empty;
            }
        }
        #endregion        
        #region 增加
        /// 
        /// 增加按钮
        /// 
        /// 
        /// 
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.GetButtonPower(BLL.Const.BtnAdd))
            {
                this.drpUnit.SelectedIndex = 0;
                this.drpInstallationId.SelectedIndex = 0;
                this.txtHotProessNo.Text = string.Empty;
                this.txtProessDate.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
                this.txtProessMethod.Text = string.Empty;
                this.txtProessEquipment.Text = string.Empty;
                this.drpTabler.Text = this.CurrUser.UserId;
                this.txtRemark.Text = string.Empty;
                this.HotProessId = string.Empty;
                this.ISO_ID = string.Empty;
                viewHotProessItems.Clear();
                this.Grid1.DataSource = viewHotProessItems;
                this.Grid1.DataBind();
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 查找管线焊口
        /// 
        /// 查找
        /// 
        /// 
        /// 
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (this.GetButtonPower(BLL.Const.BtnSave))
            {
                if (this.drpUnit.SelectedValue == BLL.Const._Null || string.IsNullOrEmpty(this.drpUnit.SelectedValue))
                {
                    Alert.ShowInTop("请选择单位!", MessageBoxIcon.Warning);
                    return;
                }
                else if (this.drpInstallationId.SelectedValue == BLL.Const._Null || string.IsNullOrEmpty(this.drpInstallationId.SelectedValue))
                {
                    Alert.ShowInTop("请选择装置名称!", MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    string window = String.Format("ShowHotProessSearch.aspx?unitId={0}&&installationId={1}", this.drpUnit.SelectedValue, this.drpInstallationId.SelectedValue, "编辑 - ");
                    PageContext.RegisterStartupScript(Window1.GetSaveStateReference(this.hdJOTID.ClientID)
                      + Window1.GetShowReference(window));
                }
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 关闭弹出窗体
        /// 
        /// 关闭弹出窗体
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            viewHotProessItems = new List();
            int pointCount = int.Parse(this.drpPointCount.SelectedValue);
            List infos = Funs.GetStrListByStr(hdJOTID.Text, ',');
            foreach (var item in infos)
            {
                int count = (from x in viewHotProessItems where x.JOT_ID == item select x).Count();
                int c = pointCount - count;
                if (c > 0)
                {
                    for (int i = 0; i < c; i++)
                    {
                        Model.View_HotProessItem info = Funs.DB.View_HotProessItem.FirstOrDefault(x => x.JOT_ID == item);
                        info.PointCount = count + i + 1;
                        viewHotProessItems.Add(info);
                    }
                }
            }
            if (viewHotProessItems.Count > 0)
            {
                this.Grid1.DataSource = viewHotProessItems;
                this.Grid1.DataBind();
            }
        }
        #endregion
        #region 删除热处理
        /// 
        /// 删除
        /// 
        /// 
        /// 
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.GetButtonPower(BLL.Const.BtnDelete))
            {
                if (!string.IsNullOrEmpty(ISO_ID))
                {
                    BLL.HotProessManageEditService.DeleteHotProessItemByIsoId(ISO_ID);
                    ShowNotify("删除成功!", MessageBoxIcon.Success);
                    this.drpUnit.SelectedIndex = 0;
                    this.drpInstallationId.SelectedIndex = 0;
                    this.txtHotProessNo.Text = string.Empty;
                    this.txtProessDate.Text = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
                    this.txtProessMethod.Text = string.Empty;
                    this.txtProessEquipment.Text = string.Empty;
                    this.drpTabler.Text = this.CurrUser.UserId;
                    this.txtRemark.Text = string.Empty;
                    viewHotProessItems.Clear();
                    this.ISO_ID = null;
                    this.Grid1.DataSource = null;
                    this.Grid1.DataBind();
                }
                else
                {
                    Alert.ShowInTop("请选择要删除的热处理记录!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion     
        #region 右键删除
        /// 
        /// 右键删除
        /// 
        /// 
        /// 
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            if (this.GetButtonPower(BLL.Const.BtnDelete))
            {
                if (Grid1.SelectedRowIndexArray.Length == 0)
                {
                    Alert.ShowInTop("请选择一条记录!", MessageBoxIcon.Warning);
                    return;
                }
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    var item = viewHotProessItems.FirstOrDefault(x => x.JOT_ID == rowID);
                    if (item != null)
                    {
                        viewHotProessItems.RemoveAt(rowIndex);
                    }
                }
                Grid1.DataSource = viewHotProessItems;
                Grid1.DataBind();
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 保存热处理
        /// 
        /// 保存
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.GetButtonPower(BLL.Const.BtnSave))
            {
                if (viewHotProessItems.Count > 0)
                {
                    foreach (var item in viewHotProessItems)
                    {
                        if (item.JOT_ID == null)
                        {
                            Alert.ShowInTop("焊口不能为空!", MessageBoxIcon.Warning);
                            return;
                        }
                    }
                }
                if (this.drpUnit.SelectedValue == BLL.Const._Null || string.IsNullOrEmpty(this.drpUnit.SelectedValue))
                {
                    Alert.ShowInTop("请选择单位!", MessageBoxIcon.Warning);
                    return;
                }
                if (this.drpInstallationId.SelectedValue == BLL.Const._Null || string.IsNullOrEmpty(this.drpInstallationId.SelectedValue))
                {
                    Alert.ShowInTop("请选择装置名称!", MessageBoxIcon.Warning);
                    return;
                }
                Model.HotProess newHotProess = new Model.HotProess();
                newHotProess.ProjectId = this.CurrUser.LoginProjectId;
                newHotProess.UnitId = this.drpUnit.SelectedValue;
                newHotProess.InstallationId = this.drpInstallationId.SelectedValue;
                newHotProess.HotProessNo = this.txtHotProessNo.Text.Trim();
                newHotProess.ProessDate = Funs.GetNewDateTime(this.txtProessDate.Text.Trim());
                newHotProess.ProessMethod = this.txtProessMethod.Text.Trim();
                newHotProess.ProessEquipment = this.txtProessEquipment.Text.Trim();
                if (this.drpTabler.SelectedValue != BLL.Const._Null && !string.IsNullOrEmpty(this.drpTabler.SelectedValue))
                {
                    newHotProess.Tabler = this.drpTabler.SelectedValue;
                }
                newHotProess.Remark = this.txtRemark.Text.Trim();
                if (!string.IsNullOrEmpty(this.HotProessId))
                {
                    newHotProess.HotProessId = this.HotProessId;
                    BLL.HotProessManageEditService.UpdateHotProess(newHotProess);
                    BLL.HotProessManageEditService.DeleteHotProessItemByHotProessId(HotProessId);
                }
                else
                {
                    newHotProess.HotType = "1";
                    this.HotProessId = SQLHelper.GetNewID(typeof(Model.HotProess));
                    newHotProess.HotProessId = this.HotProessId;
                    BLL.HotProessManageEditService.AddHotProess(newHotProess);
                }
                JArray mergedData = Grid1.GetMergedData();
                foreach (JObject mergedRow in mergedData)
                {
                    string status = mergedRow.Value("status");
                    JObject values = mergedRow.Value("values");
                    string rowID = values.Value("JOT_ID").ToString();
                    var item = viewHotProessItems.FirstOrDefault(x => x.JOT_ID == rowID);
                    if (item != null)
                    {
                        item.HotProessId = this.HotProessId;
                        item.JOT_ID = rowID;
                        item.PointCount = Funs.GetNewInt(values.Value("PointCount"));
                        item.RequiredT = values.Value("RequiredT");
                        item.ActualT = values.Value("ActualT");
                        item.RequestTime = values.Value("RequestTime");
                        item.ActualTime = values.Value("ActualTime");
                        item.RecordChartNo = values.Value("RecordChartNo");
                        item.HardnessReportNo = values.Value("HardnessReportNo");
                    }
                }
                foreach (var item in viewHotProessItems)
                {
                    Model.HotProessItem newHotProessItem = new Model.HotProessItem();
                    newHotProessItem.HotProessId = this.HotProessId;
                    newHotProessItem.JOT_ID = item.JOT_ID;
                    newHotProessItem.PointCount = item.PointCount;
                    newHotProessItem.RequiredT = item.RequiredT;
                    newHotProessItem.ActualT = item.ActualT;
                    newHotProessItem.RequestTime = item.RequestTime;
                    newHotProessItem.ActualTime = item.ActualTime;
                    newHotProessItem.RecordChartNo = item.RecordChartNo;
                    newHotProessItem.HardnessReportNo = item.HardnessReportNo;
                    BLL.HotProessManageEditService.AddHotProessItem(newHotProessItem, this.txtHotProessNo.Text, this.txtProessDate.Text.Trim());
                }
                ShowNotify("保存成功!", MessageBoxIcon.Success);
                InitTreeMenu();
                viewHotProessItems.Clear();
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Warning);
            }
        }
        #endregion  
        #region DropDownList下拉选择事件
        /// 
        /// 单位下拉选择事件
        /// 
        /// 
        /// 
        protected void drpUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.drpInstallationId.Items.Clear();
            if (!string.IsNullOrEmpty(this.drpUnit.SelectedValue) && this.drpUnit.SelectedValue != BLL.Const._Null)
            {
                //if (BLL.WorkAreaService.IsSupervisor(this.CurrUser.UnitId, this.CurrUser.LoginProjectId))
                //{
                //    BLL.Project_InstallationService.InitInstallationBySupervisorUnitIdListDownList(this.drpInstallationId, this.CurrUser.LoginProjectId, this.drpUnit.SelectedValue, this.CurrUser.UnitId, true);
                //    this.drpInstallationId.SelectedIndex = 0;
                //}
                //else
                //{
                //    BLL.Project_InstallationService.InitInstallationListDownList(this.drpInstallationId, this.CurrUser.LoginProjectId, this.drpUnit.SelectedValue, true);
                //    this.drpInstallationId.SelectedIndex = 0;
                //}
                BLL.Project_InstallationService.InitInstallationListDownList(this.drpInstallationId, this.CurrUser.LoginProjectId, this.drpUnit.SelectedValue, true);
                this.drpInstallationId.SelectedIndex = 0;
                //加载编号            
                string prefixCode = string.Empty;
                var tccCode = BLL.UnitService.GetUnitCodeByUnitId(BLL.Const.UnitId_TCC);
                var unitCode = BLL.UnitService.GetUnitCodeByUnitId(this.drpUnit.SelectedValue);
                if (!string.IsNullOrEmpty(tccCode))
                {
                    prefixCode = tccCode + "-" + unitCode + "-PWHT-";
                }
                this.txtHotProessNo.Text = BLL.SQLHelper.RunProcNewId("SpGetNewCode5ByProjectId", "dbo.HotProess", "HotProessNo", this.CurrUser.LoginProjectId, prefixCode);
            }
            else
            {
                Funs.FineUIPleaseSelect(this.drpInstallationId);
            }
        }
        /// 
        /// 装置下拉选择事件
        /// 
        /// 
        /// 
        protected void drpInstallationId_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.drpUnit.SelectedValue != BLL.Const._Null && !string.IsNullOrEmpty(this.drpUnit.SelectedValue) && this.drpInstallationId.SelectedValue != BLL.Const._Null && !string.IsNullOrEmpty(this.drpInstallationId.SelectedValue))
            {
                //加载编号            
                string prefixCode = string.Empty;
                var tccCode = BLL.UnitService.GetUnitCodeByUnitId(BLL.Const.UnitId_TCC);
                var unitCode = BLL.UnitService.GetUnitCodeByUnitId(this.drpUnit.SelectedValue);
                var area = BLL.WorkAreaService.GetWorkAreaByProjectIdAndInstalltionIdAndUnitId(this.CurrUser.LoginProjectId, this.drpInstallationId.SelectedValue, this.drpUnit.SelectedValue);
                if (!string.IsNullOrEmpty(tccCode))
                {
                    prefixCode = tccCode + "-" + unitCode + "-" + area.WorkAreaCode + "-PWHT-";
                }
                this.txtHotProessNo.Text = BLL.SQLHelper.RunProcNewId("SpGetNewCode5ByProjectId", "dbo.HotProess", "HotProessNo", this.CurrUser.LoginProjectId, prefixCode);
            }
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private bool GetButtonPower(string button)
        {
            return BLL.CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.HJGL_HotProessManageByPipeMenuId, button);
        }
        #endregion
    }
}