using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;  
using QMFrameWork.WebUI.Attribute;
using QMFrameWork.WebUI.DataSource;
using QMFrameWork.Data;
using QMAPP.Entity.Sys;
using QMAPP.Web.Models.Sys;
using QMAPP.Common.Web.Controllers;
using QMFrameWork.WebUI.Menu;
using System.Text;
using System.Data;
using QMAPP.ServicesAgent;
using System.Configuration;
using QMFrameWork.Common.Serialization;
using QMAPP.Entity;
using System.Text.RegularExpressions;
  
namespace QMAPP.Web.Controllers
{
    /// <summary>
    /// 公告管理控制层
    /// 创建人:王丹丹
    /// 创建时间:20150309
    /// </summary>
    public class NoticeController : QController
    {
        #region 字符串常量 
        private const string uploadFolder = "\\Notice\\";

        #endregion

        #region 公告信息操作

        #region 通知列表

        /// <summary>
        /// 通知列表加载
        /// </summary>
        /// <returns></returns>
        [HandleException]
        public ActionResult NoticeList(bool? callBack)
        {
            NoticeInfoModel seachModel = new NoticeInfoModel();
            if (callBack == true)
                TryGetSelectBuffer<NoticeInfoModel>(out seachModel);
            
            seachModel.rownumbers = false;
            seachModel.url = "/Notice/GetList";

            return View("NoticeList", seachModel);
        }

        /// <summary>
        /// 获取通知列表
        /// </summary>
        /// <param name="callBack">是否回调</param>
        /// <returns></returns>
        [HandleException]
        public ActionResult GetList(bool? callBack)
        {
            List<NoticeInfoModel> notice = new List<NoticeInfoModel>();
            NoticeInfoModel seachModel = null;
            DataPage page = null;
            NoticeInfo condition = null; 
            try
            {
                //获取查询对象
                seachModel = GetModel<NoticeInfoModel>();
                 
                #region 获取缓存值
                if (callBack != null)
                {
                    TryGetSelectBuffer<NoticeInfoModel>(out seachModel);
                }
                else
                {
                    //保存搜索条件
                    SetSelectBuffer<NoticeInfoModel>(seachModel);
                }

                #endregion
                  
                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);

                //获取查询条件
                condition = CopyToModel<NoticeInfo, NoticeInfoModel>(seachModel);
                condition.UserID = AccountController.GetLoginInfo().UserID;
                 
                #region 调用服务
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                page = agent.InvokeServiceFunction<DataPage>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetList.ToString(), condition, page);
                #endregion 

                #region 转换回复数量格式
                //转换回复数量格式
                List<NoticeInfo> list = JsonConvertHelper.GetDeserialize<List<NoticeInfo>>(page.Result.ToString());
                foreach (var item in list)
                {
                    if (item.REPLYCOUNT == "" || item.REPLYCOUNT == null)
                    {
                        item.REPLYCOUNT = "0";
                    }
                }
                #endregion

                //转换查询结果 
                DataGridResult<NoticeInfo> result = new DataGridResult<NoticeInfo>();
                result.Total = page.RecordCount;
                result.Rows = list;
                 
                return Content(result.GetJsonSource());

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 通知编辑

        /// <summary>
        /// 通知编辑载入
        /// </summary>
        /// <returns>通知信息</returns>
        [HandleException]
        public ActionResult NoticeEdit()
        {
            QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
            string noticeID = Request.Params["noticeID"];
            NoticeInfoModel model = new NoticeInfoModel();
            NoticeInfo notice = new NoticeInfo();  
            User user = new User();
            User usermodel = new User();
            try
            {
                if (string.IsNullOrEmpty(noticeID) == false)
                {
                    //获取原通知信息 
                    notice.NOTICEID = noticeID; 
                    notice = agent.InvokeServiceFunction<NoticeInfo>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_Get.ToString(), notice);  
                    model = CopyToModel<NoticeInfoModel, NoticeInfo>(notice); 
                    //获取文件名
                    if (!string.IsNullOrEmpty(notice.ATTACHFILE))
                    {
                        model.ATTACHFILETXT = ChangeFilePath(notice.ATTACHFILE);
                    }   

                    //根据通知ID,从通知浏览记录表中,获取发送目标   
                    List<NoticeBrowse> listEntity = agent.InvokeServiceFunction<List<NoticeBrowse>>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetSendaimIdList.ToString(), noticeID);
                    //根据浏览用户id获取用户名 
                    #region 根据浏览用户id获取用户名
                    foreach (var item in listEntity){
                        //浏览用户id
                        usermodel.UserID = item.USERID;
                        if (model.SENDAIM == "" || model.SENDAIM == null)
                        {
                            model.SENDAIM = item.USERID;
                        }
                        else
                        {
                            model.SENDAIM += "," + item.USERID;
                        } 

                        //根据浏览用户id获取用户名
                        #region 调用服务 
                        user = agent.InvokeServiceFunction<User>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetUser.ToString(), usermodel);
                        #endregion 
                        if (user != null)
                        {
                            if (model.SENDAIMNAME == "" || model.SENDAIMNAME == null)
                            {
                                model.SENDAIMNAME = user.UserName;
                            }
                            else
                            {
                                model.SENDAIMNAME += "," + user.UserName;
                            }
                        }
                    }
                    #endregion 

                }
                else
                {
                    model.USETIME = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                    model.OUTTIME = Convert.ToDateTime(DateTime.Now.AddDays(5).ToShortDateString());
                }
                return View("NoticeEdit", model);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 保存通知

        /// <summary>
        /// 保存通知
        /// </summary>
        /// <param name="saveModel">通知信息</param>
        /// <returns>返回动作</returns>
        [HttpPost]
        [HandleException]
        public ActionResult NoticeSave(NoticeInfoModel saveModel,HttpPostedFileBase file)
        {
            QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
            NoticeInfo notice = new NoticeInfo();
            NoticeInfo model = new NoticeInfo();
            NoticeUpdateInfo updateNotice = new NoticeUpdateInfo();
            NoticeBrowse noticebrowse = new NoticeBrowse();
            try
            { 
                //获取逻辑对象
                notice = CopyToModel<NoticeInfo, NoticeInfoModel>(saveModel); 
                //获取文件保存路径
                string trueFilePath = "";
                if (!string.IsNullOrEmpty(notice.ATTACHFILE))
                {
                    trueFilePath = FilePath(notice.ATTACHFILE); 
                    #region 保存附件

                    //修改通知
                    if (!string.IsNullOrEmpty(notice.NOTICEID))
                    {
                        #region 修改附件  
                        NoticeInfo entity = agent.InvokeServiceFunction<NoticeInfo>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_Get.ToString(), notice);
                      
                        //如果修改了上传附件,校验附件是否存在
                        if (trueFilePath != entity.ATTACHFILE)
                        {
                            //判断文件路径是否存在 
                            bool issuccess = agent.InvokeServiceFunction<bool>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_ExistsFile.ToString(), trueFilePath); 
                            if (issuccess)
                            {
                                SetMessage(AppResource.FileNameIsHave);
                                return View("NoticeEdit", saveModel);
                            }
                            else
                            {
                                //删除原附件
                                agent.InvokeServiceFunction(QMAPP.ServicesAgent.SystemService.NoticeManageBll_DeleteFile.ToString(), entity.ATTACHFILE);

                                //上传新附件 
                                model = this.UploadFile(file, trueFilePath);
                                if (model.IsSuccess == false)
                                {
                                    SetMessage(model.InfoError);
                                    return View("NoticeEdit", saveModel);
                                }
                            }
                        }
                        #endregion
                    }
                    //新建通知
                    else
                    {
                        #region 新建附件
                        //判断文件路径是否存在
                        bool issuccess = agent.InvokeServiceFunction<bool>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_ExistsFile.ToString(), trueFilePath); 
                             
                        if (issuccess)
                        {
                            SetMessage(AppResource.FileNameIsHave);
                            return View("NoticeEdit", saveModel);
                        }
                        else
                        {
                            //上传附件
                            model = this.UploadFile(file, trueFilePath);
                            if (model.IsSuccess == false)
                            {
                                SetMessage(model.InfoError);
                                return View("NoticeEdit", saveModel);
                            }
                        }
                        #endregion
                    }
                    #endregion 
                }
                notice.ATTACHFILE = trueFilePath;
                //保存通知
                DataResult result = agent.InvokeServiceFunction<DataResult>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_Save.ToString(), notice);

                if (result.IsSuccess == false)
                {
                    SetMessage(result.Msg);
                    return View("NoticeEdit", saveModel);
                }

                //保存成功
                SetMessage(AppResource.SaveMessge);
                return this.GetJsViewResult(string.Format("parent.List(1);parent.showTitle('{0}');parent.closeAppWindow1();"
                                            , AppResource.SaveMessge));

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 删除通知

        /// <summary>
        /// 删除通知
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        [HandleException]
        public ActionResult NoticeDelete()
        {
            string selectKey = Request.Form["selectKey"];  
            try
            { 
                #region 调用服务
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                int count = agent.InvokeServiceFunction<int>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_DeleteNotice.ToString(), selectKey); 
                #endregion 

                SetMessage(AppResource.DeleteMessage);

                return NoticeList(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 获取未读通知信息列表
        /// <summary>
        /// 获取未读通知信息列表
        /// </summary>
        /// <returns></returns>
        [HandleException]
        public ActionResult GetNotReadNotice()
        { 
            List<NoticeInfoModel> returnList = null;
            NoticeInfo model = new NoticeInfo();
            List<NoticeInfo> noticeList = new List<NoticeInfo>();
            try
            {
                model.UserID = AccountController.GetLoginInfo().UserID; 
 
                #region 调用服务
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                noticeList = agent.InvokeServiceFunction<List<NoticeInfo>>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetNotReadNotice.ToString(), model);
                #endregion 

                if (noticeList != null)
                {
                    returnList = new List<NoticeInfoModel>();
                    foreach (NoticeInfo ni in noticeList)
                    {
                        NoticeInfoModel retModel = CopyToModel<NoticeInfoModel, NoticeInfo>(ni);
                        returnList.Add(retModel);
                    }
                }
                return Json(returnList);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取未读即时通知信息列表
        /// <summary>
        /// 获取未读即时通知信息列表
        /// </summary>
        /// <returns></returns>
        [HandleException]
        public ActionResult GetNotReadInstantNotice()
        { 
            List<NoticeInfoModel> returnList = null;
            NoticeInfo model = new NoticeInfo();
            List<NoticeInfo> noticeList = new List<NoticeInfo>();
            try
            {
                model.UserID = AccountController.GetLoginInfo().UserID; 

                #region 调用服务
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                noticeList = agent.InvokeServiceFunction<List<NoticeInfo>>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetNotReadInstantNotice.ToString(), model);
                #endregion 
                  
                if (noticeList != null)
                {
                    returnList = new List<NoticeInfoModel>();
                    foreach (NoticeInfo ni in noticeList)
                    {
                        NoticeInfoModel retModel = CopyToModel<NoticeInfoModel, NoticeInfo>(ni);
                        returnList.Add(retModel);
                    }
                }
                return Json(returnList);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
        
        #endregion

        #region 公告信息及浏览记录信息查看、回复

        #region 公告信息查看
        /// <summary>
        /// 公告信息查看
        /// </summary>
        /// <returns></returns>
        [HandleException]
        public ActionResult ViewNotice()
        {
            string noticeID = Request.Params["noticeID"];
            string check = "";
            check = Request.Params["check"];
            NoticeBrowseModel seachModel = null;
            NoticeBrowse noticebrowse = new NoticeBrowse();  
            NoticeInfo noticeModel = new NoticeInfo();
          
            try
            {
                //获取查询对象
                seachModel = GetModel<NoticeBrowseModel>();   

                //获取通知公告id
                noticeModel.NOTICEID = noticeID; 

                #region 调用服务
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                noticeModel = agent.InvokeServiceFunction<NoticeInfo>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_Get.ToString(), noticeModel);
                #endregion 
                 
                #region 更新通知浏览记录为已浏览
                //获取公告浏览记录   
                noticebrowse.USERID = AccountController.GetLoginInfo().UserID;
                noticebrowse.NOTICEID = noticeID; 

                #region 调用服务 
                noticebrowse = agent.InvokeServiceFunction<NoticeBrowse>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetBrowseModel.ToString(), noticebrowse);
                #endregion

                if (noticebrowse != null)
                {
                    noticebrowse.ISREAD = "1";
                    noticebrowse.READTIME = DateTime.Now;
                    //更新通知浏览记录为已浏览
                    #region 调用服务
                    agent.InvokeServiceFunction<int>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_UpdateNoticeBrowse.ToString(), noticebrowse);
                    #endregion
                }
                #endregion

                //获取查询条件
                seachModel = CopyToModel<NoticeBrowseModel, NoticeInfo>(noticeModel); 
                //seachModel.USETIME = noticeModel.USETIME.ToShortDateString();
                seachModel.USETIME = noticeModel.USETIME.ToString("yyyy-MM-dd");
                if (noticebrowse != null)
                {
                    seachModel.REPLYCONTENT = noticebrowse.REPLYCONTENT;
                }
                //当前登录用户
                seachModel.LogInUserName = AccountController.GetLoginInfo().LoginUserID.ToLower(); 
                seachModel.check = check;
               
                #region 获取附件名称
                if (!string.IsNullOrEmpty(noticeModel.ATTACHFILE))
                {
                    seachModel.ATTACHFILE = ChangeFilePath(noticeModel.ATTACHFILE);
                }
                #endregion 

                return View("ViewNotice", seachModel); 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 公告信息回复
        /// <summary>
        /// 公告信息回复
        /// </summary>
        /// <returns></returns>
        [HandleException]
        public ActionResult ViewNoticeReply(NoticeBrowseModel saveModel)
        { 
            NoticeBrowse noticebrowse = new NoticeBrowse(); 
            try
            { 
                noticebrowse = CopyToModel<NoticeBrowse, NoticeBrowseModel>(saveModel);

                #region 更新通知浏览记录
                noticebrowse.USERID = AccountController.GetLoginInfo().UserID;
                noticebrowse.NOTICEID = saveModel.NOTICEID; 
                #region 调用服务
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                noticebrowse = agent.InvokeServiceFunction<NoticeBrowse>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetBrowse.ToString(), noticebrowse);
                #endregion
                 
                noticebrowse.REPLYTIME = DateTime.Now;
                noticebrowse.REPLYCONTENT = saveModel.REPLYCONTENT; 
                //更新通知浏览记录为已浏览 
                #region 调用服务
                agent.InvokeServiceFunction<int>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_UpdateNoticeBrowse.ToString(), noticebrowse);
                #endregion 

                #endregion

                //保存成功
                SetMessage(AppResource.SaveMessge);
                return this.GetJsViewResult(string.Format("parent.List(1);parent.showTitle('{0}');parent.closeAppWindow1();"
                                            , AppResource.SaveMessge));

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 查看公告信息及浏览记录
        /// <summary>
        /// 查看公告信息及浏览记录
        /// </summary>
        /// <returns>公告信息</returns>
        [HandleException]
        public ActionResult ViewNoticeBrowse()
        {
            string noticeID = Request.Params["noticeID"];

            NoticeBrowseModel seachModel = null;
            NoticeBrowse noticebrowse = new NoticeBrowse();
            DataPage page = null; 
            NoticeInfo noticeModel = new NoticeInfo();
            IList<NoticeBrowse> listModel = new List<NoticeBrowse>();
            try
            {
                //获取查询对象
                seachModel = GetModel<NoticeBrowseModel>();
                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);
                page.PageSize = 10000;

                //获取通知公告id
                noticebrowse.NOTICEID = noticeID; 

                //获取通知浏览记录  
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                page = agent.InvokeServiceFunction<DataPage>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetBrowseList.ToString(), noticebrowse, page);
                 

                #region 更新通知浏览记录为已浏览
                //获取公告浏览记录
                noticebrowse.USERID = AccountController.GetLoginInfo().UserID;
                noticebrowse.NOTICEID = noticeID; 
                noticebrowse = agent.InvokeServiceFunction<NoticeBrowse>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetBrowse.ToString(), noticebrowse);
                if (noticebrowse != null)
                {
                    noticebrowse.READTIME = DateTime.Now;
                    noticebrowse.ISREAD = "1"; 
                    agent.InvokeServiceFunction<int>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_UpdateNoticeBrowse.ToString(), noticebrowse);
                }
                #endregion 
                
                #region 回复时间格式转换
                List<NoticeBrowse> listInfo = JsonConvertHelper.GetDeserialize<List<NoticeBrowse>>(page.Result.ToString());

                //回复时间格式转换
                foreach (var item in listInfo)
                {
                    if (Convert.ToDateTime(item.REPLYTIME) == DateTime.MinValue)
                    {
                        item.REPLYTIMETXT = "";
                    }
                    else
                    {
                        item.REPLYTIMETXT = Convert.ToDateTime(item.REPLYTIME).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }
                #endregion 

                #region 转换查询结果
                //转换查询结果 
                DataGridResult<NoticeBrowse> result = new DataGridResult<NoticeBrowse>();
                result.Total = page.RecordCount;
                result.Rows = listInfo; 
                #endregion
                 
                //获取通知公告
                noticeModel.NOTICEID = noticeID; 
                #region 调用服务 
                noticeModel = agent.InvokeServiceFunction<NoticeInfo>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_Get.ToString(), noticeModel);
                #endregion 

                #region 获取附件名称
                if (!string.IsNullOrEmpty(noticeModel.ATTACHFILE))
                {
                    seachModel.ATTACHFILE = ChangeFilePath(noticeModel.ATTACHFILE); 
                }
                #endregion 

                //通知浏览记录
                seachModel.INFOLIST = result.GetJsonSource();
                //通知信息
                seachModel.NOTICETITLE = noticeModel.NOTICETITLE;
                seachModel.NOTICECONTEXT = noticeModel.NOTICECONTEXT; 
                seachModel.USETIME = noticeModel.USETIME.ToString("yyyy-MM-dd");
   
                return View("ViewNoticeBrowse",seachModel);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #endregion

        #region 查看公告列表

        /// <summary>
        /// 查看公告列表
        /// </summary> 
        /// <returns></returns> 
        [HandleException]
        public ActionResult NoticeMessList()
        {
            NoticeInfoModel seachModel = new NoticeInfoModel();

            TryGetSelectBuffer<NoticeInfoModel>(out seachModel);
            seachModel.rownumbers = false;
            seachModel.checkbox = false;
            seachModel.url = "/Notice/GetList";

            return View("NoticeMess", seachModel);
        }

        #endregion
         
        #region 导出excel

        /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns>结果</returns>
        [HttpPost]
        public ActionResult ExportExcel()
        {
            NoticeInfoModel seachModel = null;
            NoticeInfo condition = null;
            DataTable exportDt = new DataTable();
            ServiceAgent wcfAgent = this.GetServiceAgent();
            string ids = Request.Params["ids"];
            try
            {
                //获取查询对象
                seachModel = GetModel<NoticeInfoModel>();
                condition = CopyToModel<NoticeInfo, NoticeInfoModel>(seachModel); 
                //获取数据
                #region 调用服务
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                exportDt = agent.InvokeServiceFunction<DataTable>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetExportData.ToString(), condition);
                #endregion 

                #region 根据所选信息进行导出
                //根据所选信息进行导出
                if (ids != "")
                {
                    DataView dv = new DataView(exportDt);
                    string strWhere = "";
                    string[] list = ids.Split(":".ToCharArray());
                    foreach (string ID in list)
                    {
                        strWhere += " NOTICEID='" + ID + "' or";
                    }
                    if (strWhere != "")
                    {
                        strWhere = strWhere.Remove((strWhere.Length - 2), 2);
                    }
                    dv.RowFilter = strWhere;
                    exportDt = dv.ToTable();
                } 
                #endregion

                //导出       
                QMFrameWork.WebUI.Util.IEFileTool efTool = new QMFrameWork.WebUI.Util.IEFileTool();

                return efTool.GetExcelFileResult("NoticeInfo", "通知信息.xlsx", exportDt);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        #endregion

        #region 上传附件

        #region 上传附件
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="file"></param>
        /// <returns>附件路径,结果</returns>
        [HttpPost]
        public NoticeInfo UploadFile(HttpPostedFileBase file, string trueFilePath)
        {
            NoticeInfo model = new NoticeInfo();
            model.IsSuccess = true;
            string fileName = file.FileName;
            try
            {
                #region 校验附件大小

                //计算文件大小
                int fileLength = file.ContentLength / 1024;
                //判断如果文件大小超过5M,不允许上传
                if (fileLength > 5120)
                {
                    model.InfoError = "上传附件不能大于5M";
                    model.IsSuccess = false;
                    return model;
                }
                #endregion 

                //保存文件
                file.SaveAs(trueFilePath);
                model.ATTACHFILE = trueFilePath;
                return model;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取文件保存路径
        /// <summary>
        /// 获取文件保存路径
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public string FilePath(string filePath)
        {
            string truefilepath = "";
            string expandName = "";
            string trueFileName = "";

            #region 创建上传文件夹

            //获取配置文件上传通知文件夹名称
            string noticeUploadFile = ConfigurationManager.AppSettings.Get("UploadFileRoot");
            //应用程序物理路径
            //PhysicsRootPath = Server.MapPath(HttpRuntime.AppDomainAppVirtualPath); 
            PhysicsRootPath = GetRootPath();
            //附件目录
            string UploadFile = PhysicsRootPath + noticeUploadFile;
            //如果文件夹不存在则创建文件夹
            if (System.IO.Directory.Exists(UploadFile) == false)
            {
                System.IO.Directory.CreateDirectory(UploadFile);
            }

            //通知公告文件路径
            string NoticePath = UploadFile + "\\Notice\\";
            //如果文件夹不存在则创建文件夹
            if (System.IO.Directory.Exists(NoticePath) == false)
            {
                System.IO.Directory.CreateDirectory(NoticePath);
            } 
            #endregion
  
            //构造文件名
            if (filePath.IndexOf(".") > 0)
            {
                expandName = filePath.Substring(filePath.LastIndexOf(".") + 1);
                string temp = filePath.Substring(filePath.LastIndexOf("."));
                trueFileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                trueFileName = trueFileName.Substring(0, trueFileName.Length - temp.Length);

                truefilepath = NoticePath + trueFileName + "." + expandName; 

            }
            return truefilepath;
        }
        #endregion

        #region 截取附件名称
        /// <summary>
        /// 截取附件名称
        /// </summary>
        /// <param name="filePath">附件路径</param>
        /// <returns>附件名称</returns>
        public string ChangeFilePath(string filePath)
        {
            string expandName = "";
            string trueFileName = "sss";

            //构造文件名
            if (filePath.IndexOf(".") > 0)
            {

                expandName = filePath.Substring(filePath.LastIndexOf(".") + 1);
                string temp = filePath.Substring(filePath.LastIndexOf("."));
                trueFileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                trueFileName = trueFileName.Substring(0, trueFileName.Length - temp.Length);

                trueFileName = trueFileName + "." + expandName;
            }
            return trueFileName;
        }
        #endregion

        #endregion

        #region 定时删除超过六个月的通知浏览记录

        /// <summary>
        /// 定时删除超过六个月的通知浏览记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HandleException]
        public void DeleteNoticeBrowse()
        { 
            try
            {
                #region 调用服务
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                agent.InvokeServiceFunction<NoticeInfo>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_DeleteNoticeBrowse.ToString());
                #endregion  
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 打开添加联系人窗口

        #region 打开添加联系人窗口

        /// <summary>
        /// 打开添加联系人窗口
        /// </summary>
        /// <returns></returns>
        [HandleException]
        public ActionResult NoticeUser2()
        {
            NoticeInfoModel seachModel = new NoticeInfoModel();
            seachModel.SENDAIMNAME = Server.UrlDecode(Request.Params["SENDAIMNAME"]);
            seachModel.SENDAIM = Request.Params["SENDAIM"];
            seachModel.url = "/Notice/DefaultUserList";
            return View(seachModel);
        }
        #endregion

        #region 取得选择的组织机构下的人员列表

        /// <summary>
        /// 取得选择的组织机构下的人员列表
        /// </summary>
        /// <returns>处理结果</returns>
        [HandleException]
        public ActionResult DefaultUserList()
        {
            ContractUserModel model = GetModel<ContractUserModel>();
            string selectKey = Request.Params["OrgaID"];
            if (string.IsNullOrEmpty(selectKey))
            {
                selectKey = Request.Params["CorpID"];
            }
            DataPage page = null;

            try
            {
                //获取前台分页设置信息
                page = this.GetDataPage(model);

                #region 调用服务
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                page = agent.InvokeServiceFunction<DataPage>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetNoticeUserList.ToString(), selectKey, page);
                #endregion  
  
                DataGridResult<User> result = new DataGridResult<User>();
                result.Total = page.RecordCount;
                result.Rows = JsonConvertHelper.GetDeserialize<List<User>>(page.Result.ToString());
                 
                return Content(result.GetJsonSource());
            }
            catch (Exception ex)
            {
                throw ex; ;
            }
        }
        #endregion

        #region 获取组织结构树形集合

        /// <summary>
        /// 获取组织结构树形集合
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTreeData()
        {
            try
            {
                List<TreeNodeResult> list = new List<TreeNodeResult>();
                List<Orgaization> menus = new List<Orgaization>(); 

                #region 调用服务
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                menus = agent.InvokeServiceFunction<List<Orgaization>>(QMAPP.ServicesAgent.SystemService.NoticeManageBll_GetAllList.ToString());
                #endregion

                if (menus != null)
                {
                    for (int i = 0; i < menus.Count; i++)
                    {
                        TreeNodeResult treenode = new TreeNodeResult();
                        treenode.Tid = menus[i].OrgaID.ToString();
                        treenode.Ttext = menus[i].OrgaDESC.ToString();
                        if (menus[i].Orgas != null)
                        {
                            for (int j = 0; j < menus[i].Orgas.Count; j++)
                            {
                                TreeNodeResult cTreeNode = new TreeNodeResult();
                                cTreeNode.Tid = menus[i].Orgas[j].OrgaID.ToString();
                                cTreeNode.Ttext = menus[i].Orgas[j].OrgaDESC.ToString();
                                treenode.AddchildNode(cTreeNode);
                            }
                        }
                        list.Add(treenode);
                    }
                    list[0].TChecked = true;
                }
                return Content(TreeNodeResult.GetResultJosnS(list.ToArray()));
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion

        #endregion
   
        #region 获取通知类型下拉列表
        /// <summary>
        /// 获取通知类型下拉列表
        /// </summary>
        /// <returns></returns>
        public ContentResult GetEquComboxSource()
        {  
            try
            {
                ComboboxResult model = new ComboboxResult();
                //Dictionary<string, string> periodTypes = new Dictionary<string, string>();
                //QMFrameWork.Common.Util.ModelDictionaryHandler.TryGetModelDictionary("Month", out periodTypes);
                //foreach (string key in periodTypes.Keys)
                //{
                //    model.Add(new ComboboxItem { ID = key, Text = periodTypes[key] });
                //}
                model.Add(new ComboboxItem { ID = "1", Text = "即时通知" });
                model.Add(new ComboboxItem { ID = "2", Text = "普通通知" });

                return Content(model.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
         
        #region 查看明细

        /// <summary>
        /// 查看明细
        /// </summary>
        /// <param name="noctieModel"></param>
        /// <returns></returns>
        [HandleException]
        public ActionResult NoticeBrowseList(NoticeInfoModel model)
        {
            NoticeBrowseModel seachModel = new NoticeBrowseModel();
            TryGetSelectBuffer<NoticeBrowseModel>(out seachModel);
            seachModel.rownumbers = false; 
            seachModel.url = "/Notice/ShowNotice";

            return View("ShowNotice", seachModel);
        }
        /// <summary>
        /// 查看明细
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowNotice()
        { 
            List<NoticeBrowseModel> notice = new List<NoticeBrowseModel>();
            NoticeBrowseModel seachModel = null;
            DataPage page = null;
            NoticeBrowse condition = null;
            try
            {
                //获取查询对象
                seachModel = GetModel<NoticeBrowseModel>();


                //获取前台分页设置信息
                page = this.GetDataPage(seachModel);

                //获取查询条件
                condition = CopyToModel<NoticeBrowse, NoticeBrowseModel>(seachModel);

                //调用服务 
                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                page = agent.InvokeServiceFunction<DataPage>("NoticeManageBll_GetBrowseList", condition, page);

                //转换查询结果
                DataGridResult<NoticeBrowse> result = new DataGridResult<NoticeBrowse>();
                result.Total = page.RecordCount;
                result.Rows = (List<NoticeBrowse>)page.Result;

                return Content(result.GetJsonSource());

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 下载附件

        /// <summary>
        /// 下载文件名
        /// </summary>
        /// <param name="fileName"></param>
        [HttpPost]
        public FilePathResult DownAttach(string fileName, string oldFileName)
        {
            try
            {
                //应用程序物理路径
                //string PhysicsRootPath = Server.MapPath(HttpRuntime.AppDomainAppVirtualPath);
                PhysicsRootPath = GetRootPath();
                string noticeUploadFile = "\\" + ConfigurationManager.AppSettings.Get("UploadFileRoot") + "\\";
                string contentType = GetContenType(fileName.Substring(fileName.LastIndexOf(".")));

                return File(PhysicsRootPath + noticeUploadFile + uploadFolder + fileName, contentType, Url.Encode(oldFileName));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 根据后缀获取返回CONTENTTYPE
        /// <summary>
        /// 根据后缀获取返回CONTENTTYPE
        /// </summary>
        /// <param name="suffix">后缀</param>
        /// <returns>CONTENTTYPE</returns>
        private string GetContenType(string suffix)
        {
            string resultType = "";
            if (".txt".Equals(suffix.ToLower()))
            {
                resultType = "";
            }
            switch (suffix.ToLower())
            {
                case ".txt":
                    resultType = "text/plain";
                    break;
                case ".xls":
                    resultType = "application/vnd.ms-excel";
                    break;
                case ".xlsx":
                    resultType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    break;
                case ".doc":
                    resultType = "application/msword";
                    break;
                case ".docx":
                    resultType = "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
                    break;
                case ".ppt":
                    resultType = "application/vnd.ms-powerpoint";
                    break;
                case ".pptx":
                    resultType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
                    break; 
                case ".bmp":
                    resultType = "application/x-MS-bmp";
                    break;
                case ".jpg":
                    resultType = "aimage/jpeg";
                    break;
                case ".jpeg":
                    resultType = "image/jpeg";
                    break;
                case ".gif":
                    resultType = "image/gif";
                    break;
                case ".png":
                    resultType = "image/png";
                    break;
                case ".rar":
                    resultType = "application/x-rar-compressed";
                    break;
                case ".zip":
                    resultType = "application/zip";
                    break;

            }
            return resultType;
        }

        #endregion

        #region 判断文件是否存在
        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="oldFileName"></param>
        /// <returns></returns>
        public ActionResult ExistFile()
        {
            QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
            string fileName = Request.Params["fileName"];
            string oldFileName = Request.Params["oldFileName"];
            try
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = oldFileName;
                }
                //应用程序物理路径
                //string PhysicsRootPath = Server.MapPath(HttpRuntime.AppDomainAppVirtualPath);
                PhysicsRootPath = GetRootPath();
                string noticeUploadFile = "\\" + ConfigurationManager.AppSettings.Get("UploadFileRoot") + "\\";
                string contentType = GetContenType(fileName.Substring(fileName.LastIndexOf(".")));

                //判断文件路径是否存在
                string trueFilePath = PhysicsRootPath + noticeUploadFile + uploadFolder + fileName;
                bool issuccess = agent.InvokeServiceFunction<bool>(QMAPP.ServicesAgent.SystemService.FileInfoBLL_ExistsFile.ToString(), trueFilePath);
                if (!issuccess)
                {
                    return Json("false");
                }
                else
                {
                    return Json("true");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion 
        
        #region 取得网站根目录的物理路径
        /// <summary>
        /// 取得网站根目录的物理路径
        /// </summary>
        /// <returns></returns>
        public static string GetRootPath()
        {
            string AppPath = "";
            System.Web.HttpContext HttpCurrent = System.Web.HttpContext.Current;
            if (HttpCurrent != null)
            {
                AppPath = HttpCurrent.Server.MapPath("~");
            }
            else
            {
                AppPath = AppDomain.CurrentDomain.BaseDirectory;
                if (Regex.Match(AppPath, @"\\$", RegexOptions.Compiled).Success)
                    AppPath = AppPath.Substring(0, AppPath.Length - 1);
            }
            return AppPath;
        }
        #endregion 
    }
}