using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class News_NewsInfo : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.IsPostBack)
        {
            BindDdlDepartment();
            BindDdlNewsType();
            //BindChklSelectDepartment();
            //BindWebTitle();
            //liUserList.Visible = false;//用户列表按钮隐藏（用户列表只能是超级管理员及总经理操作）
            //liNewsType.Visible = false;//公告类型按钮隐藏
            //liWeb.Visible = false;//网站信息按钮隐藏
            int workid = 0;//职位id
            workid = Operation.GetWorkId(PersonalId);//职位id
            //if (workid == 1 || workid == 2)
            //{
            //    liUserList.Visible = true;//用户列表按钮显示（用户列表只能是超级管理员及总经理操作）
            //    liNewsType.Visible = true;//公告类型按钮显示
            //    liWeb.Visible = true;//网站信息按钮显示
            //}
            //string username = Operation.GetName(Convert.ToInt32(PersonalId));//用户名
            //spanUserName.InnerHtml = username;//用户名赋值到ID为spanUserName的span标签中
            if (!string.IsNullOrEmpty(Request["Nid"]))//编辑公告时
            {
                if ((workid == 1 || workid == 2) == true)
                {
                    BindPage();
                }
                else
                {
                    Response.Redirect("FirstPage.aspx");
                }
            }
            else//添加公告时
            {
                trFileName.Visible = false;//已上传文件行隐藏
                //btnDownLoad.Visible = false;//添加公告时，上传文件为空所以下载按钮隐藏
                if ((workid == 1 || workid == 2 || workid == 4 || workid == 8 || workid == 10 || workid == 15) == true)//workid:1-超级管理员,2-总经理,4-销售部经理,8-会计,10-推广部经理,15-技术部总监
                {
                    btnSubmit.Visible = true;//添加公告提交按钮显示
                }
                else
                {
                    Response.Redirect("FirstPage.aspx");//返回首页
                }
            }
        }
    }
    #region 绑定公告信息页面
    /// <summary>
    /// 绑定公告信息页面
    /// </summary>
    public void BindPage()
    {
        int nid = 0;
        //if (!string.IsNullOrEmpty(Request["NewsId"]))//查看
        //{
        //    nid = Convert.ToInt32(Request["NewsId"]);
        //}
        if (!string.IsNullOrEmpty(Request["Nid"]))//编辑
        {
            nid = Convert.ToInt32(Request["Nid"]);
        }
        DataSet ds = Operation.GetDataSet("SELECT * FROM dbo.tabN_News WHERE Nid=" + nid + "");
        if (ds.Tables[0].Rows.Count > 0)
        {
            txtFileNumber.Text = Convert.ToString(ds.Tables[0].Rows[0]["FileNum"]);//文件号
            ddlDepartment.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["PulishDepartmentId"]);//发布部门
            ddlNewsType.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["NewsType"]);//公告类型
            txtNewsTitle.Text = Convert.ToString(ds.Tables[0].Rows[0]["NewsTitle"]).Trim();//公告标题
            txtNewsTitle.Style["color"] = Convert.ToString(ds.Tables[0].Rows[0]["TitleColor"]);//标题颜色
            if (Convert.ToString(ds.Tables[0].Rows[0]["TitleColor"]).Trim() != "#000000")
            {
                cclColor.Color = Convert.ToString(ds.Tables[0].Rows[0]["TitleColor"]);//标题颜色
            }
            int topState = Convert.ToInt32(ds.Tables[0].Rows[0]["TopState"]);//置顶状态（0-置顶，1-普通）
            if (topState == 0)
            {
                chktTop.Checked = true;//置顶
            }
            else
            {
                chktTop.Checked = false;//普通
            }
            //txtNewsContent.Text = Convert.ToString(ds.Tables[0].Rows[0]["NewsContent"]).Trim();//公告内容
            fckNewsContent.Value = Convert.ToString(ds.Tables[0].Rows[0]["NewsContent"]).Trim();//公告内容
            txtSubscriptContent.Text = Convert.ToString(ds.Tables[0].Rows[0]["SubScript"]);//落款        
            string filename = Convert.ToString(ds.Tables[0].Rows[0]["FileName"]).Trim();//文件名
            if (filename != "")
            {
                spanFileName.InnerHtml = filename;//如果没有上传文件就不显示文件名
            }
            else
            {
                trFileName.Visible = false;//上传文件为空，已上传文件名行隐藏
            }
            aSelectFile.HRef = Convert.ToString(ds.Tables[0].Rows[0]["FilePath"]);//预览文件路径付给预览a标签的href属性
        }
    }
    #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

    #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();
    }
    #endregion

    //#region 绑定公告可看部门chklSelectDepartment
    ///// <summary>
    ///// 绑定可看部门chklSelectDepartment
    ///// </summary>
    //public void BindChklSelectDepartment()
    //{
    //    DataSet ds = Operation.GetDataSet("SELECT Did,DepartmentName FROM dbo.tabDepartment");
    //    chklSelectDepartment.DataValueField = "Did";
    //    chklSelectDepartment.DataTextField = "DepartmentName";
    //    chklSelectDepartment.DataSource = ds;
    //    chklSelectDepartment.DataBind();
    //}
    //#endregion

    #region 绑定ddlNewsType公告类型列表
    /// <summary>
    /// 绑定ddlNewsType公告类型列表
    /// </summary>
    public void BindDdlNewsType()
    {
        DataSet ds = Operation.GetDataSet("SELECT Nid,NewsTypeName FROM dbo.tabN_NewsType");
        ddlNewsType.DataValueField = "Nid";
        ddlNewsType.DataTextField = "NewsTypeName";
        ddlNewsType.DataSource = ds;
        ddlNewsType.DataBind();
    }
    #endregion


    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string filename = fuFile.FileName;//文件名
        string truepath = Server.MapPath("~/LoadFile") + "\\" + filename;//真实路径
        string virtualpath = "~/LoadFile/" + filename;//虚拟路径
        int topState = 0;//置顶状态（0-置顶，1-普通）
        if (chktTop.Checked == false)
        {
            topState = 1;
        }

        if (!string.IsNullOrEmpty(Request["Nid"]))//修改 PersonalId
        {
            #region 修改公告
            int nid = Convert.ToInt32(Request["Nid"]);
            if (filename != "")
            {
                string[] fileNameString = filename.Split('.');//文件名由”.“分隔，fileNameString[1]为文件后缀名
                if (txtFileName.Text != "")
                {
                    filename = txtFileName.Text + '.' + fileNameString[1];//手动修改上传文件名（以txtFileName中的名字为准显示）
                }
                fuFile.SaveAs(truepath);
            }
            else
            {
                DataSet ds = Operation.GetDataSet("SELECT FilePath,FileName FROM dbo.tabN_News WHERE Nid=" + nid + "");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    filename = Convert.ToString(ds.Tables[0].Rows[0]["FileName"]);
                    virtualpath = Convert.ToString(ds.Tables[0].Rows[0]["FilePath"]);
                }
                else
                {
                    virtualpath = "";
                }
            }
            int flag = Operation.Operations("UPDATE dbo.tabN_News SET NewsTitle='" + txtNewsTitle.Text.Trim() + "',NewsContent='" + fckNewsContent.Value.Trim() + "',UpdateTime='" + System.DateTime.Now + "',HandlerId=" + PersonalId + ",FilePath='" + virtualpath + "',FileName='" + filename + "',PulishDepartmentId=" + ddlDepartment.SelectedValue + ",FileNum='" + txtFileNumber.Text.Trim() + "',TitleColor='" + cclColor.Color + "',TopState=" + topState + ",NewsType=" + ddlNewsType.SelectedValue + ",SubScript='" + txtSubscriptContent.Text.Trim() + "' WHERE Nid=" + nid + "");
            if (flag > 0)
            {
                BindPage();
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language='javascript' defer>alert('修改成功！');window.location.href('FirstPage.aspx')</script>");
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language='javascript' defer>alert('修改失败，请联系管理员！');</script>");
            }
            #endregion
        }
        else//添加
        {
            #region 添加公告
            if (filename != "")
            {
                string[] fileNameString = filename.Split('.');//文件名由”.“分隔，fileNameString[1]为文件后缀名
                if (txtFileName.Text != "")
                {
                    filename = txtFileName.Text + '.' + fileNameString[1];//手动修改上传文件名（以txtFileName中的名字为准显示）
                }
                fuFile.SaveAs(truepath);//上传文件
            }
            else
            {
                virtualpath = "";
            }
            int flag = Operation.Operations("INSERT INTO dbo.tabN_News(HandlerId,PulishDepartmentId,FileNum,NewsTitle,NewsType,NewsContent,FileName,FilePath,SignState,SubScript,TopState,TitleColor,CreateTime,UpdateTime) VALUES(" + PersonalId + "," + ddlDepartment.SelectedValue + ",'" + txtFileNumber.Text.Trim() + "','" + txtNewsTitle.Text.Trim() + "'," + ddlNewsType.SelectedValue + ",'" + fckNewsContent.Value.Trim() + "','" + filename + "','" + virtualpath + "',1,'" + txtSubscriptContent.Text.Trim() + "'," + topState + ",'" + cclColor.Color + "','" + System.DateTime.Now + "','" + System.DateTime.Now + "')");
            if (flag > 0)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language='javascript' defer>alert('添加成功！');window.location.href('FirstPage.aspx')</script>");
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language='javascript' defer>alet('添加失败，请联系管理员！');</script>");
            }
            #endregion
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)//取消按钮
    {
        Response.Redirect("FirstPage.aspx");//返回首页公告列表页
        //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language='javascript' defer>window.location.href('FirstPage.aspx')</script>");//返回首页公告列表页
    }

    //protected void btnDownLoad_Click(object sender, EventArgs e)//下载按钮
    //{
    //    #region 下载文件
    //    int nid = 0;
    //    //if (!string.IsNullOrEmpty(Request["NewsId"]))//查看
    //    //{
    //    //    nid = Convert.ToInt32(Request["NewsId"]);
    //    //}
    //    if (!string.IsNullOrEmpty(Request["Nid"]))//编辑
    //    {
    //        nid = Convert.ToInt32(Request["Nid"]);
    //    }
    //    DataSet ds = Operation.GetDataSet("SELECT FileName,FilePath FROM dbo.tabN_News WHERE Nid=" + nid + "");
    //    if(ds.Tables[0].Rows.Count>0)
    //    {
    //        string fileName =Convert.ToString(ds.Tables[0].Rows[0]["FileName"]);//下载文件名
    //        if(fileName!="")
    //        {
    //            string filePath = Server.MapPath(Convert.ToString(ds.Tables[0].Rows[0]["FilePath"]));//下载文件路径
    //            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
    //}
}
