using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Controllers.workorder;
using CallCenterApi.Model;
using LumiSoft.Net.Mail;
using LumiSoft.Net.MIME;
using LumiSoft.Net.POP3.Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    public class EmailSendController : BaseController
    {
        BLL.T_Email_SendEmail bllEmail = new BLL.T_Email_SendEmail();

        /// <summary>
        /// 批量发送邮件
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult SendbatchEmail()
        {
            MailHelper mh = new MailHelper();
            mh.MailName = Configs.GetValue("MailName");         //邮箱名称
            //mh.MailName = mh.MailUserName.Split('@')[0].ToString(); //名称
            mh.MailServer = Configs.GetValue("MailServer");     //"smtp.126.com";   //邮件服务器地址
            mh.MailUserName = Configs.GetValue("MailUserName"); //用户名
            mh.MailPassword = Configs.GetValue("MailPassword"); //密码

            string workOrder = RequestString.GetFormString("workOrder");
            int typeId = RequestString.GetInt("typeId", 0);
            string emailList = RequestString.GetFormString("email");
            string title = RequestString.GetFormString("title");
            string content = RequestString.GetFormString("content");
            if (!string.IsNullOrEmpty(emailList))
            {
                int ix = 0; //成功个数
                int iy = 0; //失败个数
                string[] arrStr = emailList.Split(',');
                foreach (string str in arrStr)
                {
                    string strEmail = str;
                    bool b = mh.Send(strEmail, title, content);
                    Model.T_Email_EmailList eModel = new BLL.T_Email_EmailList().GetModelByEmail(strEmail);
                    //接收邮箱名称
                    string receiveName = string.Empty;
                    int e_Id = 0;
                    if (eModel != null)
                    {
                        receiveName = eModel.E_Name;
                        e_Id = eModel.E_Id;
                    }
                    Model.T_Email_SendEmail model = new Model.T_Email_SendEmail();
                    if (b)
                    {
                        model.E_IsSucces = 1;   //成功
                        ix++;
                    }
                    else
                    {
                        model.E_IsSucces = 0;   //失败
                        iy++;
                    }                    
                    model.E_WorkOrderId = workOrder;
                    model.E_TypeId = typeId;
                    model.E_SendEmail = mh.MailUserName;                            //发送邮箱
                    model.E_SendName = mh.MailUserName.Split('@')[0].ToString();    //发送邮箱名称
                    model.E_ReceiveEmail = strEmail;                                //接收邮箱
                    model.E_ReceiveName = string.IsNullOrEmpty(receiveName) ? strEmail.Split('@')[0].ToString() : receiveName;        
                    model.E_Title = title;
                    model.E_Content = content;
                    model.E_AddTime = DateTime.Now;
                    model.F_UserId = int.Parse(User.UserData["F_UserID"]);
                    model.F_UserName = User.UserData["F_UserCode"];
                    //model.F_UserId = 0;
                    //model.F_UserName = string.Empty;

                    new BLL.T_Email_SendEmail().Add(model);
                    if (e_Id > 0)
                    {
                        new BLL.T_Email_EmailList().Delete(eModel.E_Id);
                    }

                }
                string result = string.Empty;
                if (ix > 0) {
                    result += "已发送:" + ix;
                }
                if (iy > 0) {
                    result += "发送失败:" + iy;
                }
                if (ix > 0)
                {
                    return Success("发送成功", result);
                }
                else {
                    return Error("发送失败");
                }
            }
            else {
                return Error("邮箱不能为空");
            }
        }

        /// <summary>
        /// 导入邮件
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult ImportEmail()
        {
            string resultEmail = "";    //输出邮箱

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            HttpPostedFile _upfile = RequestString.GetFile("upFile");
            int headrow = 0;
            NPOIHelper npoi = new NPOIHelper();
            DataTable dt = npoi.ExcelToTable(_upfile, headrow);

            foreach (DataRow dr in dt.Rows)
            {
                headrow = headrow + 1;
                if (dr[0].ToString() != "" && dr[1].ToString() != "")
                {
                    Model.T_Email_EmailList model = new Model.T_Email_EmailList();
                    model.E_Name = dr[0].ToString();    //姓名
                    model.E_Email = dr[1].ToString();   //邮件
                    model.E_State = 0;                  //状态
                    model.E_AddTime = DateTime.Now;     //添加时间
                    model.F_UserId = userId;            //添加用户Id
                    if (new BLL.T_Email_EmailList().Add(model) <= 0)
                    {
                        return Error("第" + headrow + "行，导入失败!");
                    }
                    else {
                        resultEmail += dr[1].ToString() + ",";  //邮箱拼接
                    }
                }
                else
                {
                    return Error("第" + headrow + "行，第1，2列信息不能为空，未导入");
                }
            }
            return Success("导入成功", resultEmail.Trim(',').ToString());
        }

        #region 批量获取126邮件,删除,审核，创建邮件工单

        /// <summary>
        /// 获取邮件信息列表（可以分页）-- 新
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetEmailMessageList()
        {
            BLL.T_Email_EmailMessage_Map bll = new BLL.T_Email_EmailMessage_Map();
            int isAudit= RequestString.GetInt("isAudit", 0);
            int recordCount = 0;
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            //判断
            if (pagesize <= 0)
            {
                return Error("每页记录不能小于2，默认为10");
            }
            List<EmailrReceive> list = new List<EmailrReceive>();
            List<EmailrReceive> lists = new List<EmailrReceive>();

            if (isAudit == 1)
            {
                var Emaillist = bll.DataTableToList(bll.GetList(" 1=1 ").Tables[0]).OrderByDescending(x => x.E_EmailTime); ;
                foreach (var p in Emaillist)
                {
                    EmailrReceive modelEmail = new EmailrReceive();
                    modelEmail.E_EmailId = p.E_EmailId;
                    modelEmail.E_Email = p.E_SendEmail;
                    modelEmail.E_Address = p.E_SendName;
                    modelEmail.E_Title = p.E_Title;
                    modelEmail.E_EmailTime = Convert.ToDateTime(p.E_EmailTime);
                    modelEmail.E_Content = p.E_Content;
                    modelEmail.E_AttachmentsUrl = p.E_AttachmentsUrl;
                    modelEmail.E_WorkOrderId = p.E_WorkOrderId;
                    modelEmail.E_IsWorkOrder = p.E_IsWorkOrder;
                    modelEmail.E_IsAudit = p.E_IsAudit;
                    list.Add(modelEmail);
                }
            }
            else
            {
                using (POP3_Client pop3 = new POP3_Client())
                {
                    try
                    {
                        pop3.Connect(Configs.GetValue("Email_Server"), int.Parse(Configs.GetValue("Email_Port")), false);
                        pop3.Login(Configs.GetValue("Email_Name"), Configs.GetValue("Email_Password")); //两个参数，前者为Email的账号，后者为Email的密码  
                    }
                    catch (Exception ex)
                    {
                        return Error("邮箱登录失败，请查看登录配置或是否能访问外网");
                    }
                    POP3_ClientMessageCollection messages = pop3.Messages;

                    for (int i = messages.Count - 1; i >= 0; i--)
                    {
                        EmailrReceive model = new EmailrReceive();
                        POP3_ClientMessage message = messages[i];   //转化为POP3  
                        if (message != null)
                        {
                            byte[] messageBytes = message.MessageToByte();
                            Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes);
                            model.E_EmailId = message.UID;
                            model.E_Email = mime_message.From == null ? " " : mime_message.From[0].DisplayName;
                            model.E_Address = mime_message.From == null ? " " : mime_message.From[0].Address;
                            model.E_Title = mime_message.Subject ?? " ";
                            model.E_EmailTime = mime_message.Date;
                            model.E_Content = mime_message.BodyText ?? " ";

                            MIME_Entity[] attachments = mime_message.GetAttachments(true, true);
                            string Url = string.Empty;
                            int n = 0;
                            foreach (MIME_Entity entity in attachments)
                            {
                                if (entity.ContentDisposition != null)
                                {
                                    string fileName = entity.ContentDisposition.Param_FileName;
                                    if (!string.IsNullOrEmpty(fileName))
                                    {
                                        n += 1;
                                        string pathUrl = "/Upload/Email/" + DateTime.Now.ToString("yyyy") + "" + DateTime.Now.ToString("MM") + "/";   // + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                                        string path = System.Web.HttpContext.Current .Server.MapPath("..") + pathUrl;
                                        string fileNames = DateTime.Now.ToString("yyyyMM") + DateTimeConvert.ToTimetag(mime_message.Date) + n + fileName; //重新命名附件

                                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                                        path = Path.Combine(path, fileNames);
                                        MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body;
                                        Stream decodedDataStream = byteObj.GetDataStream();
                                        using (FileStream fs = new FileStream(path, FileMode.Create))
                                        {
                                            LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs, 4000);
                                        }
                                        Url += pathUrl + fileNames + ",";
                                    }
                                }
                            }
                            model.E_AttachmentsUrl = Url.TrimEnd(',');
                            if (!string.IsNullOrEmpty(message.UID))
                            {
                                var listmodel = bll.GetModelList(" E_EmailId='" + message.UID + "'").FirstOrDefault();
                                model.E_IsWorkOrder = 0;
                                model.E_IsAudit = 0;
                                if (listmodel != null)
                                {
                                    model.E_WorkOrderId = listmodel.E_WorkOrderId;
                                    model.E_IsWorkOrder = listmodel.E_IsWorkOrder;
                                    model.E_IsAudit = listmodel.E_IsAudit;
                                }
                            }

                            list.Add(model);
                        }
                    }

                }
                list = list.Where(a => a.E_IsAudit == isAudit).ToList();
            }
            var obj = new
            {
                rows = list.Skip((pageindex - 1) * pagesize).Take(pagesize),
                total = list.Count
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取邮件信息列表（可以分页） 暂不使用
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetEmailMessage()
        {
            BLL.T_Email_EmailMessage_Map bll = new BLL.T_Email_EmailMessage_Map();
            int recordCount = 0;
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10 - 1;
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize) - 1;
            }
            //判断
            if (pagesize <= 0)
            {
                return Error("每页记录不能小于2，默认为10");
            }
            List<EmailrReceive> list = new List<EmailrReceive>();

            using (POP3_Client pop3 = new POP3_Client())
            {
                pop3.Connect(Configs.GetValue("Email_Server"), int.Parse(Configs.GetValue("Email_Port")), false);
                pop3.Login(Configs.GetValue("Email_Name"), Configs.GetValue("Email_Password")); //两个参数，前者为Email的账号，后者为Email的密码  

                POP3_ClientMessageCollection messages = pop3.Messages;
                recordCount = messages.Count;
                #region 分页判断
                int emailcount = messages.Count; //总数
                float emailpage2 = emailcount % pagesize;
                int emailpage = emailcount / pagesize; //总页数
                //判断是否有余数
                if (emailpage2 > 0) //(float)emailpage
                    emailpage = emailpage + 1;
                //判断如果当前页为负数或者零时
                if (pageindex <= 0)
                    pageindex = 1;
                //判断如果当前页大于总页数时
                if (pageindex > emailpage)
                    pageindex = emailpage;

                int start = emailcount - 1 - (pageindex - 1) * pagesize;
                int end = emailcount - 1 - pageindex * pagesize;
                if (end < 0)
                    end = 0;
                #endregion

                for (int i = start; i >= end; i--)
                {
                    EmailrReceive model = new EmailrReceive();
                    POP3_ClientMessage message = messages[i];   //转化为POP3  
                    if (message != null)
                    {
                        byte[] messageBytes = message.MessageToByte();
                        Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes);
                        model.E_EmailId = message.UID;
                        model.E_Email= mime_message.From == null ? " " : mime_message.From[0].DisplayName;
                        model.E_Address= mime_message.From == null ? " " : mime_message.From[0].Address;
                        model.E_Title= mime_message.Subject ?? " ";
                        model.E_EmailTime= mime_message.Date;
                        model.E_Content= mime_message.BodyText ?? " ";

                        MIME_Entity[] attachments = mime_message.GetAttachments(true, true);
                        string Url = string.Empty;
                        int n = 0;
                        foreach (MIME_Entity entity in attachments)
                        {
                            if (entity.ContentDisposition != null)
                            {
                                string fileName = entity.ContentDisposition.Param_FileName;
                                if (!string.IsNullOrEmpty(fileName))
                                {
                                    n += 1;
                                    string pathUrl = "/Upload/Email/" + DateTime.Now.ToString("yyyy") + "" + DateTime.Now.ToString("MM") + "/";   // + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                                    string path = Server.MapPath("..") + pathUrl;
                                    string fileNames = DateTimeConvert.ToTimetag(mime_message.Date) + n + fileName; //重新命名附件

                                    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                                    path = Path.Combine(path, fileNames);
                                    MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body;
                                    Stream decodedDataStream = byteObj.GetDataStream();
                                    using (FileStream fs = new FileStream(path, FileMode.Create))
                                    {
                                        LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs, 4000);
                                    }
                                    Url += pathUrl + fileNames + ",";
                                }
                            }
                        }
                        model.E_AttachmentsUrl = Url.TrimEnd(',');
                        if (!string.IsNullOrEmpty(message.UID))
                        {
                            var listmodel = bll.GetModelList(" E_EmailId='" + message.UID + "'").FirstOrDefault();
                            if (listmodel != null)
                            {
                                model.E_WorkOrderId = listmodel.E_WorkOrderId;
                                model.E_IsWorkOrder = listmodel.E_IsWorkOrder;
                                model.E_IsAudit = listmodel.E_IsAudit;
                            }
                        }

                        list.Add(model);
                    }
                }
            }
            var obj = new
            {
                rows = list,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 获取邮件详情ByID
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public ActionResult GetEmailInfoById(string uid)
        {
            BLL.T_Email_EmailMessage_Map bll = new BLL.T_Email_EmailMessage_Map();
            List<EmailrReceive> list = new List<EmailrReceive>();
            EmailrReceive model = new EmailrReceive();
            if (string.IsNullOrEmpty(uid)) {
                return Error("参数不能为空");
            }

            using (POP3_Client pop3 = new POP3_Client())
            {
                pop3.Connect(Configs.GetValue("Email_Server"), int.Parse(Configs.GetValue("Email_Port")), false);
                pop3.Login(Configs.GetValue("Email_Name"), Configs.GetValue("Email_Password")); //两个参数，前者为Email的账号，后者为Email的密码  

                POP3_ClientMessageCollection messages = pop3.Messages;

                for (int i = 0; i < messages.Count; i++)
                {
                    POP3_ClientMessage message = messages[i];   //转化为POP3  
                    if (message != null)
                    {
                        byte[] messageBytes = message.MessageToByte();
                        Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes);

                        if (message.UID == uid)
                        {
                            model.E_EmailId = message.UID;
                            model.E_Email = mime_message.From == null ? " " : mime_message.From[0].DisplayName;
                            model.E_Address = mime_message.From == null ? " " : mime_message.From[0].Address;
                            model.E_Title = mime_message.Subject ?? " ";
                            model.E_EmailTime = mime_message.Date;
                            model.E_Content = mime_message.BodyText ?? " ";
                            MIME_Entity[] attachments = mime_message.GetAttachments(true, true);
                            string Url = string.Empty;
                            int n = 0;
                            foreach (MIME_Entity entity in attachments)
                            {
                                if (entity.ContentDisposition != null)
                                {
                                    string fileName = entity.ContentDisposition.Param_FileName;
                                    if (!string.IsNullOrEmpty(fileName))
                                    {
                                        n += 1;
                                        string pathUrl = "/Upload/Email/" + DateTime.Now.ToString("yyyy") + "" + DateTime.Now.ToString("MM") + "/";   // + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                                        string path = Server.MapPath("..") + pathUrl;
                                        string fileNames = DateTimeConvert.ToTimetag(mime_message.Date) + n + fileName; //重新命名附件

                                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                                        path = Path.Combine(path, fileNames);
                                        MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body;
                                        Stream decodedDataStream = byteObj.GetDataStream();
                                        using (FileStream fs = new FileStream(path, FileMode.Create))
                                        {
                                            LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs, 4000);
                                        }
                                        Url += pathUrl + fileNames + ",";
                                    }
                                }
                            }
                            model.E_AttachmentsUrl = Url.TrimEnd(',');
                            if (!string.IsNullOrEmpty(message.UID))
                            {
                                var listmodel = bll.GetModelList(" E_EmailId='" + message.UID + "'").FirstOrDefault();
                                if (listmodel != null)
                                {
                                    model.E_WorkOrderId = listmodel.E_WorkOrderId;
                                    model.E_IsWorkOrder = listmodel.E_IsWorkOrder;
                                    model.E_IsAudit = listmodel.E_IsAudit;
                                }
                            }
                        }
                    }
                }
            }
            return Success("获取成功", model);
        }

        /// <summary>
        /// 删除邮件信息ById
        /// </summary>
        /// <param name="uid">邮件唯一标识ID</param>
        /// <returns></returns>
        [Authority]
        public ActionResult DelEmailByID(string uid)
        {
            if (string.IsNullOrEmpty(uid))
            {
                return Error("参数为空");
            }
            using (POP3_Client pop3 = new POP3_Client())
            {
                pop3.Connect(Configs.GetValue("Email_Server"), int.Parse(Configs.GetValue("Email_Port")), false);
                pop3.Login(Configs.GetValue("Email_Name"), Configs.GetValue("Email_Password")); //两个参数，前者为Email的账号，后者为Email的密码  

                if (pop3.Messages.Count > 0)
                {
                    foreach (POP3_ClientMessage mail in pop3.Messages)
                    {
                        try
                        {
                            if (uid == mail.UID)
                            {
                                mail.MarkForDeletion();
                                return Success("删除成功");
                            }
                        }
                        catch (Exception ex)
                        {
                            return Error("删除失败");
                        }
                    }
                }
            }
            return Success("删除成功");
        }

        /// <summary>
        /// 邮件审核（0未审核，1已审核）
        /// </summary>
        /// <param name="uid">邮件ID</param>
        /// <returns></returns>
        //[Authority]
        public ActionResult IsAudit(EmailrReceive input)
        {
            BLL.T_Email_EmailMessage_Map bll = new BLL.T_Email_EmailMessage_Map();
            Model.T_Email_EmailMessage_Map model = new Model.T_Email_EmailMessage_Map();
            if (string.IsNullOrEmpty(input.E_EmailId))
            {
                return Error("邮件Id不能为空");
            }
            if (string.IsNullOrEmpty(input.E_Email))
            {
                return Error("邮件不能为空");
            }
            if (string.IsNullOrEmpty(input.E_Title))
            {
                return Error("邮件标题不能为空");
            }
            var listmodel = bll.GetModelList(" E_EmailId='" + input.E_EmailId + "' and E_IsAudit = 1 ").FirstOrDefault();
            if (listmodel == null)
            {
                //邮件未审核 添加              
                //model.E_Id = 0;
                model.E_WorkOrderId = "";
                model.E_EmailId = input.E_EmailId;
                model.E_IsWorkOrder = 0;    //是否已发工单(0未发，1已发)
                model.E_IsAudit = 1;    //0未审核，1已审核
                model.E_SendEmail = input.E_Email;
                model.E_SendName = input.E_Email.Split('@')[0].ToString();
                model.E_Title = input.E_Title;
                model.E_Content = input.E_Content;
                model.E_AttachmentsUrl = input.E_AttachmentsUrl;
                model.E_AddTime = DateTime.Now;
                model.E_EmailTime = input.E_EmailTime;
                model.F_UserId = int.Parse(User.UserData["F_UserID"]);
                model.F_UserName = User.UserData["F_UserCode"];
                int b = bll.Add(model);
                if (b > 0)
                {
                    return Success("审核成功");
                }
                else {
                    return Error("审核失败");
                }
            }
            else {
                //邮件已审核
                return Error("邮件已审核");

            }
        }

        /// <summary>
        /// 添加邮件工单（E_IsWorkOrder 0未创建工单，1已创建工单）
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AddWorkOrderByEmail()
        {
            string emailid = RequestString.GetFormString("emailid");             //邮件id
            int source = RequestString.GetInt("source", 2);             //信息来源(2市长信箱)
            string cusname = RequestString.GetFormString("cusname");    //投诉人姓名
            string cussex = RequestString.GetFormString("cussex");      //投诉人性别
            string cusphone = RequestString.GetFormString("cusphone");  //投诉人电话
            string cusaddress = RequestString.GetFormString("cusaddress");    //投诉人详细地址
            string email = RequestString.GetFormString("email");        //邮箱
            string zipcode = RequestString.GetFormString("zipcode");    //邮编
            string conname = RequestString.GetFormString("conname");    //联系人姓名
            string conphone = RequestString.GetFormString("conphone");  //客户电话
            string title = RequestString.GetFormString("title");        //标题
            string content = RequestString.GetFormString("content");    //内容
            int sourcearea = RequestString.GetInt("sourcearea", 0);      //事发地域id
            string sourceaddress = RequestString.GetFormString("sourceaddress");    //事发详细地址
            string keys = RequestString.GetFormString("keys");          //关键词id(多个用英文逗号, 隔开)
            string splituser = RequestString.GetFormString("splituser");    //分管领导id(多个用英文逗号, 隔开)
            int type = RequestString.GetInt("type", 9);              //类型（9咨询10求助11投诉12建议13表扬14其他）
            int bigtype = RequestString.GetInt("bigtype", 0);        //大类别
            int smalltype = RequestString.GetInt("smalltype", 0);    //小类别
            int isprotect = RequestString.GetInt("isprotect", 0);    //0普通1保密
            int level = RequestString.GetInt("level", 1);            //1普通2紧急3特急
            string filesurl = RequestString.GetFormString("filesurl");        //附件地址（包含多个地址英文","号隔开，不包含ip /Upload/Files/）
            WorkOrderController wo = new WorkOrderController();

            BLL.T_Email_EmailMessage_Map bll = new BLL.T_Email_EmailMessage_Map();
            Model.T_Email_EmailMessage_Map model = new Model.T_Email_EmailMessage_Map();

            if (string.IsNullOrEmpty(emailid))
            {
                return Error("邮件Id不能为空");
            }
            if (string.IsNullOrEmpty(email))
            {
                return Error("邮件不能为空");
            }
            if (string.IsNullOrEmpty(title))
            {
                return Error("标题不能为空");
            }
            //var modelemailid = bll.GetModelList(" E_EmailId='" + emailid + "' and E_IsAudit = 1 AND ISNULL(E_IsWorkOrder,0) = 0 ").FirstOrDefault();
            model = bll.GetModelList(" E_EmailId='" + emailid + "'").FirstOrDefault();
            //邮件关联表 信息存在时修改
            if (model == null)
            {
                return Error("操作失败，请先审核邮件");
            }
            if (model.E_IsAudit == 0)
            {
                return Error("操作失败，请审核邮件");
            }
            if (model.E_IsWorkOrder == 1)
            {
                return Error("操作失败，已提交工单");
            }

            #region 工单附件上传
            string file_string = string.Empty;
            if (!string.IsNullOrEmpty(filesurl))
            {
                //List<Model.T_Sys_Accessories> acs = new List<Model.T_Sys_Accessories>();
                string[] file_arry = filesurl.Trim().Split(',');
                foreach (var item in file_arry)
                {
                    var filetype = item.Substring(item.LastIndexOf("."));   //获取最后/后面的文件名称
                    var filename = item.Substring(item.LastIndexOf("/")).Replace("/", "");   //获取最后/后面的文件名称
                    var model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                    model_T_Sys_Accessories.F_AddTime = DateTime.Now;   //上传时间
                    model_T_Sys_Accessories.F_FileName = filename;          //附件名称
                    model_T_Sys_Accessories.F_FileType = filetype;      //附件类型
                    model_T_Sys_Accessories.F_FileUrl = item;           //附件地址
                    model_T_Sys_Accessories.F_Size = 0;                 
                    model_T_Sys_Accessories.F_UserCode = User.UserData["F_UserCode"]; //上传人  
                    int id = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    if (id > 0)
                        file_string += id + ",";
                }
                file_string = file_string.TrimEnd(',');
            }
            #endregion

            //新增邮件工单信息
            string WorkOrderId = wo.AddWorkOrderBySource(source, cusname, cussex, cusphone, cusaddress, email, zipcode, conname, conphone, title, content, sourcearea, sourceaddress, keys, splituser, type, bigtype, smalltype, isprotect, level, file_string);
            if (string.IsNullOrEmpty(WorkOrderId))
                return Error("操作失败");

            //新增邮件关联表信息
            //model = bll.GetModelList(" E_EmailId='" + emailid + "'").FirstOrDefault();
            model.E_WorkOrderId = WorkOrderId;
            model.E_IsWorkOrder = 1;
            model.E_AddTime = DateTime.Now;
            if (!bll.Update(model))
            {
                return Error("操作失败");
            }

            //新增信息T_Sys_Users关联表
            var modelUsers = new BLL.T_Sys_Users().GetModel(emailid);
            if (modelUsers == null)
            {
                modelUsers = new Model.T_Sys_Users();
                modelUsers.F_OpenId = emailid;
                modelUsers.F_Type = (int)EnumUserType.email;//2;  //F_Type：1微信OpenId;2邮件Id
                modelUsers.F_CreateTime = DateTime.Now;
                new BLL.T_Sys_Users().Add(modelUsers);
            }

            //新增信息T_Sys_Users关联表
            var emailuser = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + emailid + "'  and F_Type=2 ").FirstOrDefault();
            var modelUserWorkOrder = new BLL.T_Bus_UserWorkOrder().GetModel(WorkOrderId);
            if (modelUserWorkOrder == null)
            {
                Model.T_Bus_UserWorkOrder tbu = new Model.T_Bus_UserWorkOrder();
                tbu.F_UserId = emailuser.F_Id;
                tbu.F_WorkOrderId = WorkOrderId;
                new BLL.T_Bus_UserWorkOrder().Add(tbu);
            }

            return Success("操作成功");
        }       

        #endregion

        #region 内部邮件 - 已发送邮件管理

        /// <summary>
        /// 获取所有已发送邮箱
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetAllList()
        {
            DataTable dt = new DataTable();
            string email = HttpUtility.UrlDecode(RequestString.GetQueryString("email"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("strstarttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("strendtime"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            string sql = string.Empty;
            if (email.Trim() != "")
            {
                sql += " and E_ReceiveEmail like '%" + email + "%'";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,E_AddTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,E_AddTime,'" + strendtime + "')>=0   ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                    "T_Email_SendEmail",
                    "E_Id",
                    "*",
                    sql,
                    "ORDER BY E_Id desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取一条详细信息
        /// </summary>
        /// <param name="infoid"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetInfo(string infoid)
        {
            if (infoid != null && infoid.Trim() != "")
            {
                Model.T_Email_SendEmail model = bllEmail.GetModel(int.Parse(infoid.Trim()));
                if (model != null)
                {
                    return Success("获取成功", model);
                }
                else
                {
                    return Error("获取失败");
                };
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 删除已发送管理 邮箱
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult DelSendEmail(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                if (bllEmail.DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                    return Error("删除失败");
            }
            else
            {
                return Error("获取参数失败");
            }
        }
        #endregion

    }
}