using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Text;

public partial class News_FirstPage : PageBase
{
    private static int currentPageNum = 1;//当前页数
    private static int pageCount = 1;//总页数
    //未登录的用户只能查看公告和下载文件
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.IsPostBack)
        {
            BindDdlDepartment();
            //BindWebTitle();
            //liUserList.Visible = false;//用户列表按钮隐藏（用户列表只能是超级管理员及总经理操作）
            //liNewsType.Visible = false;//公告类型按钮隐藏
            //liWeb.Visible = false;//网站信息按钮隐藏
                //liLogin.Visible = false;//登录按钮隐藏
                //string username = Operation.GetName(Convert.ToInt32(PersonalId));//用户名
                //spanUserName.InnerHtml = username;//用户名赋值到ID为spanUserName的span标签中
                int workid = Operation.GetWorkId(Convert.ToInt32(PersonalId));//职位id
                //if ((workid == 1 || workid == 2) == true)//是1-超级管理员或2-总经理的用户
                //{
                //    liUserList.Visible = true;//用户列表按钮显示（用户列表只能是超级管理员及总经理操作）
                //    liNewsType.Visible = true;//公告类型按钮显示
                //    liWeb.Visible = true;//网站信息按钮显示
                //}
                if ((workid == 1 || workid == 2 || workid == 4 || workid == 8 || workid == 10 || workid == 15) == false)//workid:1-超级管理员,2-总经理,4-销售部经理,8-会计,10-推广部经理,15-技术部总监
                {
                    btnAdd.Visible = false;//添加公告按钮隐藏
                }
                BindRptNews();
        }
    }
    #region 绑定ddlDepartment部门列表
    /// <summary>
    /// 绑定ddlDepartment部门列表
    /// </summary>
    public void BindDdlDepartment()
    {
        DataSet ds = Operation.GetDataSet("SELECT DepartmentId,DepartmentName FROM dbo.tabP_Department");
        ddlDepartment.DataValueField = "DepartmentId";
        ddlDepartment.DataTextField = "DepartmentName";
        ddlDepartment.DataSource = ds;
        ddlDepartment.DataBind();
        ddlDepartment.Items.Insert(0,new ListItem("请选择发布部门","0"));
    }
    #endregion
    //#region 绑定网站名和logo图片
    ///// <summary>
    ///// 绑定网站名和logo图片
    ///// </summary>
    //public void BindWebTitle()
    //{
    //    DataSet ds = Operation.GetDataSet("SELECT CompanyLogo,webName,webDescribe FROM dbo.tabN_Company WHERE Cid=1");
    //    if (ds.Tables[0].Rows.Count > 0)
    //    {
    //        this.Page.Title = Convert.ToString(ds.Tables[0].Rows[0]["webName"]) + "-首页";//页面标题
    //        h3Title.InnerHtml = Convert.ToString(ds.Tables[0].Rows[0]["webName"]);//网站名
    //        if (Convert.ToString(ds.Tables[0].Rows[0]["CompanyLogo"]) != "")
    //        {
    //            imgLogo.Src = Convert.ToString(ds.Tables[0].Rows[0]["CompanyLogo"]);//网站logo
    //        }
    //        else
    //        {
    //            imgLogo.Src = "~/Image/nopic.gif";//即默认图片
    //        }
    //    }
    //}
    //#endregion

    /// <summary>
    /// 绑定rptNews公告列表
    /// </summary>
    public void BindRptNews()
    {
        pageCount = GetPageCount();//总页数
        spanPageCount.InnerHtml = ConvertHelper.GetString(pageCount);//总页数
        ControlHelper.BindRepeater(this.rptNews, "constring", StrWhere + "AND Row BETWEEN (" + currentPageNum + "-1)*15+1 AND " + currentPageNum + "*15 ");
    }
    #region 获取操作人真实姓名
    /// <summary>
    /// 获取操作人真实姓名
    /// </summary>
    /// <param name="handlerId"></param>
    /// <returns></returns>
    public string GetOperationer(object handlerId)
    {
        int handlerID = Convert.ToInt32(handlerId);
        string username = "";
        DataSet ds = Operation.GetDataSet("SELECT PersonnelName FROM dbo.tabP_Personnel WHERE Pid=" + handlerId + "");
        if (ds.Tables[0].Rows.Count > 0)
        {
            username = Convert.ToString(ds.Tables[0].Rows[0]["PersonnelName"]);
        }
        return username;
    }
    #endregion

    #region 文件名为空，则显示”空“字,不为空则显示其文件名
    /// <summary>
    /// 文件名为空，则显示”空“字,不为空则显示其文件名
    /// </summary>
    /// <param name="filename">文件名</param>
    /// <returns></returns>
    public string GetFileName(object filename)
    {
        string fileName = Convert.ToString(filename);
        if (fileName == "")
        {
            fileName = "无";
        }
        return fileName;
    }
    #endregion

    #region 获取公告发布部门
    /// <summary>
    /// 获取公告发布部门名
    /// </summary>
    /// <param name="nid">公告发布部门id</param>
    /// <returns></returns>
    public string GetPublishDepartmentName(object pulishDepartmentId)
    {
        string departmentName = "";
        DataSet ds = Operation.GetDataSet("SELECT DepartmentName FROM dbo.tabP_Department WHERE DepartmentId=" + pulishDepartmentId + "");
        if (ds.Tables[0].Rows.Count > 0)
        {
            departmentName = Convert.ToString(ds.Tables[0].Rows[0]["DepartmentName"]);
        }
        return departmentName;
    }
    #endregion
    protected void rptNews_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int nid = Convert.ToInt32((e.Item.FindControl("hfNewsId") as HiddenField).Value);//公告ID
        string filepath = (e.Item.FindControl("hfFilePath") as HiddenField).Value;//上传文件的地址
        if (e.CommandName == "selectContent")//点击公告标题查看详细信息
        {
            int newsType = Convert.ToInt32((e.Item.FindControl("hfNewsType") as HiddenField).Value);
            if (newsType == 4)//带模板1
            {
                Response.Redirect("SelectNews.aspx?NewsId=" + nid + "");
            }
            else//自定义模板或公司动态
            {
                Response.Redirect("SelectDIYNew.aspx?NewsId=" + nid + "");
            }
        }
        if (e.CommandName == "select")//点击查看按钮显示公告详细信息
        {
            int newsType = Convert.ToInt32((e.Item.FindControl("hfNewsType") as HiddenField).Value);
            if (newsType == 4)//带模板1
            {
                Response.Redirect("SelectNews.aspx?NewsId=" + nid + "");
            }
            else//自定义模板或公司动态
            {
                Response.Redirect("SelectDIYNew.aspx?NewsId=" + nid + "");
            }
        }
        if (e.CommandName == "download")//下载文件
        {
            #region 下载文件
            string fileName = (e.Item.FindControl("hfFileName") as HiddenField).Value;//下载文件名
            string filePath = Server.MapPath((e.Item.FindControl("hfFilePath") as HiddenField).Value);//下载文件路径
            FileInfo fileInfo = new FileInfo(filePath);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            Response.End();
            #endregion
        }
        if (e.CommandName == "selectFile")//预览文件
        {
            Response.Redirect(filepath);
        }
        if (e.CommandName == "edit")//修改
        {
            Response.Redirect("NewsInfo.aspx?Nid=" + nid + "");
        }
        if (e.CommandName == "delete")//单个删除
        {
            int flag = Operation.Operations("UPDATE dbo.tabN_News SET State=0 WHERE Nid=" + nid + "");//State:删除状态（0-已删除，1-未删除）
            //#region 删除已删除公告的上传文件
            //FileInfo newFile = new FileInfo(Server.MapPath((e.Item.FindControl("hfFilePath") as HiddenField).Value));
            //if (newFile.Exists == true)
            //{
            //    newFile.Delete();//删除文件
            //}
            //#endregion
            if (flag > 0)
            {
                BindRptNews();
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language='javascript' defer>alert('删除成功！');</script>");
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language='javascript' defer>alert('删除失败！')</script>");
            }
        }
    }
    protected void rptNews_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        int nid = Convert.ToInt32((e.Item.FindControl("hfNewsId") as HiddenField).Value);
        #region 标题截取字符串
        string newsTitle = (e.Item.FindControl("spanNewsTitle") as HtmlGenericControl).InnerHtml;//标题
        if (newsTitle.Length > 30)
        {
            (e.Item.FindControl("spanNewsTitle") as HtmlGenericControl).InnerHtml = newsTitle.Substring(0, 30);//截取字符串
        }
        #endregion
        #region 修改删除按钮的显示和隐藏
        DataSet ds = Operation.GetDataSet("SELECT Pid FROM dbo.tabP_Personnel WHERE Pid=" + PersonalId + " AND (WorkId=1 OR WorkId=2)");//WorkId：1-超级管理员；2-总经理
        if (ds.Tables[0].Rows.Count < 1)//登录后不是超级管理员的用户
        {
            (e.Item.FindControl("lbtnEdit") as LinkButton).Visible = false;//修改隐藏
            (e.Item.FindControl("lbtnDelete") as LinkButton).Visible = false;//删除隐藏
        }
        #endregion
        #region 上传下载按钮的显示和隐藏
        if ((e.Item.FindControl("hfFileName") as HiddenField).Value == "")//上传文件为空
        {
            (e.Item.FindControl("lbtnDownLoad") as LinkButton).Visible = false;//上传文件为空时，下载按钮隐藏
            (e.Item.FindControl("lbtnSelectFile") as LinkButton).Visible = false;//上传文件为空时，预览按钮隐藏
        }
        #endregion
        #region 未查看公告文字行呈红色
        DataSet dsSelectInfo = SqlHelper.GetDataSet("SELECT SelectNewsId FROM dbo.tabN_NewsSelect WHERE NewsId=" + nid + " AND SelectUserId="+PersonalId+"", "constring");
        if(dsSelectInfo.Tables[0].Rows.Count<=0)
        {
            (e.Item.FindControl("trNews") as HtmlTableRow).Style["color"] = "Red";//未查看行
            (e.Item.FindControl("lbtnSelectContent") as LinkButton).Style["color"] = "Red";//公告内容
            (e.Item.FindControl("lbtnSelect") as LinkButton).Style["color"] = "Red";//查看按钮
            (e.Item.FindControl("lbtnDownLoad") as LinkButton).Style["color"] = "Red";//下载按钮
            (e.Item.FindControl("lbtnSelectFile") as LinkButton).Style["color"] = "Red";//预览按钮
            (e.Item.FindControl("lbtnEdit") as LinkButton).Style["color"] = "Red";//编辑按钮
            (e.Item.FindControl("lbtnDelete") as LinkButton).Style["color"] = "Red";//删除按钮
        }
        #endregion
    }
    #region 分页
    #region 获取分页总页数
    /// <summary>
    /// 获取分页总页数
    /// </summary>
    /// <returns></returns>
    public int GetPageCount()
    {
        int pagecount = 0;//总页数
        SetStrWhere();
        DataSet ds = SqlHelper.GetDataSet(StrWhere, "constring");
        if (ds.Tables[0].Rows.Count > 0)
        {
            int loanAccountCount = ConvertHelper.GetInteger(ds.Tables[0].Rows.Count);//借贷用户总个数
            if (loanAccountCount % 15 == 0)
            {
                pagecount = loanAccountCount / 15;
            }
            else
            {
                pagecount = loanAccountCount / 15 + 1;
            }
        }
        else
        {
            pagecount = 1;
        }
        return pagecount;
    }
    #endregion
    #region 首页
    protected void lbtnPageFirst_Click(object sender, EventArgs e)//首页
    {
        currentPageNum = 1;
        BindRptNews();
        spanPageCurrent.InnerHtml = "1";//当前页为1
    }
    #endregion
    #region 上页
    protected void lbtnPageUp_Click(object sender, EventArgs e)//上页
    {
        if (spanPageCurrent.InnerHtml != "1")//不是首页时
        {
            currentPageNum = ConvertHelper.GetInteger(spanPageCurrent.InnerHtml) - 1;
            BindRptNews();
            spanPageCurrent.InnerHtml = ConvertHelper.GetString(currentPageNum);//当前页spanPageCurrent赋值
        }
    }
    #endregion
    #region 下页
    protected void lbtnPageDown_Click(object sender, EventArgs e)//下页
    {
        if (spanPageCurrent.InnerHtml != ConvertHelper.GetString(pageCount))//不是尾页时
        {
            currentPageNum = ConvertHelper.GetInteger(spanPageCurrent.InnerHtml) + 1;
            BindRptNews();
            spanPageCurrent.InnerHtml = ConvertHelper.GetString(currentPageNum);//当前页spanPageCurrent赋值
        }
    }
    #endregion
    #region 末页
    protected void lbtnPageLast_Click(object sender, EventArgs e)//末页
    {
        currentPageNum = GetPageCount();
        BindRptNews();
        spanPageCurrent.InnerHtml = ConvertHelper.GetString(pageCount);//当前页等于总页数
    }
    #endregion
    #endregion
    #region 查询sql语句属性
    /// <summary>
    /// 查询sql语句属性
    /// </summary>
    public string StrWhere
    {
        get { return Convert.ToString(ViewState["StrWhere"]); }
        set { ViewState["StrWhere"] = value; }
    }
    /// <summary>
    /// 修改sql语句属性的方法
    /// </summary>
    public void SetStrWhere()
    {
        StringBuilder strb = new StringBuilder();
        int workid = Operation.GetWorkId(Convert.ToInt32(PersonalId));//职位id
        if ((workid == 1 || workid == 2) == true)//是1-超级管理员或2-总经理的用户
        {
            strb.Append("SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY TopState ASC,CreateTime DESC) AS Row,Nid,HandlerId,PulishDepartmentId,NewsTitle,NewsContent,FileName,FileNum,FilePath,CreateTime,UpdateTime,NewsType FROM dbo.tabN_News WHERE State=1) AS temptable  WHERE 1=1 ");
        }
        else
        {
            strb.Append("SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY TopState ASC,CreateTime DESC) AS Row,Nid,HandlerId,PulishDepartmentId,NewsTitle,NewsContent,FileName,FileNum,FilePath,CreateTime,UpdateTime,NewsType FROM dbo.tabN_News WHERE State=1 AND PulishDepartmentId =(SELECT DepartmentId FROM dbo.tabP_Work WHERE WorkId=" + workid + ") OR PulishDepartmentId=1) AS temptable  WHERE 1=1 ");
        }
        if(!(string.IsNullOrEmpty(txtStateTime.Text.Trim())||string.IsNullOrEmpty(txtEndTime.Text.Trim())))//查询的发布时间
        {
            if(ConvertHelper.GetDateTime(txtStateTime.Text.Trim())<ConvertHelper.GetDateTime(txtEndTime.Text.Trim()))
            {
                strb.Append(" AND (CreateTime>='" + ConvertHelper.GetDateTime(txtStateTime.Text.Trim()) + "' AND CreateTime<='" + ConvertHelper.GetDateTime(txtEndTime.Text.Trim()) + "') ");
            }
        }
        if(!string.IsNullOrEmpty(txtTitle.Text.Trim()))//公告标题
        {
            strb.Append(" AND NewsTitle LIKE '%"+txtTitle.Text.Trim()+"%' ");
        }
        if(ddlDepartment.SelectedValue!="0")//发布部门
        {
            strb.Append(" AND PulishDepartmentId="+ddlDepartment.SelectedValue+" ");
        }
        //if (uclBankCard.BankCardID != 0)//查询事件中的银行卡
        //{
        //    strb.Append("AND BankCardID=" + uclBankCard.BankCardID + " ");//银行卡id
        //}
        //else if (!string.IsNullOrEmpty(Request["BankId"]))//从银行卡列表页点击查看明细跳转到明细页面（即本页面）
        //{
        //    strb.Append("AND BankCardID=" + Request["BankId"] + " ");//银行卡id
        //}
        //if (!string.IsNullOrEmpty(txtCardNumber.Text.Trim()))
        //{
        //    strb.Append("AND BankCardNumber like '%" + txtCardNumber.Text.Trim() + "%' ");//银行卡号（模糊查询）
        //}
        //if (!string.IsNullOrEmpty(txtHeader.Text.Trim()))
        //{
        //    strb.Append("AND Header like '%" + txtHeader.Text.Trim() + "%' ");//户主名（模糊查询）
        //}
        //if (!string.IsNullOrEmpty(txtOther.Text.Trim()))
        //{
        //    strb.Append("AND OtherName like '%" + txtOther.Text.Trim() + "%'");//交易对方（模糊查询）
        //}
        //strb.Append(string.Format(timewhere.WhereString, " a.CreateTime"));
        StrWhere = strb.ToString();
    }
    #endregion
    protected void btnAdd_Click(object sender, EventArgs e)//添加公告
    {
        Response.Redirect("NewsInfo.aspx");
    }
    protected void btnSelect_Click(object sender, EventArgs e)
    {
        BindRptNews();
    }
}
