using BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
namespace FineUIPro.Web.TestRun.DriverHse
{
    public partial class HseLicense : 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.TestRunLicenseTypeService.GetTestRunLicenseTypeList();
            foreach (var q in types)
            {
                TreeNode newNode = new TreeNode();
                newNode.ToolTip = q.LicenseTypeName;
                newNode.Text = q.LicenseTypeName;
                newNode.NodeID = q.LicenseTypeId;
                newNode.EnableExpandEvent = true;
                newNode.EnableClickEvent = true;
                node.Nodes.Add(newNode);
            }
        }
        #endregion
        #endregion
        #region 树点击事件
        /// 
        /// 资料库类别树点击事件
        /// 
        /// 
        /// 
        protected void tvDataTypeInit_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 数据绑定
        /// 
        /// 数据绑定
        /// 
        public void BindGrid()
        {
            string strSql = @"SELECT driver.HseLicenseId,
                                     driver.ProjectId,
                                     driver.Code,
                                     driver.LicenseTypeId,
                                     driver.ApplyUnit,
                                     driver.ApplyMan,
                                     driver.HeaderMan,
                                     driver.WorkAddress,
                                     driver.WorkContents,
                                     driver.Remark,
                                     TestRunLicenseType.LicenseTypeName"
                           + @" FROM DriverHse_HseLicense AS driver "
                           + @" LEFT JOIN Base_TestRunLicenseType AS TestRunLicenseType ON TestRunLicenseType.LicenseTypeId = driver.LicenseTypeId WHERE driver.ProjectId=@projectId";
            List listStr = new List();
            listStr.Add(new SqlParameter("@projectId", this.CurrUser.LoginProjectId));
            if (!string.IsNullOrEmpty(this.tvDataTypeInit.SelectedNodeID))
            {
                strSql += " AND driver.LicenseTypeId=@licenseTypeId";
                listStr.Add(new SqlParameter("@licenseTypeId", this.tvDataTypeInit.SelectedNodeID));
            }
            if (!string.IsNullOrEmpty(this.txtCode.Text.Trim()))
            {
                strSql += " AND driver.Code like @code";
                listStr.Add(new SqlParameter("@code", "%" + this.txtCode.Text.Trim() + "%"));
            }
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            Grid1.RecordCount = tb.Rows.Count;
            //tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #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 btnMenuAdd_Click(object sender, EventArgs e)
        {
            //string id = this.tvDataTypeInit.SelectedNodeID;
            //if (!string.IsNullOrEmpty(id))
            //{
                PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("TestRunLicenseTypeEdit.aspx?type={1}", "add", "编辑 - ")));
            //}
        }
        /// 
        /// 修改类别
        /// 
        /// 
        /// 
        protected void btnMenuModify2_Click(object sender, EventArgs e)
        {
            string id = this.tvDataTypeInit.SelectedNodeID;
            if (!string.IsNullOrEmpty(id) && id != "0")
            {
                PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("TestRunLicenseTypeEdit.aspx?licenseTypeId={0}&type={1}", id, "edit", "编辑 - ")));
            }
            else
            {
                Alert.ShowInTop("请选择类别", MessageBoxIcon.Warning);
                return;
            }
        }
        /// 
        /// 删除类别
        /// 
        /// 
        /// 
        protected void btnMenuDel2_Click(object sender, EventArgs e)
        {
            string id = this.tvDataTypeInit.SelectedNodeID;
            if (!string.IsNullOrEmpty(id) && id != "0")
            {
                Model.Base_TestRunLicenseType testRunLicenseType = BLL.TestRunLicenseTypeService.GetLicenseTypeById(id);
                if (testRunLicenseType != null)
                {
                    BLL.TestRunLicenseTypeService.DeleteTestRunLicenseTypeById(id);
                }
            }
            else
            {
                Alert.ShowInTop("请选择类别", MessageBoxIcon.Warning);
                return;
            }
            InitTree();
        }
        #endregion
        #region 增加按钮
        /// 
        /// 增加
        /// 
        /// 
        /// 
        protected void btnNew_Click(object sender, EventArgs e)
        {
            if (this.tvDataTypeInit.SelectedNode != null)
            {
                if (this.tvDataTypeInit.SelectedNodeID != "0")
                {
                    PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("HseLicenseEdit.aspx?licenseTypeId={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;
            }
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("HseLicenseEdit.aspx?hseLicenseId={0}", Grid1.SelectedRowID, "编辑 - ")));
        }
        #endregion
        #region 删除
        /// 
        /// 右键删除
        /// 
        /// 
        /// 
        protected void btnMenuDel_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    var hseLicense = BLL.HseLicenseService.GetHseLicenseById(rowID);
                    if (hseLicense != null)
                    {
                        BLL.HseLicenseService.DeleteHseLicenseById(rowID);
                    }
                }
                BindGrid();
                ShowNotify("删除数据成功!", 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/DriverHse/HseLicense&menuId={1}", id, BLL.Const.HseLicenseMenuId)));
            }
        }
        #endregion
        #region 权限设置
        /// 
        /// 权限设置
        /// 
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.HseLicenseMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnDownLoad.Hidden = false;
                    this.btnNew.Hidden = false;
                    this.btnMenuAdd.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnDownLoad.Hidden = false;
                    this.btnMenuModify.Hidden = false;
                    this.btnMenuModify2.Hidden = false;
                    this.Grid1.EnableRowDoubleClickEvent = true;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnMenuDel.Hidden = false;
                    this.btnMenuDel2.Hidden = false;
                }
            }
        }
        #endregion
        #region 下载模板
        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            if (this.tvDataTypeInit.SelectedNode != null)
            {
                if (this.tvDataTypeInit.SelectedNodeID != "0")
                {
                    Model.AttachFile attachFile = BLL.AttachFileService.GetAttachFile(this.tvDataTypeInit.SelectedNodeID, BLL.Const.HseLicenseMenuId);
                    if (attachFile != null)
                    {
                        PageContext.RegisterStartupScript(Confirm.GetShowReference("是否确认下载作业类别模板?", String.Empty, MessageBoxIcon.Question, PageManager1.GetCustomEventReference(false, "Confirm_OK"), PageManager1.GetCustomEventReference("Confirm_Cancel")));
                    }
                    else
                    {
                        Alert.ShowInTop("模板不存在,请先上传模板!", MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    Alert.ShowInTop("请选择类别!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                Alert.ShowInTop("请选择树节点!", MessageBoxIcon.Warning);
            }
        }
        /// 
        /// 下载导入模板
        /// 
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "Confirm_OK")
            {
                string rootPath = Server.MapPath("~/");
                string initTemplatePath = string.Empty;
                string uploadfilepath = string.Empty;
                Model.AttachFile attachFile = BLL.AttachFileService.GetAttachFile(this.tvDataTypeInit.SelectedNodeID, BLL.Const.HseLicenseMenuId);
                initTemplatePath = attachFile.AttachUrl;
                uploadfilepath = rootPath + initTemplatePath;
                string fileName = Path.GetFileName(initTemplatePath);
                FileInfo info = new FileInfo(uploadfilepath);
                long fileSize = info.Length;
                Response.Clear();
                Response.ContentType = "application/x-zip-compressed";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                Response.AddHeader("Content-Length", fileSize.ToString());
                Response.TransmitFile(uploadfilepath, 0, fileSize);
                Response.Flush();
                Response.Close();
            }
        }
        #endregion
    }
}