using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.TestRun.BeforeTestRun
{
    public partial class FourDecisionOtherConfirm : PageBase
    {
        /// 
        /// 子系统主键
        /// 
        public string SsubSystemId
        {
            get { return (string)ViewState["SsubSystemId"]; }
            set { ViewState["SsubSystemId"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //加载树
                this.InitTreeMenu();
            }
        }
        /// 
        /// 加载树
        /// 
        private void InitTreeMenu()
        {
            this.tvControlItem.Nodes.Clear();
            TreeNode rootNode = new TreeNode();
            rootNode.Text = "人员确认";
            rootNode.NodeID = "0";
            rootNode.Expanded = true;
            rootNode.ToolTip = "";
            rootNode.EnableClickEvent = true;
            this.tvControlItem.Nodes.Add(rootNode);
            var decisions = Funs.DB.PreRun_SubThreeChecksFourDecision.Where(x => x.ProjectId == this.CurrUser.LoginProjectId && x.ProposeConfirm == 2 && (x.GeneraUser == this.CurrUser.UserId || x.SupervisionUser == this.CurrUser.UserId || x.OwnerUser == this.CurrUser.UserId)).ToList();
            if (decisions.Count == 0) return;
            //获取子系统主键
            var subsystemids = decisions.ConvertAll(x => x.SubSystemId);
            //根据子系统获取其他节点ID
            var userDevices = Funs.DB.PreRun_SysDevice.Where(p => p.ProjectId == this.CurrUser.LoginProjectId && subsystemids.Contains(p.PreRunId)).ToList();
            List allIds = new List();
            allIds.AddRange(userDevices.ConvertAll(x => x.ProcessesId));
            allIds.AddRange(userDevices.ConvertAll(x => x.SystemId));
            allIds.AddRange(subsystemids);
            var allPreRunLs = Funs.DB.PreRun_SysDevice.Where(p => p.ProjectId == this.CurrUser.LoginProjectId && p.PreRunLevel > 1 && allIds.Contains(p.PreRunId)).ToList();
            var onePreRunLs = allPreRunLs.Where(p => p.PreRunLevel == 2).OrderBy(x => x.Sort);
            foreach (var item in onePreRunLs)
            {
                TreeNode rootUnitNode = new TreeNode();//定义根节点
                rootUnitNode.NodeID = item.PreRunId;
                rootUnitNode.Text = item.PreRunName;
                rootUnitNode.ToolTip = item.PreRunName;
                rootUnitNode.CommandName = "";
                rootUnitNode.EnableClickEvent = false;
                rootUnitNode.EnableExpandEvent = false;
                rootNode.Nodes.Add(rootUnitNode);
                rootUnitNode.Expanded = true;
                var otherPreRunls = allPreRunLs.Where(p => p.PreRunLevel != 1).ToList();
                this.BindNodes(rootUnitNode, otherPreRunls, item.PreRunId);
            }
        }
        /// 
        ///  绑定树节点
        /// 
        private void BindNodes(TreeNode node, List list, string parentId)
        {
            var itemList = list.Where(p => p.ParentId == parentId).OrderBy(x => x.Sort).ToList();
            if (itemList.Count > 0)
            {
                foreach (var item in itemList)
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Text = item.PreRunName;
                    newNode.NodeID = item.PreRunId;
                    newNode.ToolTip = item.PreRunName;
                    newNode.CommandName = "";
                    newNode.EnableClickEvent = item.PreRunLevel == 4 ? true : false;
                    newNode.EnableExpandEvent = item.PreRunLevel == 4 ? true : false;
                    newNode.Expanded = true;
                    node.Nodes.Add(newNode);
                    BindNodes(newNode, list, item.PreRunId);
                }
            }
        }
        /// 
        /// 点击TreeView
        /// 
        /// 
        /// 
        protected void tvControlItem_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            this.SsubSystemId = tvControlItem.SelectedNodeID;
            BindGrid();
        }
        #region 绑定数据
        /// 
        /// 数据绑定
        /// 
        public void BindGrid()
        {
            string zbSql = "select NewId() as Id,a.DecisionId,a.ProjectId,a.SubSystemId,a.ResponsibilityUser,ruser.UserName as ResponsibilityUserName,a.ResponsibilityUnit,unit.UnitName as ResponsibilityUnitName,a.QuestionDesc,a.Level,a.Speciality,a.AskDestructionTime,a.RealityDestructionTime,a.RestrictCondition,a.GeneraUser as ConfirmUser,cuser.UserName as ConfirmUserName,4 as ConfirmType,'总包' as ConfirmTypeName,a.GeneraConfirm as ConfirmState,(case a.GeneraConfirm when 1 then '未确认' when 2 then '确认通过' else '' end) as ConfirmStateName,a.GeneraConfirmData as ConfirmData,a.DecisionIsClose,(case a.DecisionIsClose when 1 then '已关闭' else '未关闭' end) as DecisionIsCloseName,(case ISNULL(a.AskDestructionTime,'') when '' then 0 else DATEDIFF(DAY, GETDATE(),a.AskDestructionTime) end) as DestructionDiffDay,a.AddUser,a.AddTime,a.Sort from PreRun_SubThreeChecksFourDecision as a left join Sys_User as cuser on a.GeneraUser=cuser.UserId left join Sys_User as ruser on a.ResponsibilityUser=ruser.UserId left join Base_Unit as unit on a.ResponsibilityUnit=unit.UnitId where 1=1 and a.ProposeConfirm=2 and a.SubSystemId=@SubSystemId and a.ProjectId=@ProjectId ";
            string jlSql = "select NewId() as Id,a.DecisionId,a.ProjectId,a.SubSystemId,a.ResponsibilityUser,ruser.UserName as ResponsibilityUserName,a.ResponsibilityUnit,unit.UnitName as ResponsibilityUnitName,a.QuestionDesc,a.Level,a.Speciality,a.AskDestructionTime,a.RealityDestructionTime,a.RestrictCondition,a.SupervisionUser as ConfirmUser,cuser.UserName as ConfirmUserName,5 as ConfirmType,'监理' as ConfirmTypeName,a.SupervisionConfirm as ConfirmState,(case a.SupervisionConfirm when 1 then '未确认' when 2 then '确认通过' else '' end) as ConfirmStateName,a.SupervisionConfirmData as ConfirmData,a.DecisionIsClose,(case a.DecisionIsClose when 1 then '已关闭' else '未关闭' end) as DecisionIsCloseName,(case ISNULL(a.AskDestructionTime,'') when '' then 0 else DATEDIFF(DAY, GETDATE(),a.AskDestructionTime) end) as DestructionDiffDay,a.AddUser,a.AddTime,a.Sort from PreRun_SubThreeChecksFourDecision as a left join Sys_User as cuser on a.SupervisionUser=cuser.UserId left join Sys_User as ruser on a.ResponsibilityUser=ruser.UserId left join Base_Unit as unit on a.ResponsibilityUnit=unit.UnitId where 1=1 and a.ProposeConfirm=2 and a.SubSystemId=@SubSystemId and a.ProjectId=@ProjectId ";
            string yzSql = "select NewId() as Id,a.DecisionId,a.ProjectId,a.SubSystemId,a.ResponsibilityUser,ruser.UserName as ResponsibilityUserName,a.ResponsibilityUnit,unit.UnitName as ResponsibilityUnitName,a.QuestionDesc,a.Level,a.Speciality,a.AskDestructionTime,a.RealityDestructionTime,a.RestrictCondition,a.OwnerUser as ConfirmUser,cuser.UserName as ConfirmUserName,6 as ConfirmType,'业主' as ConfirmTypeName,a.OwnerConfirm as ConfirmState,(case a.OwnerConfirm when 1 then '未确认' when 2 then '确认通过' else '' end) as ConfirmStateName,a.OwnerConfirmData as ConfirmData,a.DecisionIsClose,(case a.DecisionIsClose when 1 then '已关闭' else '未关闭' end) as DecisionIsCloseName,(case ISNULL(a.AskDestructionTime,'') when '' then 0 else DATEDIFF(DAY, GETDATE(),a.AskDestructionTime) end) as DestructionDiffDay,a.AddUser,a.AddTime,a.Sort from PreRun_SubThreeChecksFourDecision as a left join Sys_User as cuser on a.OwnerUser=cuser.UserId left join Sys_User as ruser on a.ResponsibilityUser=ruser.UserId left join Base_Unit as unit on a.ResponsibilityUnit=unit.UnitId where 1=1 and a.ProposeConfirm=2 and a.SubSystemId=@SubSystemId and a.ProjectId=@ProjectId ";
            List listStr = new List();
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            listStr.Add(new SqlParameter("@SubSystemId", this.SsubSystemId));
            string where = string.Empty;
            //是否确认
            if (!string.IsNullOrWhiteSpace(ddlConfirmState.SelectedValue))
            {
                where = " and isnull(t.ConfirmState,1) = @ConfirmState";
                listStr.Add(new SqlParameter("@ConfirmState", ddlConfirmState.SelectedValue));
            }
            //是否关闭
            if (!string.IsNullOrWhiteSpace(ddlDecisionState.SelectedValue))
            {
                where += " and isnull(t.DecisionIsClose,0)=@DecisionIsClose";
                listStr.Add(new SqlParameter("@DecisionIsClose", ddlDecisionState.SelectedValue));
            }
            string strSql = $"select * from ({zbSql} union all {jlSql} union all {yzSql} ) as t where 1=1 {where} order by t.ConfirmType,t.AddTime desc";
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        /// 
        /// 分页
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }
        /// 
        /// 双击事件
        /// 
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            btnSubmitConfirm_Click(null, null);
        }
        /// 
        /// 分页下拉框
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        /// 
        /// 排序
        /// 
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            BindGrid();
        }
        /// 
        /// 行数据处理事件
        /// 
        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            DataRowView row = e.DataItem as DataRowView;
            int diffDay = Convert.ToInt32(row["DestructionDiffDay"]);
            TemplateField AdjustDiffDay = Grid1.FindColumn("DestructionDiffDay") as TemplateField;
            int isClose = int.Parse(Grid1.DataKeys[e.RowIndex][3].ToString());
            if (isClose != 1)
            {
                if (diffDay > 0)
                {
                    e.CellAttributes[AdjustDiffDay.ColumnIndex]["data-color"] = "color1";
                }
                else if (diffDay == 0)
                {
                    e.CellAttributes[AdjustDiffDay.ColumnIndex]["data-color"] = "color2";
                }
                else if (diffDay < 0)
                {
                    e.CellAttributes[AdjustDiffDay.ColumnIndex]["data-color"] = "color3";
                }
            }
        }
        #endregion       
        /// 
        /// 查询
        /// 
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        /// 
        /// 查看
        /// 
        protected void btnView_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string decisionId = Grid1.DataKeys[Grid1.SelectedRowIndex][0].ToString();
            string confirmType = Grid1.DataKeys[Grid1.SelectedRowIndex][2].ToString();
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("FourDecisionOtherConfirmEdit.aspx?DecisionId={0}&ConfirmType={1}&IsView=true", decisionId, confirmType, "查看 - ")));
        }
        /// 
        /// 确认
        /// 
        protected void btnSubmitConfirm_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string decisionId = Grid1.DataKeys[Grid1.SelectedRowIndex][0].ToString();
            string ConfirmState = Grid1.DataKeys[Grid1.SelectedRowIndex][1] != null ? Grid1.DataKeys[Grid1.SelectedRowIndex][1].ToString() : string.Empty;
            string confirmType = Grid1.DataKeys[Grid1.SelectedRowIndex][2].ToString();
            if (ConfirmState == "2")
            {
                Alert.ShowInTop("已确认通过,无法再次确认!", MessageBoxIcon.Warning);
                return;
            }
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("FourDecisionOtherConfirmEdit.aspx?DecisionId={0}&ConfirmType={1}", decisionId, confirmType, "确认 - ")));
        }
        /// 
        /// 确认
        /// 
        protected void btnMenuConfirm_Click(object sender, EventArgs e)
        {
            btnSubmitConfirm_Click(sender, e);
        }
        /// 
        /// 是否逾期返回
        /// 
        /// 
        public string IsOverdue(object diffDayVal, object stateVal)
        {
            var result = string.Empty;
            var diffDay = 0;
            var itemState = 0;
            if (diffDayVal != null) diffDay = int.Parse(diffDayVal.ToString());
            if (stateVal != null) itemState = int.Parse(stateVal.ToString());
            if (itemState != 1)
            {
                if (diffDay > 0)
                {
                    result = "未逾期";
                }
                else if (diffDay == 0)
                {
                    result = "即将逾期";
                }
                else if (diffDay < 0)
                {
                    result = "已逾期";
                }
            }
            else
            {
                result = "已关闭";
            }
            return result;
        }
        /// 
        /// 关闭
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
        }
    }
}