using BLL;
using BLL.ZHGL.Question;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
namespace FineUIPro.Web.ZHGL.Question
{
    public partial class QuestionDB : PageBase
    {
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Funs.DropDownPageSize(this.ddlPageSize);
                this.GetButtonPower();
                this.InitTreeMenu();
            }
        }
        /// 
        /// 初始化树
        /// 
        private void InitTreeMenu()
        {
            tvTestTraining.Nodes.Clear();
            tvTestTraining.ShowBorder = false;
            tvTestTraining.ShowHeader = false;
            tvTestTraining.EnableIcons = true;
            tvTestTraining.AutoScroll = true;
            tvTestTraining.EnableSingleClickExpand = true;
            TreeNode rootNode = new TreeNode
            {
                Text = "问题库",
                NodeID = "0",
                Expanded = true
            };
            this.tvTestTraining.Nodes.Add(rootNode);
            BoundTree(rootNode.Nodes, rootNode.NodeID);
        }
        private void BoundTree(TreeNodeCollection nodes, string parentId)
        {
            var dt = GetNewTraining(parentId);
            if (dt.Count() > 0)
            {
                TreeNode tn = null;
                foreach (var dr in dt)
                {
                    string name = dr.QuestionDBName;                   
                    if (!string.IsNullOrEmpty(dr.QuestionDBCode))
                    {
                        name = "[" + dr.QuestionDBCode + "]" + dr.QuestionDBName;
                    }
                    tn = new TreeNode
                    {
                        Text = name,
                        NodeID = dr.QuestionDBId,
                        EnableClickEvent = true,
                        ToolTip = dr.QuestionDBName
                    };
                    nodes.Add(tn);
                    ///是否存在下级节点
                    var sup = Funs.DB.Question_QuestionDB.FirstOrDefault(x => x.SupQuestionDBId == tn.NodeID);
                    if (sup != null)
                    {
                        BoundTree(tn.Nodes, tn.NodeID);
                    }
                }
            }
        }
        /// 
        /// 得到培训类型
        /// 
        /// 
        /// 
        private List GetNewTraining(string parentId)
        {
            return (from x in Funs.DB.Question_QuestionDB
                    where x.SupQuestionDBId == parentId
                    orderby x.QuestionDBCode
                    select x).ToList();
        }
        //protected void btnNew_Click(object sender, EventArgs e)
        //{
        //    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("TrainingSave.aspx", "编辑 - ")));
        //}
        protected void btnMenuADD_Click(object sender, EventArgs e)
        {
            if (this.tvTestTraining.SelectedNode != null)
            {
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("QuestionDBSave.aspx?SupQuestionDBId={0}", this.tvTestTraining.SelectedNode.NodeID, "新增 - ")));
            }
            else
            {
                ShowNotify("请选择树节点!", MessageBoxIcon.Warning);
            }
        }
        protected void btnTreeMenuEdit_Click(object sender, EventArgs e)
        {
            if (this.tvTestTraining.SelectedNode != null)
            {
                if (this.tvTestTraining.SelectedNode.NodeID != "0")   //非根节点可以编辑
                {
                    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("QuestionDBSave.aspx?QuestionDBId={0}", this.tvTestTraining.SelectedNode.NodeID, "编辑 - ")));
                }
                else
                {
                    ShowNotify("根节点无法编辑!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("请选择树节点!", MessageBoxIcon.Warning);
            }
        }
        protected void btnTreeMenuDelete_Click(object sender, EventArgs e)
        {
            if (this.tvTestTraining.SelectedNode != null && this.tvTestTraining.SelectedNodeID != "0")
            {
                var edu = Funs.DB.Question_QuestionDB.FirstOrDefault(x => x.SupQuestionDBId == this.tvTestTraining.SelectedNode.NodeID);
                if (edu == null)
                {
                    QuestionService.DeleteQuestionDBById(this.tvTestTraining.SelectedNode.NodeID);
                    InitTreeMenu();
                    Grid1.DataSource = null;
                    Grid1.DataBind();
                }
                else
                {
                    ShowNotify("存在子目录,不能删除!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("请选择删除项!", MessageBoxIcon.Warning);
            }
        }
        protected void tvTestTraining_NodeCommand(object sender, FineUIPro.TreeCommandEventArgs e)
        {
            BindGrid();
        }
        #region BindGrid
        private void BindGrid()
        {
            if (this.tvTestTraining.SelectedNode != null && !string.IsNullOrEmpty(this.tvTestTraining.SelectedNode.NodeID))
            {
                string strSql = @"SELECT QuestionDBItemId,QuestionDBId,QuestionDBItemCode,QuestionDBItemName,Abstracts,AttachUrl,VersionNum,TestType "
                                + @" ,(CASE WHEN TestType = '1' THEN '单选题' WHEN TestType = '2' THEN '多选题' ELSE '判断题' END) AS TestTypeName "
                                + @" ,AItem,BItem,CItem,DItem,EItem,AnswerItems "
                                + @" FROM dbo.Question_QuestionDBItem"
                                + @" WHERE QuestionDBId=@QuestionDBId ";
                List listStr = new List
                {
                    new SqlParameter("@QuestionDBId", this.tvTestTraining.SelectedNode.NodeID)
                };
                if (!string.IsNullOrEmpty(this.txtName.Text.Trim()))
                {
                    strSql += " AND (QuestionDBItemCode LIKE @Name OR QuestionDBItemName LIKE @Name OR Abstracts LIKE @Name  )";
                    listStr.Add(new SqlParameter("@Name", "%" + this.txtName.Text.Trim() + "%"));
                }
                if (this.drptype.SelectedValue != "0")
                {
                    strSql += " AND TestType=@TestType";
                    listStr.Add(new SqlParameter("@TestType", this.drptype.SelectedValue));
                }
                if (this.ckIsItem.Checked)
                {
                    strSql += " AND (AItem IS NULL OR BItem IS NULL OR AItem ='' OR BItem ='')";
                }
                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();
            }
        }
        #endregion
        #region Events
        protected void Window1_Close(object sender, EventArgs e)
        {
            this.InitTreeMenu();
        }
        protected void Window2_Close(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        protected void Window3_Close(object sender, EventArgs e)
        {
            this.InitTreeMenu();
            this.BindGrid();
        }
        /// 
        /// 右键删除事件
        /// 
        /// 
        /// 
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            this.DeleteData();
        }
        /// 
        /// 删除方法
        /// 
        private void DeleteData()
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    var getD = BLL.ZHGL.Question.QuestionService.getQuestionDBItemById(rowID);
                    if (getD != null)
                    {
                        BLL.LogService.AddSys_Log(this.CurrUser, getD.QuestionDBItemCode, getD.QuestionDBItemId, BLL.Const.QuestionDBMenuId, BLL.Const.BtnDelete);
                        BLL.ZHGL.Question.QuestionService.DeleteQuestionDBItemById(rowID);                      
                    }
                }
                BindGrid();
                ShowNotify("删除数据成功!");
            }
        }
        #endregion
        #region GV排序页面
        /// 
        /// 
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            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
        /// 
        /// 编辑试题
        /// 
        /// 
        /// 
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            this.EditData();
        }
        /// 
        /// 右键编辑事件
        /// 
        /// 
        /// 
        protected void btnMenuEdit_Click(object sender, EventArgs e)
        {
            this.EditData();
        }
        /// 
        /// 编辑数据方法
        /// 
        private void EditData()
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string trainingItemId = Grid1.SelectedRowID;
            PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("QuestionDBItemSave.aspx?QuestionDBItemId={0}", trainingItemId, "编辑 - ")));
        }
        /// 
        ///  增加
        /// 
        /// 
        /// 
        protected void btnNewDetail_Click(object sender, EventArgs e)
        {            
            if (this.tvTestTraining.SelectedNode != null)
            {
                string id = this.tvTestTraining.SelectedNodeID;
                var questionDB = QuestionService.getQuestionDBById(id);
                if (questionDB != null && questionDB.IsEndLever == true)
                {
                    PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("QuestionDBItemSave.aspx?QuestionDBId={0}", this.tvTestTraining.SelectedNode.NodeID, "编辑 - ")));
                }
                else
                {
                    ShowNotify("请选择末级树节点!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("请选择树节点!", MessageBoxIcon.Warning);
            }
        }
        #region 按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.TestTrainingMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnMenuADD.Hidden = false;
                    this.btnImport.Hidden = false;
                    this.btnNewDetail.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnTreeMenuEdit.Hidden = false;
                    this.btnMenuEdit.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnTreeMenuDelete.Hidden = false;
                    this.btnMenuDelete.Hidden = false;
                }
            }
            //if (this.CurrUser.UserId == BLL.Const.sysglyId)
            //{
            //    this.btnRefresh.Hidden = false;
            //    this.btnRefresh1.Hidden = false;
            //}
        }
        #endregion
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        #region 导入
        /// 
        /// 导入按钮
        /// 
        /// 
        /// 
        protected void btnImport_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window3.GetShowReference(String.Format("QuestionDBItemIn.aspx", "导入 - ")));
        }
        #endregion
        #region 导出
        /// 
        /// 导出按钮
        /// 
        /// 
        /// 
        protected void btnMenuOut_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window3.GetShowReference(String.Format("QuestionDBOut.aspx", "导出 - ")));
        }
        /// 
        /// 导出按钮
        /// 
        /// 
        /// 
        protected void btnMenuOut1_Click(object sender, EventArgs e)
        {
            if (this.tvTestTraining.SelectedNode != null && this.tvTestTraining.SelectedNodeID != "0")
            {
                Response.ClearContent();
                string filename = Funs.GetNewFileName();
                Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("问题试题" + filename, System.Text.Encoding.UTF8) + ".xls");
                Response.ContentType = "application/excel";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                this.Grid1.PageSize = Grid1.RecordCount;
                BindGrid();
                Response.Write(GetGridTableHtml(Grid1));
                Response.End();
            }
            else
            {
                ShowNotify("请选择树节点!", MessageBoxIcon.Warning);
            }
        }
        #endregion
          
        /// 
        /// 显示选项不全的题目
        /// 
        /// 
        /// 
        protected void ckIsItem_CheckedChanged(object sender, CheckedEventArgs e)
        {
            this.BindGrid();
        }
    }
}