using BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace FineUIPro.Web.TestRun
{
    public partial class DriverScheme : PageBase
    {
        #region 加载页面
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();
                InitTree();//加载类别树
            }
        }
        #region 绑定方案类别
        /// 
        /// 绑定方案树节点
        /// 
        private void InitTree()
        {
            this.tvDataTypeInit.Nodes.Clear();
            TreeNode node = new TreeNode();
            node.Text = "开车方案管理";
            node.NodeID = "0";
            node.Expanded = true;
            this.tvDataTypeInit.Nodes.Add(node);
            var types = BLL.TestRunConstructSolutionService.GetSolutionType();
            foreach (var q in types)
            {
                TreeNode newNode = new TreeNode();
                newNode.ToolTip = q.Text;
                newNode.Text = q.Text;
                newNode.NodeID = q.Value;
                newNode.EnableExpandEvent = true;
                newNode.EnableClickEvent = true;
                node.Nodes.Add(newNode);
            }
        }
        /// 
        /// 展开树
        /// 
        /// 
        /// 
        //protected void trWBS_NodeExpand(object sender, TreeNodeEventArgs e)
        //{
        //    e.Node.Nodes.Clear();
        //    var types = from x in Funs.DB.DriverPrepare_DriverDataType
        //                where x.ProjectId == this.CurrUser.LoginProjectId && x.ParentId == e.Node.NodeID
        //                select x;
        //    if (types.Count() > 0)
        //    {
        //        foreach (var type in types)
        //        {
        //            TreeNode newNode = new TreeNode();
        //            newNode.ToolTip = type.DriverDataTypeName;
        //            newNode.Text = type.DriverDataTypeName;
        //            newNode.NodeID = type.DriverDataTypeId;
        //            newNode.EnableExpandEvent = true;
        //            newNode.EnableClickEvent = true;
        //            e.Node.Nodes.Add(newNode);
        //            var childTypes = from x in Funs.DB.DriverPrepare_DriverDataType where x.ParentId == type.DriverDataTypeId select x;
        //            if (childTypes.Count() > 0)
        //            {
        //                TreeNode temp = new TreeNode();
        //                temp.Text = "";
        //                temp.NodeID = "";
        //                newNode.Nodes.Add(temp);
        //            }
        //        }
        //    }
        //}
        #endregion
        #endregion
        #region 树点击事件
        /// 
        /// 资料库类别树点击事件
        /// 
        /// 
        /// 
        protected void tvDataTypeInit_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 数据绑定
        /// 
        /// 数据绑定
        /// 
        public void BindGrid()
        {
            string strSql = @"SELECT chec.ConstructSolutionId,chec.ProjectId,chec.UnitId,chec.UnitWorkIds,chec.CNProfessionalCodes,"
                              + @" chec.CompileMan,chec.CompileDate,chec.code,chec.state,chec.SolutionType,chec.SolutionName,"
                              + @" unit.UnitName,u.userName as CompileManName,chec.SpecialSchemeTypeId,chec.System,"
                              + @" t.SpecialSchemeTypeName"
                              + @" FROM Solution_TestRunConstructSolution chec "
                              + @" left join Base_Unit unit on unit.unitId=chec.UnitId "
                              + @" left join sys_User u on u.userId = chec.CompileMan"
                              + @" left join[dbo].[Base_SpecialSchemeType] t on chec.SpecialSchemeTypeId=t.SpecialSchemeTypeId"
                              + @" where chec.ProjectId=@ProjectId and chec.SolutionType=@SolutionType";
            List listStr = new List();
            listStr.Add(new SqlParameter("@projectId", this.CurrUser.LoginProjectId));
            listStr.Add(new SqlParameter("@SolutionType", this.tvDataTypeInit.SelectedNodeID));
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = tb.Rows.Count;
            //var CNProfessional = CNProfessionalService.GetList();
            //var uniWork = UnitWorkService.GetUnitWorkLists(CurrUser.LoginProjectId);
            //if (tb.Rows.Count > 0)
            //{
            //    for (int i = 0; i < tb.Rows.Count; i++)
            //    {
            //        if (tb.Rows[i]["CNProfessionalCodes"] != null)
            //        {
            //            var code = tb.Rows[i]["CNProfessionalCodes"].ToString().Split(',');
            //            var listf = CNProfessional.Where(p => code.Contains(p.CNProfessionalId)).Select(p => p.ProfessionalName).ToArray();
            //            tb.Rows[i]["CNProfessionalCodes"] = string.Join(",", listf);
            //        }
            //        if (tb.Rows[i]["UnitWorkIds"] != null)
            //        {
            //            var code = tb.Rows[i]["UnitWorkIds"].ToString().Split(',');
            //            var workid = uniWork.Where(p => code.Contains(p.UnitWorkId)).Select(p => p.UnitWorkName + BLL.UnitWorkService.GetProjectType(p.ProjectType)).ToArray();
            //            tb.Rows[i]["UnitWorkIds"] = string.Join(",", workid);
            //        }
            //    }
            //}
            tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
            if (this.tvDataTypeInit.SelectedNodeID.Length > 1)
            {
                if (this.tvDataTypeInit.SelectedNodeID == "12")
                {
                    this.Grid1.Columns[4].Hidden = true;
                    this.Grid1.Columns[5].Hidden = true;
                }
                else
                {
                    this.Grid1.Columns[4].Hidden = false;
                    this.Grid1.Columns[5].Hidden = false;
                }
            }
        }
        #endregion
        #region 分页
        /// 
        /// 分页索引事件
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }
        /// 
        /// 分页下拉框事件
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, FineUIPro.GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }
        #endregion
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        ///  
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 关闭弹出窗口
        /// 
        /// 关闭弹出窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            InitTree();
            BindGrid();
        }
        #endregion
        #region 增加按钮
        /// 
        /// 增加
        /// 
        /// 
        /// 
        protected void btnNew_Click(object sender, EventArgs e)
        {
            if (this.tvDataTypeInit.SelectedNode != null)
            {
                //if (this.trWBS.SelectedNode.Nodes.Count == 0)   //末级节点
                if (this.tvDataTypeInit.SelectedNodeID != "0")
                {
                    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("DriverSchemeEdit.aspx?SolutionType={0}", this.tvDataTypeInit.SelectedNode.NodeID, "新增 - ")));
                }
                else
                {
                    Alert.ShowInTop("请选择方案类别!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                Alert.ShowInTop("请选择树节点!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 编辑
        protected void btnMenuModify_Click(object sender, EventArgs e)
        {
            EditData();
        }
        /// 
        /// Grid行双击事件
        /// 
        /// 
        /// 
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            EditData();
        }
        /// 
        /// 编辑
        /// 
        private void EditData()
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string id = Grid1.SelectedRowID.Split(',')[0];
            Model.Solution_TestRunConstructSolution constructSolution = TestRunConstructSolutionService.GetConstructSolutionByConstructSolutionId(id);
            if (constructSolution.State == Const.TestRunConstructSolution_Complete)
            {
                Alert.ShowInTop("该方案已经发布,无法操作,请右键查看!", MessageBoxIcon.Warning);
                return;
            }
            else if (constructSolution.State == Const.TestRunConstructSolution_Compile)
            {
                if (constructSolution.CompileMan == CurrUser.UserId || CurrUser.UserId == Const.sysglyId)
                {
                    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("DriverSchemeEdit.aspx?constructSolutionId={0}", id)));
                }
                else
                {
                    Alert.ShowInTop("您不是编制人,无法操作!请右键查看", MessageBoxIcon.Warning);
                    return;
                }
            }
            else if (constructSolution.State == Const.TestRunConstructSolution_Audit || constructSolution.State == Const.TestRunConstructSolution_ReCompile || constructSolution.State == Const.TestRunConstructSolution_Audit2)
            {
                var approve = TestRunConstructSolutionApproveService.GetThisApproveByConstructSolutionId(id);
                if (approve != null && approve.ApproveMan == this.CurrUser.UserId)
                {
                    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("DriverSchemeEdit.aspx?constructSolutionId={0}", id)));
                }
                else
                {
                    Alert.ShowInTop("您不是办理用户,无法操作!请右键查看", MessageBoxIcon.Warning);
                    return;
                }
            }
        }
        protected void btnMenuView_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string id = Grid1.SelectedRowID.Split(',')[0];
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("DriverSchemeView.aspx?constructSolutionId={0}", id)));
        }
        #endregion
        #region 删除
        /// 
        /// 右键删除
        /// 
        /// 
        /// 
        protected void btnMenuDel_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string id = Grid1.SelectedRowID.Split(',')[0];
            if (CommonService.GetAllButtonPowerList(CurrUser.LoginProjectId, CurrUser.UserId, Const.TestRunConstructSolutionMenuId, Const.BtnDelete))
            {
                var constructSolution = TestRunConstructSolutionService.GetConstructSolutionByConstructSolutionId(id);
                if (constructSolution.State == Const.TestRunConstructSolution_ReCompile || constructSolution.State == Const.TestRunConstructSolution_Compile)
                {
                    if (constructSolution.CompileMan == this.CurrUser.UserId || this.CurrUser.UserId == Const.hfnbdId || this.CurrUser.UserId == Const.sysglyId)
                    {
                        TestRunConstructSolutionApproveService.DeleteConstructSolutionApprovesByConstructSolutionId(id);
                        TestRunConstructSolutionService.DeleteConstructSolution(id);
                        LogService.AddSys_Log(CurrUser, constructSolution.Code, id, Const.TestRunConstructSolutionMenuId, "删除方案审查");
                        BindGrid();
                        Alert.ShowInTop("删除成功!", MessageBoxIcon.Success);
                    }
                    else
                    {
                        Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Success);
                    }
                }
                else
                {
                    if (this.CurrUser.UserId == Const.hfnbdId || this.CurrUser.UserId == Const.sysglyId)
                    {
                        TestRunConstructSolutionApproveService.DeleteConstructSolutionApprovesByConstructSolutionId(id);
                        TestRunConstructSolutionService.DeleteConstructSolution(id);
                        LogService.AddSys_Log(CurrUser, constructSolution.Code, id, Const.TestRunConstructSolutionMenuId, "删除方案审查");
                        BindGrid();
                        Alert.ShowInTop("删除成功!", MessageBoxIcon.Success);
                        return;
                    }
                    Alert.ShowInTop("删除失败,方案正在审批中!", MessageBoxIcon.Success);
                }
            }
            else
            {
                Alert.ShowInTop("您没有这个权限,请与管理员联系!", MessageBoxIcon.Success);
            }
        }
        #endregion
        #region Grid行点击事件
        /// 
        /// Grid行点击事件
        /// 
        /// 
        /// 
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string id = Grid1.DataKeys[e.RowIndex][0].ToString();
            if (e.CommandName == "AttachUrl")
            {
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../../AttachFile/webuploader.aspx?type=-1&toKeyId={0}&path=FileUpload/TestRun/DriverPrepare/DriverData&menuId={1}", id, BLL.Const.TestRunConstructSolutionMenuId)));
            }
        }
        #endregion
        #region 权限设置
        /// 
        /// 权限设置
        /// 
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.TestRunConstructSolutionMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnNew.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnMenuModify.Hidden = false;
                    this.Grid1.EnableRowDoubleClickEvent = true;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnMenuDel.Hidden = false;
                }
            }
        }
        #endregion
    }
}