using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Common;
using CallCenterApi.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    public class thirdController : BaseController
    {

       

        private information.InternalMessagesController msg = new information.InternalMessagesController();

        private BLL.T_Sys_UserAccount userBLL = new BLL.T_Sys_UserAccount();

        private BLL.T_Bus_WorkOrder workorderBLL = new BLL.T_Bus_WorkOrder();
        private BLL.T_Bus_AssignedInfo assignBLL = new BLL.T_Bus_AssignedInfo();
        private BLL.T_Bus_AssignedItemInfo assignItemBLL = new BLL.T_Bus_AssignedItemInfo();
        private BLL.T_Bus_Operation operBLL = new BLL.T_Bus_Operation();
        private BLL.T_Sys_SystemConfig configBll = new BLL.T_Sys_SystemConfig();
        private BLL.T_Bus_RemindRecord remindBLL = new BLL.T_Bus_RemindRecord();
        private BLL.T_Bus_Feedback feedbackBLL = new BLL.T_Bus_Feedback();

        //http://218.29.107.66:9999
        string thirdUrl = Configs.GetValue("thirdUrl");
      
        
        /// <summary>
        /// NameValueCollection 转换为json格式
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IDictionary<string, string> NameVlueToDictionary(NameValueCollection source)
        {
            return source.AllKeys.ToDictionary(k => k, k => source[k]);
        }
        public class Login
        {
            public string code { set; get; }
            public string token { set; get; }
            public string msg { set; get; }
            public string cUserName { set; get; }
            public string cName { set; get; }
            public string gh { set; get; }
            public string curUnitCode { set; get; }
        }
        private string token = "", curUnitCode="";
        public ActionResult Log()
        {
            NameValueCollection log = new NameValueCollection();
            log.Add("Clieng_Id", "gy02");
            log.Add("Client_secret", "000000");
            var keyDict = NameVlueToDictionary(log);
            string strJSON = JsonConvert.SerializeObject(keyDict);
            NameValueCollection values = new NameValueCollection();
            values.Add("jsonStr", strJSON);
            var url = $"{thirdUrl}/api/dock/login";
            try
            {
                string ret = HttpPostMultipartFormData(url, values);
                Login login = JsonConvert.DeserializeObject<Login>(ret);
                token = login.token;
                curUnitCode = login.curUnitCode;
                return Success (token); 
            }
            catch (Exception e)
            {
                return Success(e.Message );
            }
        }

        public string  Logins()
        {
            NameValueCollection log = new NameValueCollection();
            log.Add("Clieng_Id", "gy02");
            log.Add("Client_secret", "000000");
            var keyDict = NameVlueToDictionary(log);
            string strJSON = JsonConvert.SerializeObject(keyDict);
            NameValueCollection values = new NameValueCollection();
            values.Add("jsonStr", strJSON);
            var url = $"{thirdUrl}/api/dock/login";
            try
            {
                string ret = HttpPostMultipartFormData(url, values);
                Login login = JsonConvert.DeserializeObject<Login>(ret);
                token = login.token;
                curUnitCode = login.curUnitCode;
                return token;
            }
            catch (Exception e)
            {
                return "";
            }
        }

        public class didAddWorders
        {   /// <summary>
            /// 案件id(int)
            /// </summary>
            public int problemCode { set; get; }
            /// <summary>
            /// 标题
            /// </summary>
            public string  problemTitle { set; get; }
            /// <summary>
            /// 类别(varchar)
            /// </summary>
            public string problemType { set; get; }
            /// <summary>
            /// 类别(varchar)
            /// </summary>
            public string problemSmallType { set; get; }
            /// <summary>
            /// 类别(varchar)经纬度（lng,lat）,由逗号间隔
            /// </summary>
            public string problemLocation { set; get; }
            /// <summary>
            ///诉求方式(varchar)（电话，手机采集也就是app，人民网，省平台交办）
            /// </summary>
            public string problemWay { set; get; }
            /// <summary>
            /// 诉求类别
            /// </summary>
            public string ptype { set; get; }
            /// <summary>
            ///内容描述   类型为text
            /// </summary>
            public string problemDescription { set; get; }
            /// <summary>
            ///详细地址 varchar(100)
            /// </summary>
            public string problemSite { set; get; }
            /// <summary>
            ///限定期限（年月日时分秒格式）
            /// </summary>
            public string timeLimit { set; get; }
            /// <summary>
            ///来电人(varchar)
            /// </summary>
            public string reporter { set; get; }
            /// <summary>
            ///来电人手机号码(varchar)
            /// </summary>
            public string reporterContactInfo { set; get; }
            /// <summary>
            ///来电时间（年月日时分秒格式）
            /// </summary>
            public string reportTime { set; get; }
            /// <summary>
            ///登记人(varchar)
            /// </summary>
            public string forwarder { set; get; }
            /// <summary>
            ///登记日期（年月日时分秒格式）
            /// </summary>
            public string forwardTime { set; get; }
            /// <summary>
            /// 三级单位编码（可由此判断是否为一旦直达三级）
            /// </summary>
            public string threeunitid { set; get; }
            /// <summary>
            ///案件编码（热线系统的案件编码，varchar）
            /// </summary>
            public string code { set; get; }
            /// <summary>
            ///转办记录唯一id（int）
            /// </summary>
            public int  did { set; get; }
            /// <summary>
            /// 四级分类编码
            /// </summary>
            public string fourClassification { set; get; }
        }
        private information.InternalMessagesController InternalMessages = new information.InternalMessagesController();
        /// <summary>
        /// 催单
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult Reminders(string code,string msg)
        {
          
                var workorder = workorderBLL.GetModelList("F_OldWorkOrderId='" +
                         code + "'" +
                         "and F_IsDelete=0");
                var user = new BLL.T_Sys_UserAccount().GetModelList("F_RoleId=6 and F_DeleteFlag=0");
                if (user != null)
                {
                    foreach (var item in user)
                    {
                        InternalMessages.AddInternalMessagesInfo
                            ("催单消息", "工单" + workorder.FirstOrDefault ().F_WorkOrderId  + "收到郑州市催办，请及时处理！", 
                            item.F_UserCode, "郑州市", (int)EnumSmsType.additional);
                    }
                    workorder.FirstOrDefault().ReminderNum += 1;
                    bool t = new BLL.T_Bus_WorkOrder().Update(workorder.FirstOrDefault());
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = workorder.FirstOrDefault().F_WorkOrderId;
                    oper.F_State = workorder.FirstOrDefault().F_WorkState;

                    string userinfo = "郑州市";
                    oper.F_Message = userinfo + " 催办工单";
                    oper.F_CreateUser = "郑州市";
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    #endregion
                }

            return Success("操作成功");
        }
        /// <summary>
        /// 服务工单交办接口
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult pushcase(didAddWorders info)
        {
            if (info == null)
                return Error("内容为空");
            try
            {
                LogFactory.GetLogger("1123").Warn(info.ToJson());
                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存工单信息

                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();

                    modelT_Bus_WorkOrder.F_OldWorkOrderId = info.code;
                    var workorder = workorderBLL.GetModelList("F_OldWorkOrderId='" +
                        modelT_Bus_WorkOrder.F_OldWorkOrderId + "'" +
                        "and F_IsDelete=0");
                    if (workorder != null && workorder.Count > 0)
                    {
                        return Error("工单已交办");
                    }
                    else
                    {
                        modelT_Bus_WorkOrder.F_WorkState = 1;
                        modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID("8000");
                    }
                    modelT_Bus_WorkOrder.F_InfoConBigType = 1;
                    //if (info.ideliverprogress == 11)
                    //    modelT_Bus_WorkOrder.F_Backreason = info.backreason;
                    modelT_Bus_WorkOrder.F_Caseid = info.problemCode;
                    modelT_Bus_WorkOrder.F_InfoSource = 2;//信息来源
                    if (info.problemType == "信箱案件承办")
                        modelT_Bus_WorkOrder.F_InfoSource = 2;//信息来源
                    else if (info.problemType == "APP")
                        modelT_Bus_WorkOrder.F_InfoSource = 89;//信息来源
                    else
                        modelT_Bus_WorkOrder.F_InfoSource = 3;//信息来源
                    try
                    {
                        modelT_Bus_WorkOrder.F_InfoConSmallType = int.Parse
                    (DbHelperSQL.GetSingle($"select[dbo].[GetDictionaryID]('{ info.problemSmallType}')").ToString());
                    }
                    catch
                    {

                    }
                    modelT_Bus_WorkOrder.F_Files = "";
                    if (!string.IsNullOrEmpty(info.problemLocation))
                        modelT_Bus_WorkOrder.F_Longitude  = decimal   .Parse(info.problemLocation.Split(',')[0]);
                    if (!string .IsNullOrEmpty (info.problemLocation))
                    modelT_Bus_WorkOrder.F_Latitude = decimal.Parse ( info.problemLocation.Split(',')[1]);
                    try
                    {
                        modelT_Bus_WorkOrder.F_Mode = int.Parse
                        (DbHelperSQL.GetSingle($"select[dbo].[GetDictionaryID]('{ info.ptype}')").ToString());
                    }
                    catch
                    {

                    }
                   if (!string .IsNullOrEmpty(info.timeLimit))
                    modelT_Bus_WorkOrder.F_LimitTime =Convert .ToDateTime ( info.timeLimit);
                    modelT_Bus_WorkOrder.requirementFinishDay = info.timeLimit;
                    modelT_Bus_WorkOrder.F_CusAddress = info.problemSite;
                    modelT_Bus_WorkOrder.F_CusName = info.reporter;
                   // modelT_Bus_WorkOrder.F_NewRemarks = info.workorderremark;
                    modelT_Bus_WorkOrder.F_ConName = info.reporter; ;//联系人姓名
                    modelT_Bus_WorkOrder.F_CusPhone = info.reporterContactInfo;//
                    modelT_Bus_WorkOrder.F_ConPhone = info.reporterContactInfo;//联系人
                    try
                    {
                        modelT_Bus_WorkOrder.F_CreateTime = DateTime.Parse(info.forwardTime);
                    }
                    catch
                    {
                        modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;
                    }
                  //  modelT_Bus_WorkOrder.F_Event = info.ismallcategory;//事件类别
                    modelT_Bus_WorkOrder.F_Transferor = info.forwarder;//转办人
                    modelT_Bus_WorkOrder.F_TransferTime = DateTime.Now;
                    modelT_Bus_WorkOrder.F_ComTitle = info.problemTitle;
                   // modelT_Bus_WorkOrder.F_Transferunit = info.transferunit;//转办单位
                    modelT_Bus_WorkOrder.F_ComContent = info.problemDescription;//
                    modelT_Bus_WorkOrder.F_Did = info.did;
                   // modelT_Bus_WorkOrder.F_ResultRemarks = info.advice;//拟办意见
                    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfos = new Model.T_Bus_AssignedInfo();
                    //if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_ResultRemarks))
                    //{

                    //    try
                    //    {
                    //        string[] limtim = modelT_Bus_WorkOrder.F_ResultRemarks.Split('于', '月', '日', '前');
                    //        DateTime limittime = DateTime.Parse(DateTime.Now.ToString("yyyy") + "年" + limtim[1] + "月" + limtim[2] + "日" + " 23:59:59");
                    //        if (limittime < DateTime.Now && limittime.Month == 1)
                    //        {
                    //            limittime = limittime.AddYears(1);
                    //        }
                    //        modelT_Bus_WorkOrder.F_LimitTime = limittime;
                    //    }
                    //    catch
                    //    {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
                    //    }
                    //}
                   // modelT_Bus_WorkOrder.F_FinalOpinion = info.result;//处理结果
                  //  modelT_Bus_WorkOrder.F_Result = info.remark;//回访情况
                    modelT_Bus_WorkOrder.F_Remarks = "★以上登记信息仅供市长热线平台及承办人员查阅，未经许可不得向外提供";//
                    modelT_Bus_WorkOrder.F_IsDelete = 0;
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;
                    string msgss = "";
                    try
                    {
                        if (!string.IsNullOrEmpty(info.threeunitid) && info.threeunitid != "null")
                        {
                            var deptList =
                            new BLL.T_Sys_Department().GetModelList($"F_DeptNameSpell= '{info.threeunitid}'"); ;
                            if (deptList != null && deptList.Count() > 0)
                            {
                                var dept = deptList.FirstOrDefault();
                                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                                modelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                DateTime limittime = DateTime.Now;
                                try
                                {
                                    limittime = DateTime.Parse(info.timeLimit);
                                }
                                catch
                                {
                                    LogFactory.GetLogger("1123").Error(info.code + "限定期限错误");
                                    return Error("限定期限错误");
                                }
                                modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                modelT_Bus_AssignedInfo.F_MainDeptId = dept.F_DeptId;//主办单位id
                                modelT_Bus_AssignedInfo.F_OtherDeptIds = "";//协办单位id
                                modelT_Bus_AssignedInfo.F_AssignedOpinion = "郑州市交办";//交办意见
                                modelT_Bus_AssignedInfo.F_State = 1;//0草稿  1正式
                                modelT_Bus_AssignedInfo.F_CreateUser = "8000";
                                modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                modelT_Bus_AssignedInfo.F_IsDelete = 0;
                                modelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                modelT_Bus_AssignedInfo.F_IsSure = 0;
                                modelT_Bus_AssignedInfo.F_IsReload = 0;
                                modelT_Bus_AssignedInfo.F_IsNext = 0;
                                modelT_Bus_AssignedInfo.F_TimeResp = assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                                int aid = assignBLL.Add(modelT_Bus_AssignedInfo);
                                if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_State == 1)
                                {
                                    #region 保存工单信息
                                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.receive;//待查收
                                    modelT_Bus_WorkOrder.F_LimitTime = limittime;
                                    modelT_Bus_WorkOrder.F_Scanning = limittime.AddDays(3);
                                    modelT_Bus_WorkOrder.F_MainDeptId = dept.F_DeptId;
                                    modelT_Bus_WorkOrder.F_IsEnabled = 2;

                                    modelT_Bus_WorkOrder.F_OtherDeptIds = "";
                                    modelT_Bus_WorkOrder.F_AssignUser = "8000";
                                    modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;
                                    workorderBLL.Update(modelT_Bus_WorkOrder);
                                    #endregion

                                    #region 删除草稿信息
                                    var cglist = assignBLL.GetModelList(" F_IsDelete=0 and F_State=0 " +
                                        "and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'");

                                    foreach (var cg in cglist)
                                    {
                                        cg.F_IsDelete = 1;
                                        cg.F_DeleteUser = "8000";
                                        cg.F_DeleteTime = DateTime.Now;

                                        assignBLL.Update(cg);
                                    }
                                    #endregion

                                    #region 插入操作记录
                                    msgss = "郑州市" + " 交办了工单，主办单位：" + dept.F_DeptName;



                                    //推送消息表
                                    var users = userBLL.GetModelList(" F_DeptId='" + dept.F_DeptId + "' ");

                                    foreach (var u in users)
                                    {
                                        msg.AddInternalMessagesInfo("工单消息", msgss + "，工单编号：" +
                                            modelT_Bus_WorkOrder.F_WorkOrderId, u.F_UserCode, "8000", (int)EnumSmsType.workorder);
                                        if (!string.IsNullOrEmpty(u.F_Mobile))
                                        {
                                            string count = "你有新的工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                            //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                            //bool n = new SMSController().AddSmS(1963450, 133, count, mag, u.F_Mobile);
                                            string mag = "[\"" + modelT_Bus_WorkOrder.F_WorkOrderId + "\"]";
                                            string v = SMSNewController.AddSmS(133, count, u.F_Mobile, "1132299838815801344", mag, modelT_Bus_WorkOrder.F_WorkOrderId);

                                        }
                                        if (!string.IsNullOrEmpty(u.F_Telephone))
                                        {
                                            var userlist = u.F_Telephone.Split(',');
                                            if (userlist != null)
                                            {

                                                foreach (string item in userlist)
                                                {
                                                    string count = "你有新的工单，工单号" + modelT_Bus_WorkOrder.
                                                  F_WorkOrderId + ",请及时查收。";
                                                    //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                                    //bool n = new SMSController().AddSmSGroup(1963450, 133,
                                                    //    count, mag, userlist, u.F_Telephone);
                                                    string mag = "[\"" + modelT_Bus_WorkOrder.F_WorkOrderId + "\"]";
                                                    string v = SMSNewController.AddSmS(133, count, item, "1132299838815801344", mag, modelT_Bus_WorkOrder.F_WorkOrderId);
                                                }

                                                //string count = "你有新的工单，工单号" + modelT_Bus_WorkOrder.
                                                //    F_WorkOrderId + ",请及时查收。";
                                                ////string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                                ////bool n = new SMSController().AddSmSGroup(1963450, 133,
                                                ////    count, mag, userlist, u.F_Telephone);
                                                //string mag = "[\"" + modelT_Bus_WorkOrder.F_WorkOrderId + "\"]";
                                                //string v = SMSNewController.AddSmS(133, count, u.F_Telephone, "1132299838815801344", mag, modelT_Bus_WorkOrder.F_WorkOrderId);

                                            }

}
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                    catch
                    {

                    }


                    if (modelT_Bus_WorkOrder.F_Id > 0)
                    {
                        workorderBLL.Update(modelT_Bus_WorkOrder);

                       
                    }
                    else
                    {

                        // BLL.T_Bus_WorkOrderNew newbll = new BLL.T_Bus_WorkOrderNew();
                        // Model.T_Bus_WorkOrder model = new T_Bus_WorkOrder();
                        // model = modelT_Bus_WorkOrder;
                        //// model.F_ComTitle= info.title;
                        // newbll.Add(model);

                        // modelT_Bus_WorkOrder.F_ComTitle = "";
                        workorderBLL.Add(modelT_Bus_WorkOrder);
                        updateYJProgress(modelT_Bus_WorkOrder.F_WorkOrderId);

                    }
                    #endregion
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = "郑州市系统";
                    if (modelT_Bus_WorkOrder.F_WorkState == 0 || modelT_Bus_WorkOrder.F_WorkState == 1)
                    {
                        oper.F_Message = userinfo + " 登记了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    else if (modelT_Bus_WorkOrder.F_WorkState ==2)
                    {
                        oper.F_Message = msgss ;
                    }
                    else
                    {
                        oper.F_Message = userinfo + " 提交重办了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    oper.F_CreateUser = info .forwarder;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            catch (Exception ex)
            {
                return Error("操作失败" + ex.Message);
            }
        }


        /// <summary>
        /// 服务工单交办接口
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult pushcase1()
        {
            StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
            var postString = reader.ReadToEnd();
            JObject paras = null;
            paras = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(postString);
            
            var info = Newtonsoft.Json.JsonConvert.DeserializeObject<didAddWorders>(paras.ToJson ());


            if (info == null)
                return Error("内容为空");
            try
            {
                LogFactory.GetLogger("1123").Warn(info.ToJson());
                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存工单信息

                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();

                    modelT_Bus_WorkOrder.F_OldWorkOrderId = info.code;
                    var workorder = workorderBLL.GetModelList("F_OldWorkOrderId='" +
                        modelT_Bus_WorkOrder.F_OldWorkOrderId + "'" +
                        "and F_IsDelete=0");
                    if (workorder != null && workorder.Count > 0)
                    {
                        return Error("工单已交办");
                    }
                    else
                    {
                        modelT_Bus_WorkOrder.F_WorkState = 1;
                        modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID("8000");
                    }
                    modelT_Bus_WorkOrder.F_InfoConBigType = 1;
                    //if (info.ideliverprogress == 11)
                    //    modelT_Bus_WorkOrder.F_Backreason = info.backreason;
                    modelT_Bus_WorkOrder.F_Caseid = info.problemCode;
                    modelT_Bus_WorkOrder.F_InfoSource = 2;//信息来源
                    if (info.problemType == "信箱案件承办")
                        modelT_Bus_WorkOrder.F_InfoSource = 2;//信息来源
                    else if (info.problemType == "APP")
                        modelT_Bus_WorkOrder.F_InfoSource = 89;//信息来源
                    else
                        modelT_Bus_WorkOrder.F_InfoSource = 3;//信息来源
                    try
                    {
                        modelT_Bus_WorkOrder.F_InfoConSmallType = int.Parse
                    (DbHelperSQL.GetSingle($"select[dbo].[GetDictionaryID]('{ info.problemSmallType}')").ToString());
                    }
                    catch
                    {

                    }
                    modelT_Bus_WorkOrder.F_Files = "";
                    if (!string.IsNullOrEmpty(info.problemLocation))
                        modelT_Bus_WorkOrder.F_Longitude = decimal.Parse(info.problemLocation.Split(',')[0]);
                    if (!string.IsNullOrEmpty(info.problemLocation))
                        modelT_Bus_WorkOrder.F_Latitude = decimal.Parse(info.problemLocation.Split(',')[1]);
                    try
                    {
                        modelT_Bus_WorkOrder.F_Mode = int.Parse
                        (DbHelperSQL.GetSingle($"select[dbo].[GetDictionaryID]('{ info.ptype}')").ToString());
                    }
                    catch
                    {

                    }
                    if (!string.IsNullOrEmpty(info.timeLimit))
                        modelT_Bus_WorkOrder.F_LimitTime = Convert.ToDateTime(info.timeLimit);
                    modelT_Bus_WorkOrder.requirementFinishDay = info.timeLimit;
                    modelT_Bus_WorkOrder.F_CusAddress = info.problemSite;
                    modelT_Bus_WorkOrder.F_CusName = info.reporter;
                    // modelT_Bus_WorkOrder.F_NewRemarks = info.workorderremark;
                    modelT_Bus_WorkOrder.F_ConName = info.reporter; ;//联系人姓名
                    modelT_Bus_WorkOrder.F_CusPhone = info.reporterContactInfo;//
                    modelT_Bus_WorkOrder.F_ConPhone = info.reporterContactInfo;//联系人
                    try
                    {
                        modelT_Bus_WorkOrder.F_CreateTime = DateTime.Parse(info.forwardTime);
                    }
                    catch
                    {
                        modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;
                    }
                    //  modelT_Bus_WorkOrder.F_Event = info.ismallcategory;//事件类别
                    modelT_Bus_WorkOrder.F_Transferor = info.forwarder;//转办人
                    modelT_Bus_WorkOrder.F_TransferTime = DateTime.Now;
                    modelT_Bus_WorkOrder.F_ComTitle = info.problemTitle;
                    // modelT_Bus_WorkOrder.F_Transferunit = info.transferunit;//转办单位
                    modelT_Bus_WorkOrder.F_ComContent = info.problemDescription;//
                    modelT_Bus_WorkOrder.F_Did = info.did;
                    // modelT_Bus_WorkOrder.F_ResultRemarks = info.advice;//拟办意见
                    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfos = new Model.T_Bus_AssignedInfo();
                   
                    modelT_Bus_WorkOrder.F_Remarks = "★以上登记信息仅供市长热线平台及承办人员查阅，未经许可不得向外提供";//
                    modelT_Bus_WorkOrder.F_IsDelete = 0;
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;
                    string msgss = "";
                    try
                    {
                        if (!string.IsNullOrEmpty(info.threeunitid) && info.threeunitid != "null")
                        {
                            var deptList =
                            new BLL.T_Sys_Department().GetModelList($"F_DeptNameSpell= '{info.threeunitid}'"); ;
                            if (deptList != null && deptList.Count() > 0)
                            {
                                var dept = deptList.FirstOrDefault();
                                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                                modelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                DateTime limittime = DateTime.Now;
                                try
                                {
                                    limittime = DateTime.Parse(info.timeLimit);
                                }
                                catch
                                {
                                    LogFactory.GetLogger("1123").Error(info.code + "限定期限错误");
                                    return Error("限定期限错误");
                                }
                                modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                modelT_Bus_AssignedInfo.F_MainDeptId = dept.F_DeptId;//主办单位id
                                modelT_Bus_AssignedInfo.F_OtherDeptIds = "";//协办单位id
                                modelT_Bus_AssignedInfo.F_AssignedOpinion = "郑州市交办";//交办意见
                                modelT_Bus_AssignedInfo.F_State = 1;//0草稿  1正式
                                modelT_Bus_AssignedInfo.F_CreateUser = "8000";
                                modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                modelT_Bus_AssignedInfo.F_IsDelete = 0;
                                modelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                modelT_Bus_AssignedInfo.F_IsSure = 0;
                                modelT_Bus_AssignedInfo.F_IsReload = 0;
                                modelT_Bus_AssignedInfo.F_IsNext = 0;
                                modelT_Bus_AssignedInfo.F_TimeResp = assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                                int aid = assignBLL.Add(modelT_Bus_AssignedInfo);
                                if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_State == 1)
                                {
                                    #region 保存工单信息
                                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.receive;//待查收
                                    modelT_Bus_WorkOrder.F_LimitTime = limittime;
                                    modelT_Bus_WorkOrder.F_Scanning = limittime.AddDays(3);
                                    modelT_Bus_WorkOrder.F_MainDeptId = dept.F_DeptId;
                                    modelT_Bus_WorkOrder.F_IsEnabled = 2;

                                    modelT_Bus_WorkOrder.F_OtherDeptIds = "";
                                    modelT_Bus_WorkOrder.F_AssignUser = "8000";
                                    modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;
                                    workorderBLL.Update(modelT_Bus_WorkOrder);
                                    #endregion

                                    #region 删除草稿信息
                                    var cglist = assignBLL.GetModelList(" F_IsDelete=0 and F_State=0 " +
                                        "and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'");

                                    foreach (var cg in cglist)
                                    {
                                        cg.F_IsDelete = 1;
                                        cg.F_DeleteUser = "8000";
                                        cg.F_DeleteTime = DateTime.Now;

                                        assignBLL.Update(cg);
                                    }
                                    #endregion

                                    #region 插入操作记录
                                    msgss = "郑州市" + " 交办了工单，主办单位：" + dept.F_DeptName;



                                    //推送消息表
                                    var users = userBLL.GetModelList(" F_DeptId='" + dept.F_DeptId + "' ");

                                    foreach (var u in users)
                                    {
                                        msg.AddInternalMessagesInfo("工单消息", msgss + "，工单编号：" +
                                            modelT_Bus_WorkOrder.F_WorkOrderId, u.F_UserCode, "8000", (int)EnumSmsType.workorder);
                                        if (!string.IsNullOrEmpty(u.F_Mobile))
                                        {
                                            string count = "你有新的工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                            //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                            //bool n = new SMSController().AddSmS(1963450, 133, count, mag, u.F_Mobile);

                                            string mag = "[\"" + modelT_Bus_WorkOrder.F_WorkOrderId + "\"]";
                                            string v = SMSNewController.AddSmS(133, count, u.F_Mobile, "1132299838815801344", mag, modelT_Bus_WorkOrder.F_WorkOrderId);
                                        }
                                        if (!string.IsNullOrEmpty(u.F_Telephone))
                                        {
                                            var userlist = u.F_Telephone.Split(',');
                                            if (userlist != null)
                                            {
                                                string count = "你有新的工单，工单号" + modelT_Bus_WorkOrder.
                                                    F_WorkOrderId + ",请及时查收。";
                                                //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                                //bool n = new SMSController().AddSmSGroup(1963450, 133,
                                                //    count, mag, userlist, u.F_Telephone);
                                                string mag = "[\"" + modelT_Bus_WorkOrder.F_WorkOrderId + "\"]";
                                                string v = SMSNewController.AddSmS(133, count, u.F_Telephone, "1132299838815801344", mag, modelT_Bus_WorkOrder.F_WorkOrderId);  
                                            }

                                        }
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                    catch
                    {

                    }


                    if (modelT_Bus_WorkOrder.F_Id > 0)
                    {
                        workorderBLL.Update(modelT_Bus_WorkOrder);


                    }
                    else
                    {

                        // BLL.T_Bus_WorkOrderNew newbll = new BLL.T_Bus_WorkOrderNew();
                        // Model.T_Bus_WorkOrder model = new T_Bus_WorkOrder();
                        // model = modelT_Bus_WorkOrder;
                        //// model.F_ComTitle= info.title;
                        // newbll.Add(model);

                        // modelT_Bus_WorkOrder.F_ComTitle = "";
                        workorderBLL.Add(modelT_Bus_WorkOrder);
                        updateYJProgress(modelT_Bus_WorkOrder.F_WorkOrderId);

                    }
                    #endregion
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = "郑州市系统";
                    if (modelT_Bus_WorkOrder.F_WorkState == 0 || modelT_Bus_WorkOrder.F_WorkState == 1)
                    {
                        oper.F_Message = userinfo + " 登记了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    else if (modelT_Bus_WorkOrder.F_WorkState == 2)
                    {
                        oper.F_Message = msgss;
                    }
                    else
                    {
                        oper.F_Message = userinfo + " 提交重办了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    oper.F_CreateUser = info.forwarder;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            catch (Exception ex)
            {
                return Error("操作失败" + ex.Message);
            }
        }
        public class eidAddWorders
        {   /// <summary>
            /// 案件id(int)
            /// </summary>
            public int eid { set; get; }
            /// <summary>
            /// 标题
            /// </summary>
            public string title { set; get; }
           
          
          
            /// <summary>
            ///内容描述   类型为text
            /// </summary>
            public string content { set; get; }
      
            /// <summary>
            ///限定期限（年月日时分秒格式）
            /// </summary>
            public string requirementFinishDay { set; get; }
            /// <summary>
            ///来电人(varchar)
            /// </summary>
            public string caller { set; get; }
            /// <summary>
            ///来电人手机号码(varchar)
            /// </summary>
            public string callerPhone { set; get; }
            /// <summary>
            ///来电时间（年月日时分秒格式）
            /// </summary>
            public string registerTime { set; get; }
            /// <summary>
            ///登记人(varchar)
            /// </summary>
            public string forwarder { set; get; }
            /// <summary>
            /// 单位编码（varchar）
            /// </summary>
            public string unitCode { set; get; }
            /// <summary>
            ///登记日期（年月日时分秒格式）
            /// </summary>
            public string forwardTime { set; get; }
            /// <summary>
            ///案件编码（热线系统的案件编码，varchar）
            /// </summary>
            public string code { set; get; }
            /// <summary>
            /// 转办时间（年月日时分秒格式）
            /// </summary>
            public string operationTime { set; get; }
            /// <summary>
            ///转办记录唯一id（int）
            /// </summary>
            public int did { set; get; }
        }
        /// <summary>
        /// 即办工单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult transferSend(eidAddWorders info)
        {
            if (info == null)
                return Error("内容为空");
            try
            {
                LogFactory.GetLogger("1123").Warn(info.ToJson());
                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存工单信息

                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
                    modelT_Bus_WorkOrder.F_OldWorkOrderId = info.code;
                    var workorder = workorderBLL.GetModelList("F_OldWorkOrderId='" +
                        modelT_Bus_WorkOrder.F_OldWorkOrderId + "'" +
                        "and F_IsDelete=0");
                    if (workorder != null && workorder.Count > 0)
                    {
                        return Error("工单已交办");
                    }
                    else
                    {
                        modelT_Bus_WorkOrder.F_WorkState = 1;
                        modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID("8000");
                    }
                    modelT_Bus_WorkOrder.F_Files = "";
                    modelT_Bus_WorkOrder.F_InfoConBigType = 0;
                    modelT_Bus_WorkOrder.F_Caseid = info.eid;
                    modelT_Bus_WorkOrder.F_InfoSource = 1;//信息来源
                    modelT_Bus_WorkOrder.F_NoticeDeptIds = info.unitCode;
                    modelT_Bus_WorkOrder.F_LimitTime = Convert.ToDateTime(info.requirementFinishDay);
                    modelT_Bus_WorkOrder.requirementFinishDay = info.requirementFinishDay;
                    modelT_Bus_WorkOrder.F_CusName = info.caller;
                    modelT_Bus_WorkOrder.F_ConName = info.caller; ;//联系人姓名
                    modelT_Bus_WorkOrder.F_CusPhone = info.callerPhone;//
                    modelT_Bus_WorkOrder.F_ConPhone = info.callerPhone;//联系人
                    try
                    {
                        modelT_Bus_WorkOrder.F_CreateTime = DateTime.Parse(info.forwardTime);
                    }
                    catch
                    {
                        modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;
                    }
                    modelT_Bus_WorkOrder.F_Transferor = info.forwarder;//转办人
                    modelT_Bus_WorkOrder.F_TransferTime = Convert.ToDateTime(info.operationTime);
                    modelT_Bus_WorkOrder.F_ComTitle = info.title;
                    modelT_Bus_WorkOrder.F_ComContent = info.content;//
                    modelT_Bus_WorkOrder.F_Did = info.did;
                    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfos = new Model.T_Bus_AssignedInfo();
                    modelT_Bus_WorkOrder.F_Remarks = "★以上登记信息仅供市长热线平台及承办人员查阅，未经许可不得向外提供";//
                    modelT_Bus_WorkOrder.F_IsDelete = 0;
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;

                    if (modelT_Bus_WorkOrder.F_Id > 0)
                    {
                        workorderBLL.Update(modelT_Bus_WorkOrder);
                        updateYJProgress(modelT_Bus_WorkOrder.F_WorkOrderId);
                    }
                    else
                    {
                        workorderBLL.Add(modelT_Bus_WorkOrder);
                    }
                    #endregion
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = "郑州市系统";
                    if (modelT_Bus_WorkOrder.F_WorkState == 0 || modelT_Bus_WorkOrder.F_WorkState == 1)
                    {
                        oper.F_Message = userinfo + " 登记了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    else
                    {
                        oper.F_Message = userinfo + " 提交重办了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    oper.F_CreateUser = info.forwarder;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            catch (Exception ex)
            {
                return Error("操作失败" + ex.Message);
            }
        }
        public class returnvalue
        {
            public string code { set; get; }
            public string msg { set; get; }
        }
        public class returnvalue1
        {
            public string code { set; get; }
            public string message { set; get; }
        }
        /// <summary>
        /// 服务工单受理
        /// </summary>
        /// <returns></returns>
        public string updateProgress(string workorderid)
        {
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);

            if (modelT_Bus_WorkOrder != null )
            {
                
                    var dept =
                     new BLL.T_Sys_Department().GetModel (modelT_Bus_WorkOrder.F_MainDeptId.Value  ) ;
                          NameValueCollection log = new NameValueCollection();
                            log.Add("token", Logins());
                            log.Add("did", modelT_Bus_WorkOrder.F_Caseid.ToString());
                            log.Add("curUnitCode", dept.F_DeptNameSpell);
                            var keyDict = NameVlueToDictionary(log);
                            string strJSON = JsonConvert.SerializeObject(keyDict);
                            NameValueCollection values = new NameValueCollection();
                            values.Add("jsonStr", strJSON);
                            var url = $"{thirdUrl}/api/dockthree/updateProgress";
                            try
                            {
                                string ret = HttpPostMultipartFormData(url, values);
                                returnvalue1 jo = JsonConvert.DeserializeObject<returnvalue1>(ret);
                                if (jo.code != "0")
                                    return jo.message ;
                            }
                            catch (Exception e)
                            {
                                LogFactory.GetLogger("受理").Error(e.Message);
                                return e.Message;
                            }
                       
                    return "";
            }
            else
            {
                return "该工单不存在";
            }

        }


        /// <summary>
        /// 服务工单受理
        /// </summary>
        /// <returns></returns>
        public string updateYJProgress(string workorderid)
        {
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);

            if (modelT_Bus_WorkOrder != null)
            {
                NameValueCollection log = new NameValueCollection();
                log.Add("token", Logins());
                log.Add("did", modelT_Bus_WorkOrder.F_Caseid.ToString());
                log.Add("curUnitCode", curUnitCode);
                var keyDict = NameVlueToDictionary(log);
                string strJSON = JsonConvert.SerializeObject(keyDict);
                NameValueCollection values = new NameValueCollection();
                values.Add("jsonStr", strJSON);
                var url = $"{thirdUrl}/api/dock/updateProgress";
                try
                {
                    string ret = HttpPostMultipartFormData(url, values);
                    returnvalue1 jo = JsonConvert.DeserializeObject<returnvalue1>(ret);
                    if (jo.code != "0")
                        return jo.message;
                }
                catch (Exception e)
                {
                    LogFactory.GetLogger("受理").Error(e.Message);
                    return e.Message;
                }

                return "";
            }
            else
            {
                return "该工单不存在";
            }

        }
        /// <summary>
        /// 申请延时
        /// </summary>
        /// <returns></returns>
        public string DWDelayWorkOrder(string workorderid, 
            string reason, string files, DateTime newlimittime, DateTime OldTime)
        {
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

            if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null)
            {

                if (modelT_Bus_AssignedInfo.F_IsSure == 1)
                {
                 
                        string F_DeptNameSpell = curUnitCode;
                        if (modelT_Bus_WorkOrder.F_MainDeptId > 0)
                        {
                            var dept =
                      new BLL.T_Sys_Department().GetModel(modelT_Bus_WorkOrder.F_MainDeptId.Value);
                            F_DeptNameSpell = dept.F_DeptNameSpell;
                        }
                        string token = Logins();
                        NameValueCollection log = new NameValueCollection();
                        log.Add("token", token);
                        log.Add("did", modelT_Bus_WorkOrder.F_Caseid.ToString());
                        log.Add("daynum", newlimittime.Subtract(OldTime).TotalDays.ToString());
                        log.Add("reason", reason);
                        log.Add("curUnitCode", F_DeptNameSpell);
                        var keyDict = NameVlueToDictionary(log);
                        string strJSON = JsonConvert.SerializeObject(keyDict);
                        NameValueCollection values = new NameValueCollection();
                        values.Add("jsonStr", strJSON);
                        var url = $"{thirdUrl}/api/dockthree/increasetime";
                        try
                        {
                            string ret = HttpPostMultipartFormData(url, values);
                        returnvalue1 jo = JsonConvert.DeserializeObject<returnvalue1>(ret);
                            if (jo.code != "0")
                                return jo.message ;
                        }
                        catch (Exception e)
                        {
                            LogFactory.GetLogger("延期").Error(e.Message);
                            return e.Message;
                        }
                        Processing(token, modelT_Bus_WorkOrder.F_Caseid.ToString(), F_DeptNameSpell
                  , modelT_Bus_WorkOrder.F_WorkOrderId, "办理中", "申请延期工单", 1);
                    
                    return "";
                }
                else
                {
                    return "该工单暂未交办";
                }

            }
            else
            {
                return "该工单不存在";
            }

        }

        /// <summary>
        /// 申请延时
        /// </summary>
        /// <returns></returns>
        public string DelayWorkOrder(string workorderid,string reason,string files, 
            DateTime newlimittime, DateTime OldTime)
        {
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null )
                {
               
                    if (modelT_Bus_AssignedInfo.F_IsSure == 1)
                    {
                      

                            if (modelT_Bus_WorkOrder .F_InfoConBigType ==0)
                            {
                                NameValueCollection log = new NameValueCollection();
                                log.Add("token", Logins());
                                log.Add("eid", modelT_Bus_WorkOrder.F_Caseid.ToString());
                                log.Add("delayTime", newlimittime.ToString("yyyy-MM-dd") );
                                log.Add("value", reason);
                                log.Add("unitCode", curUnitCode);
                                var keyDict = NameVlueToDictionary(log);
                                string strJSON = JsonConvert.SerializeObject(keyDict);
                                NameValueCollection values = new NameValueCollection();
                                values.Add("jsonStr", strJSON);
                                var url = $"{thirdUrl}/api/dock/delaytransfer";
                                try
                                {
                                    string ret = HttpPostMultipartFormData(url, values);
                                returnvalue1 jo = JsonConvert.DeserializeObject<returnvalue1>(ret);
                                if (jo.code != "0")
                                    return jo.message ;

                            }
                                catch (Exception e)
                            {
                                LogFactory.GetLogger("延期").Error(e.Message);
                                return e.Message;
                               
                                }
                            }
                            else
                            {
                                NameValueCollection log = new NameValueCollection();
                                log.Add("token", Logins());
                                log.Add("did", modelT_Bus_WorkOrder.F_Caseid.ToString());
                                log.Add("daynum", newlimittime.Subtract(OldTime).TotalDays.ToString());
                                log.Add("reason", reason);
                                log.Add("curUnitCode", curUnitCode);
                                var keyDict = NameVlueToDictionary(log);
                                string strJSON = JsonConvert.SerializeObject(keyDict);
                                NameValueCollection values = new NameValueCollection();
                                values.Add("jsonStr", strJSON);
                                var url = $"{thirdUrl}/api/dock/increasetime";
                                try
                                {
                                    string ret = HttpPostMultipartFormData(url, values);
                                returnvalue jo = JsonConvert.DeserializeObject<returnvalue>(ret);
                                if (jo.code != "0")
                                    return jo.msg;
                            }
                                catch (Exception e)
                                {
                                    LogFactory.GetLogger("延期").Error(e.Message);
                                return e.Message;
                                }
                            }
                           
                        
                        return "";
                    }
                    else
                    {
                        return "该工单暂未交办";
                    }

                }
                else
                {
                return "该工单不存在";
                }
           
        }


        /// <summary>
        /// 审核延时工单
        /// </summary>
        /// <returns></returns>
        [HttpPost ]
        public ActionResult pushoverduecase(int  problemCode,string tfinishday,bool flag,string reason,string processman)
        {
              var  list  = workorderBLL.GetModelList ($"F_Caseid='{problemCode}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                 modelT_Bus_WorkOrder = list.FirstOrDefault();
            Model.T_Bus_DelayTime modelT_Bus_DelayTime = new BLL.T_Bus_DelayTime().GetNewModelByWorkOrderID(modelT_Bus_WorkOrder.F_WorkOrderId);
            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(modelT_Bus_WorkOrder.F_WorkOrderId);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_DelayTime != null )
                {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 保存工单信息

                            TimeSpan ts =Convert .ToDateTime ( tfinishday).Subtract(modelT_Bus_WorkOrder.F_LimitTime.Value);
                            int tss = int.Parse(Math.Round(ts.TotalHours, 0).ToString());
                            if (modelT_Bus_WorkOrder.F_Scanning != null)
                                modelT_Bus_WorkOrder.F_Scanning = modelT_Bus_WorkOrder.F_Scanning.Value.AddHours(tss);
                             
                           // modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.dealing;//办理中
                            modelT_Bus_WorkOrder.F_LimitTime = modelT_Bus_WorkOrder.F_LimitTime.Value.AddHours(tss);
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

                            #region 保存审核信息
                            if (flag)
                            modelT_Bus_DelayTime.F_IsAudit = 1;//审核
                            else
                            modelT_Bus_DelayTime.F_IsAudit = 2;//审核
                            modelT_Bus_DelayTime.F_AuditUser = processman;
                            modelT_Bus_DelayTime.F_AuditTime = DateTime.Now;
                            modelT_Bus_DelayTime.F_RefuseReason = reason;
                            modelT_Bus_DelayTime.F_AgreeTime = modelT_Bus_WorkOrder.F_LimitTime.Value.AddHours(tss);
                            new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime);
                            #endregion
                            string type = "同意"; string des = "";
                            if (modelT_Bus_DelayTime.F_IsAudit == 1)
                            {
                                #region 修改交办记录
                         
                        if (modelT_Bus_AssignedInfo!=null )
                        {
                            modelT_Bus_AssignedInfo.F_LimitTime = modelT_Bus_DelayTime.F_AgreeTime;
                            assignBLL.Update(modelT_Bus_AssignedInfo);
                        }
                              

                                #endregion
                                #region 处理协办单位
                                var xblist = assignItemBLL.GetModelList(" F_IsDelete=0 and F_State=1 and  ISNULL(F_FeedbackTime, '')='' and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'");
                                foreach (var xb in xblist)
                                {
                                    //xb.F_LimitTime = DateTime.Now;
                                    xb.F_LimitTime = modelT_Bus_DelayTime.F_AgreeTime;

                                    assignItemBLL.Update(xb);
                                }
                                #endregion
                                des = "，原定时间" + modelT_Bus_DelayTime.F_OldTime + "，申请延长到" + modelT_Bus_WorkOrder.F_LimitTime.Value.AddHours(tss);
                            }
                            else
                            {
                                type = "拒绝";
                            }

                            #region 插入操作记录
                            Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                            oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                            oper.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                            oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                            string userinfo = processman;
                            oper.F_Message = userinfo + " " + type + "了工单延时申请" + des;
                           oper.F_CreateUser = processman;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);

                            //推送消息表
                            msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, modelT_Bus_DelayTime.F_CreateUser, processman, (int)EnumSmsType.workorder);
                            #endregion

                            trans.Complete();
                        }
                        return Success("操作成功");
                   
                }
                else
                {
                    return Error("操作失败");
                }
          
        }


        /// <summary>
        /// 即办件延期审核通过
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult transferDelayAdopt(int eid, string requirementFinishDay, bool flag, string processman)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{eid}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            Model.T_Bus_DelayTime modelT_Bus_DelayTime = new BLL.T_Bus_DelayTime().GetNewModelByWorkOrderID(modelT_Bus_WorkOrder.F_WorkOrderId);
            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(modelT_Bus_WorkOrder.F_WorkOrderId);

            if (modelT_Bus_WorkOrder != null && modelT_Bus_DelayTime != null && modelT_Bus_AssignedInfo != null)
            {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存工单信息

                        TimeSpan ts = Convert.ToDateTime(requirementFinishDay).Subtract(modelT_Bus_WorkOrder.F_LimitTime.Value);
                        int tss = int.Parse(Math.Round(ts.TotalHours, 0).ToString());
                        if (modelT_Bus_WorkOrder.F_Scanning != null)
                            modelT_Bus_WorkOrder.F_Scanning = modelT_Bus_WorkOrder.F_Scanning.Value.AddHours(tss);

                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.dealing;//办理中
                        modelT_Bus_WorkOrder.F_LimitTime = modelT_Bus_WorkOrder.F_LimitTime.Value.AddHours(tss);
                        workorderBLL.Update(modelT_Bus_WorkOrder);
                        #endregion

                        #region 保存审核信息
                        if (flag)
                            modelT_Bus_DelayTime.F_IsAudit = 1;//审核
                        else
                            modelT_Bus_DelayTime.F_IsAudit = 0;//审核
                        modelT_Bus_DelayTime.F_AuditUser = processman;
                        modelT_Bus_DelayTime.F_AuditTime = DateTime.Now;
                        modelT_Bus_DelayTime.F_RefuseReason = "";
                        modelT_Bus_DelayTime.F_AgreeTime = modelT_Bus_WorkOrder.F_LimitTime.Value.AddHours(tss);
                        new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime);
                        #endregion
                        string type = "同意"; string des = "";
                        if (modelT_Bus_DelayTime.F_IsAudit == 1)
                        {
                            #region 修改交办记录

                            modelT_Bus_AssignedInfo.F_LimitTime = modelT_Bus_DelayTime.F_AgreeTime;
                            assignBLL.Update(modelT_Bus_AssignedInfo);

                            #endregion
                            #region 处理协办单位
                            var xblist = assignItemBLL.GetModelList(" F_IsDelete=0 and F_State=1 and  ISNULL(F_FeedbackTime, '')='' and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'");
                            foreach (var xb in xblist)
                            {
                                //xb.F_LimitTime = DateTime.Now;
                                xb.F_LimitTime = modelT_Bus_DelayTime.F_AgreeTime;

                                assignItemBLL.Update(xb);
                            }
                            #endregion
                            des = "，原定时间" + modelT_Bus_DelayTime.F_OldTime + "，申请延长到" + modelT_Bus_WorkOrder.F_LimitTime.Value.AddHours(tss);
                        }
                        else
                        {
                            type = "拒绝";
                        }

                        #region 插入操作记录
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                        oper.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                        oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                        string userinfo = processman;
                        oper.F_Message = userinfo + " " + type + "了工单延时申请" + des;
                        oper.F_CreateUser = processman;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);

                        //推送消息表
                        msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, modelT_Bus_DelayTime.F_CreateUser, processman, (int)EnumSmsType.workorder);
                        #endregion

                        trans.Complete();
                    }
                    return Success("操作成功");
              
            }
            else
            {
                return Error("操作失败");
            }

        }


        /// <summary>
        /// 即办件延期审核不通过
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult transferDelayFail(int eid, string value, bool flag, string processman)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{eid}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            Model.T_Bus_DelayTime modelT_Bus_DelayTime = new BLL.T_Bus_DelayTime().GetNewModelByWorkOrderID(modelT_Bus_WorkOrder.F_WorkOrderId);
            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(modelT_Bus_WorkOrder.F_WorkOrderId);

            if (modelT_Bus_WorkOrder != null && modelT_Bus_DelayTime != null && modelT_Bus_AssignedInfo != null)
            {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存审核信息
                        if (flag)
                            modelT_Bus_DelayTime.F_IsAudit = 1;//审核
                        else
                            modelT_Bus_DelayTime.F_IsAudit = 2;//审核
                        modelT_Bus_DelayTime.F_AuditUser = processman;
                        modelT_Bus_DelayTime.F_AuditTime = DateTime.Now;
                        modelT_Bus_DelayTime.F_RefuseReason = value;
                        new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime);
                        #endregion
                        string type = "同意"; string des = "";
                        type = "拒绝";
                       //  modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.dealing;//办理中
                           workorderBLL.Update(modelT_Bus_WorkOrder);

                        #region 插入操作记录
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                        oper.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                        oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                        string userinfo = processman;
                        oper.F_Message = userinfo + " " + type + "了工单延时申请" + des;
                        oper.F_CreateUser = processman;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);

                        //推送消息表
                        msg.AddInternalMessagesInfo("工单消息",
                            oper.F_Message + "，工单编号：" + oper.F_WorkOrderId,
                            modelT_Bus_DelayTime.F_CreateUser, processman, (int)EnumSmsType.workorder);
                        #endregion

                        trans.Complete();
                    }
                    return Success("操作成功");
                
            }
            else
            {
                return Error("操作失败");
            }

        }
        /// <summary>
        /// 单位处理记录
        /// </summary>
        /// <returns></returns>
        public string Processing(string token,string eid,string F_DeptNameSpell
            ,string workorderid,
            string progress,string operate
            ,int flag=1)
        {
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
         
                NameValueCollection log = new NameValueCollection();
                log.Add("token", token);
                log.Add("eid", eid);
                log.Add("progress", progress);
                log.Add("unitCode", F_DeptNameSpell);
                log.Add("operate", operate);
                log.Add("remark", "");
                log.Add("flag", flag.ToString ());
                var keyDict = NameVlueToDictionary(log);
                string strJSON = JsonConvert.SerializeObject(keyDict);
                NameValueCollection values = new NameValueCollection();
                values.Add("jsonStr", strJSON);
                var url = $"{thirdUrl}/api/dock/threeFinishResult";
                try
                {
                    string ret = HttpPostMultipartFormData(url, values);
                    returnvalue1 jo = JsonConvert.DeserializeObject<returnvalue1>(ret);
                    if (jo.code != "0")
                        return jo.message ;
                }
                catch (Exception e)
                {
                    LogFactory.GetLogger("工单处理记录").Error(e.Message);
                    return e.Message;
                }

            
            return "";



        }
        /// <summary>
        /// 单位退回工单
        /// </summary>
        /// <returns></returns>
        public string  DWBackWorkOrder(string workorderid,string reason,string username,string usercode)
        {
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
             
                string F_DeptNameSpell = curUnitCode;
                var dept =
             new BLL.T_Sys_Department().GetModel(modelT_Bus_WorkOrder.F_MainDeptId.Value);
                F_DeptNameSpell = dept.F_DeptNameSpell;
                NameValueCollection log = new NameValueCollection();
                string token = Logins();
                log.Add("token", token);
                log.Add("did", modelT_Bus_WorkOrder.F_Caseid.ToString());
                log.Add("reason", reason);
                log.Add("curUnitCode", F_DeptNameSpell);
                var keyDict = NameVlueToDictionary(log);
                string strJSON = JsonConvert.SerializeObject(keyDict);
                NameValueCollection values = new NameValueCollection();
                values.Add("jsonStr", strJSON);
                var url = $"{thirdUrl}/api/dockthree/applysendback";
                try
                {
                    string ret = HttpPostMultipartFormData(url, values);
                returnvalue1 jo = JsonConvert.DeserializeObject<returnvalue1>(ret);
                    if (jo.code != "0")
                        return jo.message  ;

                }
                catch (Exception e)
                {
                    LogFactory.GetLogger("申请退回工单").Error(e.Message);
                    return e.Message;
                }
                Processing(token, modelT_Bus_WorkOrder.F_Caseid.ToString(), F_DeptNameSpell
                    , modelT_Bus_WorkOrder.F_WorkOrderId, "办理中", "申请退回工单", 2);
                 
                return "";


          
        }

        /// <summary>
        /// 申请退回工单 这个不用了
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult BackWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            if (userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "ZXLD")
            {
                    string workorderid = RequestString.GetFormString("workorderid");
                  string reason = RequestString.GetFormString("reason");
                var reminds = remindBLL.GetModelList($" F_State=0 and F_WorkOrderId='{workorderid }' and F_IsDelete=0 and F_Type =1").ToList();
                if (reminds != null && reminds.Count() > 0)
                {
                    return Error("督办工单不能退回");
                }
                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                        using (TransactionScope trans = new TransactionScope())
                        {
                            if (modelT_Bus_WorkOrder.F_InfoConBigType == 0)
                            {
                                NameValueCollection log = new NameValueCollection();
                                log.Add("token", Logins());
                                log.Add("eid", modelT_Bus_WorkOrder.F_Caseid.ToString());
                                log.Add("value", reason);
                                log.Add("unitCode", curUnitCode);
                                var keyDict = NameVlueToDictionary(log);
                                string strJSON = JsonConvert.SerializeObject(keyDict);
                                NameValueCollection values = new NameValueCollection();
                                values.Add("jsonStr", strJSON);
                                var url = $"{thirdUrl}/api/dock/returntransfer";
                                try
                                {
                                    string ret = HttpPostMultipartFormData(url, values);

                            returnvalue1 jo = JsonConvert.DeserializeObject<returnvalue1>(ret);
                            if (jo.code != "0")
                                return Error(jo.message );
                                }
                                catch (Exception e)
                                {
                                    LogFactory.GetLogger("申请退回工单").Error(e.Message);
                            return Error(e.Message);
                                }
                            }
                            else
                            {
                                NameValueCollection log = new NameValueCollection();
                                log.Add("token", Logins());
                                log.Add("did", modelT_Bus_WorkOrder.F_Caseid.ToString());
                                log.Add("reason", reason);
                                log.Add("curUnitCode", curUnitCode);
                                var keyDict = NameVlueToDictionary(log);
                                string strJSON = JsonConvert.SerializeObject(keyDict);
                                NameValueCollection values = new NameValueCollection();
                                values.Add("jsonStr", strJSON);
                                var url = $"{thirdUrl}/api/dock/applysendback";
                                try
                                {
                                    string ret = HttpPostMultipartFormData(url, values);
                            returnvalue jo = JsonConvert.DeserializeObject<returnvalue>(ret);
                            if (jo.code != "0")
                                return Error(jo.msg);

                        }
                                catch (Exception e)
                                {
                                    LogFactory.GetLogger("申请退回工单").Error(e.Message);
                            return Error(e.Message);
                        }
                            }

                            #region 保存工单信息
                              modelT_Bus_WorkOrder.F_WorkState = 14;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

                      

                            #region 插入操作记录
                            Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                            oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                            oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 申请了退回工单";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;
                            operBLL.Add(oper);
                            //推送消息表
                            #endregion

                         
                            trans.Complete();
                        }
                        return Success("操作成功");
                   
               
            }
            else
            {
                return Error("权限不足");
            }
        }




        /// <summary>
        /// 审核退回工单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult pushbackcase(int problemCode,int did, bool flag, string reason, string processman)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{problemCode}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {
                  
                    string type = "同意";
                    if (!flag)
                    {
                        modelT_Bus_WorkOrder.F_WorkState = 1;//办理中
                        type = "拒绝";

                       if(modelT_Bus_WorkOrder.F_IsEnabled ==2)
                        {
                            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.
                                GetNewModelByWorkOrderID(modelT_Bus_WorkOrder.F_WorkOrderId );
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.receive;//待查收
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            //modelT_Bus_AssignedInfo.F_FeedbackTime = null;//反馈时间
                            modelT_Bus_AssignedInfo.F_IsSure = 0;
                            modelT_Bus_AssignedInfo.F_SureUser = "";
                            modelT_Bus_AssignedInfo.F_SureTime = null;
                            assignBLL.Update(modelT_Bus_AssignedInfo);
                        }
                     
                    }
                    else
                    {
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                    }
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = processman;
                    oper.F_Message = userinfo + " " + type + "了工单退回申请" + reason;
                    oper.F_CreateUser = processman;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    //推送消息表
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }

        }

        /// <summary>
        /// 即办件同意退回工单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult transferReturnAdopt(int eid,  bool flag, string processman)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{eid}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {
                   
                    string type = "同意";
                    if (!flag)
                    {
                        modelT_Bus_WorkOrder.F_WorkState = 1;//办理中
                        type = "拒绝";
                    }
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = processman;
                    oper.F_Message = userinfo + " " + type + "了工单退回申请" ;
                    oper.F_CreateUser = processman;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    //推送消息表
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }

        }


        /// <summary>
        /// 即办件拒绝退回工单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult transferReturnFail(int eid, bool flag,string value, string processman)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{eid}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    
                    string type = "同意";
                    if (!flag)
                    {
                        modelT_Bus_WorkOrder.F_WorkState = 1;//办理中
                        type = "拒绝";
                    }
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = processman;
                    oper.F_Message = userinfo + " " + type + "了工单退回申请"+ value;
                    oper.F_CreateUser = processman;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    //推送消息表
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }

        }

        public string DwHandWorkorder
            (Model.T_Bus_WorkOrder modelT_Bus_WorkOrder, Model.T_Sys_UserAccount userModel)
        {
            token = Logins();
            if (modelT_Bus_WorkOrder.F_IsEnabled == 2)
            {
                string F_DeptNameSpell = curUnitCode;
                if (modelT_Bus_WorkOrder.F_MainDeptId > 0)
                {
                    var dept =
              new BLL.T_Sys_Department().GetModel(modelT_Bus_WorkOrder.F_MainDeptId.Value);
                    F_DeptNameSpell = dept.F_DeptNameSpell;
                }
              string    did = modelT_Bus_WorkOrder.F_Caseid.ToString();
                NameValueCollection log = new NameValueCollection();
                log.Add("token", token);
                log.Add("did", modelT_Bus_WorkOrder.F_Caseid.ToString());
                log.Add("result", modelT_Bus_WorkOrder.F_NewResult);
                log.Add("curUnitCode", F_DeptNameSpell);
                var keyDict = NameVlueToDictionary(log);
                string strJSON = JsonConvert.SerializeObject(keyDict);
                NameValueCollection values = new NameValueCollection();
                values.Add("jsonStr", strJSON);
                var url = $"{thirdUrl}/api/dockthree/unitsavecase";
                try
                {
                    string ret = HttpPostMultipartFormData(url, values);
                    returnvalue1 jo = JsonConvert.DeserializeObject<returnvalue1>(ret);
                    if (jo.code != "0")
                        return jo.message;
                }
                catch (Exception e)
                {
                    LogFactory.GetLogger("结果").Error(e.Message);
                    return e.Message;
                }
            }
            return "";
        }
  

        /// <summary>
        /// 推送处理结果
        /// </summary>
        /// <returns></returns>
        public string    HandleWorkOrder(Model.T_Bus_WorkOrder modelT_Bus_WorkOrder, Model .T_Sys_UserAccount userModel)
        {
              
                
                    string  type = "";string did = "";string token = "";
                   token = Logins();
               
                
                    var reminds = remindBLL.GetModelList($" F_State=0 and F_WorkOrderId='{modelT_Bus_WorkOrder.F_WorkOrderId }' and F_IsDelete=0 and F_Type =1").ToList();
                    if (reminds != null && reminds.Count() > 0)
                    {
                        type = "12";
                        NameValueCollection log = new NameValueCollection();
                        log.Add("token", token);
                        log.Add("id", reminds.FirstOrDefault().F_Did);
                        did = reminds.FirstOrDefault().F_Did;
                        log.Add("result", modelT_Bus_WorkOrder.F_NewResult);
                        if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_HCFiles))
                        {
                            string message = upload(modelT_Bus_WorkOrder.F_HCFiles, token, did, type);
                            if (message != "")
                                return message;
                        }
                        var keyDict = NameVlueToDictionary(log);
                        string strJSON = JsonConvert.SerializeObject(keyDict);
                        NameValueCollection values = new NameValueCollection();
                        values.Add("jsonStr", strJSON);
                        var url = $"{thirdUrl}/api/dock/finishSupervise";
                        try
                        {
                            string ret = HttpPostMultipartFormData(url, values);
                            returnvalue jo = JsonConvert.DeserializeObject<returnvalue>(ret);
                            if (jo.code != "0")
                                return jo.msg;

                        }
                        catch (Exception e)
                        {
                            LogFactory.GetLogger("督办结果").Error(e.Message);
                            return e.Message;
                        }
                    }
                    else
                    {
                        did = modelT_Bus_WorkOrder.F_Caseid.ToString();
                        if (modelT_Bus_WorkOrder.F_InfoConBigType == 0)
                        {
                            type = "19";
                            NameValueCollection log = new NameValueCollection();
                            log.Add("token", token);
                            log.Add("eid", modelT_Bus_WorkOrder.F_Caseid.ToString());
                            log.Add("result", modelT_Bus_WorkOrder.F_NewResult);
                            log.Add("unitCode", curUnitCode);
                            if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_HCFiles))
                            {
                                string message = upload(modelT_Bus_WorkOrder.F_HCFiles, token, did, type);
                                if (message != "")
                                    return message;
                            }
                            var keyDict = NameVlueToDictionary(log);
                            string strJSON = JsonConvert.SerializeObject(keyDict);
                            NameValueCollection values = new NameValueCollection();
                            values.Add("jsonStr", strJSON);
                            var url = $"{thirdUrl}/api/dock/finishtransfer";
                            try
                            {
                                string ret = HttpPostMultipartFormData(url, values);
                                returnvalue1 jo = JsonConvert.DeserializeObject<returnvalue1>(ret);
                                if (jo.code != "0")
                                    return jo.message;

                            }
                            catch (Exception e)
                            {
                                LogFactory.GetLogger("既办结果").Error(e.Message);
                                return e.Message;
                            }
                        }
                        else
                        {
                            type = "13";
                            NameValueCollection log = new NameValueCollection();
                            log.Add("token", token);
                            log.Add("did", modelT_Bus_WorkOrder.F_Caseid.ToString());
                            log.Add("result", modelT_Bus_WorkOrder.F_NewResult);
                            log.Add("curUnitCode", curUnitCode);
                            var keyDict = NameVlueToDictionary(log);
                            if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_HCFiles))
                            {
                                string message = upload(modelT_Bus_WorkOrder.F_HCFiles, token, did, type);
                                if (message != "")
                                    return message;
                            }
                            string strJSON = JsonConvert.SerializeObject(keyDict);
                            NameValueCollection values = new NameValueCollection();
                            values.Add("jsonStr", strJSON);
                            var url = $"{thirdUrl}/api/dock/unitsavecase";
                            try
                            {
                                string ret = HttpPostMultipartFormData(url, values);
                                returnvalue jo = JsonConvert.DeserializeObject<returnvalue>(ret);
                                if (jo.code != "0")
                                    return jo.msg;
                            }
                            catch (Exception e)
                            {
                                LogFactory.GetLogger("结果").Error(e.Message);
                                return e.Message;
                            }
                        }
                    }

                




                //if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_Files))
                //{
                //    if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_Files))
                //    {
                //        using (var content = new MultipartFormDataContent())
                //        {
                //            var files = GetFileData(modelT_Bus_WorkOrder.F_Files);

                //            NameValueCollection fileCollection = new NameValueCollection();
                //            for (int i = 0; i < files.Count(); i++)
                //            {
                //                fileCollection.Add($"file", files[i]);
                //            }
                //            NameValueCollection nameValueCollection = new NameValueCollection();
                //            nameValueCollection.Add("token", token);
                //            nameValueCollection.Add("id", did);
                //            nameValueCollection.Add("type", type);
                //            string url = $"{thirdUrl}/api/dock/uploadfile";
                //            try
                //            {
                //                var Postresult = PostMultipartFormData(url, null, nameValueCollection, files);
                //                returnvalue jo = JsonConvert.DeserializeObject<returnvalue>(Postresult);
                //                if (jo.code != "0")
                //                    return jo.msg;
                //            }
                //            catch (Exception e)
                //            {
                //                LogFactory.GetLogger("附件").Error(e.Message);
                //                return e.ToJson();
                //            }

                //        }

                //    }

                //}

                #region 保存工单信息
                //  modelT_Bus_WorkOrder.F_WorkState = 14;//延时审核中
                //  workorderBLL.Update(modelT_Bus_WorkOrder);



                #endregion



                #region 插入操作记录
                Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                    oper.F_Message = userinfo + " 推送处理结果";
                    oper.F_CreateUser = userModel.F_UserCode;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    //推送消息表
                    #endregion


                 
                return "" ;


           
        }
       public string  upload(string F_Files,string token,string  did,string  type)
        {
           
            if (!string.IsNullOrEmpty(F_Files))
            {
                using (var content = new MultipartFormDataContent())
                {
                    var files = GetFileData(F_Files);

                   //NameValueCollection fileCollection = new NameValueCollection();
                   // for  (int i= 0;i <files .Count ();i++)
                   // {
                   //     fileCollection.Add($"file", files[i ]);
                   // }
                    NameValueCollection nameValueCollection = new NameValueCollection();
                    nameValueCollection.Add("token", token);
                    nameValueCollection.Add("id", did);
                    nameValueCollection.Add("type", type);
                    string url = $"{thirdUrl}/api/dock/uploadfile";
                    try
                    {
                        var Postresult = PostMultipartFormData(url,null , nameValueCollection, files);
                        returnvalue1 jo = JsonConvert.DeserializeObject<returnvalue1>(Postresult);
                        if (jo.code != "0")
                        {
                            LogFactory.GetLogger("附件").Error(jo.message);
                            return jo.message;
                        }
                          
                    }
                    catch (Exception e)
                    {
                        LogFactory.GetLogger("附件").Error(e.Message);
                        return e.ToJson();
                    }

                }

            }
            return "";
        }

     
        /// <summary>
        /// 使用multipart/form-data方式上传文件及其他数据
        /// </summary>
        /// <param name="headers">请求头参数</param>
        /// <param name="nameValueCollection">键值对参数</param>
        /// <param name="fileCollection">文件参数：参数名，文件路径</param>
        /// <returns>接口返回结果</returns>
        public static string PostMultipartFormData(string url, Dictionary<string, string> headers,
            NameValueCollection nameValueCollection, List <string > files)
        {
            using (var client = new HttpClient())
            {
                

                using (var content = new MultipartFormDataContent())
                {
                    // 键值对参数
                    string[] allKeys = nameValueCollection.AllKeys;
                    foreach (string key in allKeys)
                    {
                        var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(nameValueCollection[key]));
                        dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                        {
                            Name = key
                        };
                        content.Add(dataContent);
                    }






                    //处理文件内容
                    string Currentpath = System.Web.HttpContext.Current.Server.MapPath("..");
                   // string[] fileKeys = fileCollection.AllKeys;
                    foreach (string key in files)
                    {
                        var filepath = Currentpath + key;
                        byte[] bmpBytes =System.IO.File.ReadAllBytes(filepath);
                        var fileContent = new ByteArrayContent(bmpBytes);//填充文件字节
                        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                        {
                            Name = "file",
                            FileName = Path.GetFileName(filepath)
                        };
                       // content.Add(fileContent, "file", key);
                       content.Add(fileContent);
                    }
                   

                    //处理文件内容


                    var result = client.PostAsync(url, content).Result;//post请求
                    string data = result.Content.ReadAsStringAsync().Result;
                    return data;//返回操作结果
                }
            }
        }



       

        /// <summary>
        /// 获取附件数据
        /// </summary>
        /// <param name="ids">附件id，多个用英文逗号,隔开</param>
        /// <param name="prefix">前缀</param>
        /// <returns></returns>
        public List<string  >  GetFileData(string ids)
        {
            List<string> files = new List<string>();
            DataTable dt = DbHelperSQL.Query("select * from T_Sys_Accessories WITH(NOLOCK) where F_FileId in (" + ids + ") order by F_AddTime desc").Tables[0];
           
            foreach (DataRow dr in dt.Rows)
            {
              string   F_FileUrl = dr["F_FileUrl"].ToString();
                files.Add(F_FileUrl);
            }
            return files;
        }


        /// <summary>
        /// 办结审核结果
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult pushconfirmresult(int problemCode, int did, bool flag, int progress, string reason, string processman)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{problemCode}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {
                   
                    string type = "同意";
                    if (!flag)
                    {
                        if (progress == 11)
                        {
                            type = processman+"拒绝并提交重办";
                            modelT_Bus_WorkOrder.IsExport = 0;
                            modelT_Bus_WorkOrder.F_WorkState = 11;//办理中
                            modelT_Bus_WorkOrder.F_Backreason = reason;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                        }
                        else
                        {
                            modelT_Bus_WorkOrder.IsExport = 0;
                            modelT_Bus_WorkOrder.F_WorkState = 9;
                      workorderBLL.Update(modelT_Bus_WorkOrder);
                            type = "拒绝";
                        }
                      
                    }
                 
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = processman;
                    oper.F_Message = userinfo + " " + type + "了工单办结" + reason;
                    oper.F_CreateUser = processman;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    //推送消息表
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }

        }

       

        /// <summary>
        /// 即办件办结审核通过
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult transferConcludeAdopt(int eid, string finishTransferTime, bool flag, string processman)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{eid}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {
                   
                    string type = "同意";
                    if (!flag)
                    {
                        modelT_Bus_WorkOrder.F_WorkState = 9;//办理中

                        type = "拒绝";

                    }
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = processman;
                    oper.F_Message = userinfo + " " + type + "了工单办结" ;
                    oper.F_CreateUser = processman;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    //推送消息表
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }

        }


        /// <summary>
        /// 即办件办结审核不通过
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult transferConcludeFail(int eid, string finishTransferTime,string value, bool flag, string processman)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{eid}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {
                  
                    string type = "同意";
                    if (!flag)
                    {
                        modelT_Bus_WorkOrder.F_WorkState = 7;//办理中

                        type = "拒绝";

                    }
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = processman;
                    oper.F_Message = userinfo + " " + type + "了工单办结"+ value;
                    oper.F_CreateUser = processman;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    //推送消息表
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }

        }


        public class Remind
        {
            public int problemCode { set; get; }//problemCode：关联案件的id，与工单推送的字段意思一致(int)
            public string problemDescription { set; get; }//描述(varchar)
            public string timeLimit { set; get; }//限定时间，此字段非日期类型
            public string reporterContactInfo { set; get; }//手机号码(varchar)
            public string reportTime { set; get; }//登记日期
            public string forwarder { set; get; }//发送人(varchar)
            public string forwardTime { set; get; }//发送时间
            public string problemRequire { set; get; }//督办要求(varchar)
            public int   did { set; get; }//督办记录唯一id（此值供（督办工单结果信息接口）的参数id使用）
            public string code { set; get; }//督办编码
        }
        /// <summary>
        /// 督办工单
        /// </summary>
        /// <returns></returns>
        public ActionResult supervisecase(Remind remind )
        {
            //  var list = workorderBLL.GetModelList($"F_Caseid='{remind.problemCode}' and F_IsDelete=0");

            // if (list != null && list.Count ()>0)
            // {
            LogFactory.GetLogger("1123").Warn(remind.ToJson());
            using (TransactionScope trans = new TransactionScope())
                {
                #region 保存工单信息

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();

                modelT_Bus_WorkOrder.F_OldWorkOrderId = remind.code;
                var workorder = workorderBLL.GetModelList("F_OldWorkOrderId='" +
                    modelT_Bus_WorkOrder.F_OldWorkOrderId + "'" +
                    "and F_IsDelete=0");
                if (workorder != null && workorder.Count > 0)
                {

                    modelT_Bus_WorkOrder = workorder[0];
                }
                else
                {
                    modelT_Bus_WorkOrder.F_WorkState = 1;
                    modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID("8000");
                }
                modelT_Bus_WorkOrder.F_InfoConBigType = 1;
                modelT_Bus_WorkOrder.F_Files = "";
                modelT_Bus_WorkOrder.F_Caseid = remind.problemCode;
                modelT_Bus_WorkOrder.F_InfoSource = 176;//信息来源
                if (!string.IsNullOrEmpty(remind.timeLimit))
                {
                    modelT_Bus_WorkOrder.F_LimitTime = Convert.ToDateTime(remind.timeLimit);
                    modelT_Bus_WorkOrder.requirementFinishDay = remind.timeLimit;

                }
                   
                modelT_Bus_WorkOrder.F_CusPhone = remind.reporterContactInfo;//
                modelT_Bus_WorkOrder.F_ConPhone = remind.reporterContactInfo;//联系人
                try
                {
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Parse(remind.reportTime);
                }
                catch
                {
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;
                }
                //  modelT_Bus_WorkOrder.F_Event = info.ismallcategory;//事件类别
                modelT_Bus_WorkOrder.F_Transferor = remind.forwarder;//转办人
                modelT_Bus_WorkOrder.F_TransferTime = DateTime.Now;
             
                modelT_Bus_WorkOrder.F_ComContent = remind.problemDescription;//
                modelT_Bus_WorkOrder.F_Did = remind.did;
                // modelT_Bus_WorkOrder.F_ResultRemarks = info.advice;//拟办意见
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfos = new Model.T_Bus_AssignedInfo();
                modelT_Bus_WorkOrder.F_Remarks = "★以上登记信息仅供市长热线平台及承办人员查阅，未经许可不得向外提供";//
                modelT_Bus_WorkOrder.F_IsDelete = 0;
                modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;

                if (modelT_Bus_WorkOrder.F_Id > 0)
                {
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                }
                else
                {
                    workorderBLL.Add(modelT_Bus_WorkOrder);
                }
                #endregion
                #region 插入操作记录
                Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                string userinfo = "郑州市系统";
                if (modelT_Bus_WorkOrder.F_WorkState == 0 || modelT_Bus_WorkOrder.F_WorkState == 1)
                {
                    oper.F_Message = userinfo + " 登记了督办工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                }
                else
                {
                    oper.F_Message = userinfo + " 提交督办了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                }
                oper.F_CreateUser = remind.forwarder;
                oper.F_CreateTime = DateTime.Now;
                oper.F_IsDelete = 0;
                operBLL.Add(oper);
                #endregion
                #region 插入督办记录
             
                    Model.T_Bus_RemindRecord modelT_Bus_RemindRecord = new Model.T_Bus_RemindRecord();
                    modelT_Bus_RemindRecord.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    modelT_Bus_RemindRecord.F_Type = 1;
                    modelT_Bus_RemindRecord.F_Content = remind.problemDescription;
                    modelT_Bus_RemindRecord.F_State = 0;//0待办 1已办 2退回
                    modelT_Bus_RemindRecord.F_IsDelete = 0;
                    modelT_Bus_RemindRecord.F_CreateUser = remind.forwarder;
                    modelT_Bus_RemindRecord.F_Remark = remind.problemRequire;
                    modelT_Bus_RemindRecord.F_CreateTime = DateTime.Now;
                    modelT_Bus_RemindRecord.F_Did = remind.did.ToString ();
                    modelT_Bus_RemindRecord.F_Code = remind.code;
                    modelT_Bus_RemindRecord.F_Limit  = remind.timeLimit;
                    new BLL.T_Bus_RemindRecord().Add(modelT_Bus_RemindRecord);
                    #endregion
                    #region 插入操作记录
                    Model.T_Bus_Operation oper1 = new Model.T_Bus_Operation();
                  oper1.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                   oper1.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    oper.F_Message = userinfo + " " + "督办" + "了工单";
                    oper.F_CreateUser = remind.forwarder;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;

                    operBLL.Add(oper);
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
           // }
           // else
           // {
            //    return Error("操作失败");
           // }
        }


        /// <summary>
        /// 督办工单撤回
        /// </summary>
        /// <returns></returns>
        public ActionResult pushbacksupervise(string problemCode,string did)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{problemCode}' and F_IsDelete=0");

            if (list != null && list.Count() > 0)
            {
                using (TransactionScope trans = new TransactionScope())
                {

                    #region 插入督办记录
                    var modelT_Bus_WorkOrder = list.FirstOrDefault();
                    //if (modelT_Bus_WorkOrder!=null )
                    //{
                    //    var RemindRecord = new BLL.T_Bus_RemindRecord().GetModelList
                    //        ($"F_Did='{did}' and F_WorkOrderId={modelT_Bus_WorkOrder.F_WorkOrderId }");
                    //    if (RemindRecord!=null )
                    //    {
                    //        foreach (var it in RemindRecord)
                    //        {
                    //            it.F_IsDelete = 1;
                    //            new BLL.T_Bus_RemindRecord().Update(it);
                    //        }
                    //    }
                    //}
                    #region 保存工单信息
                    modelT_Bus_WorkOrder.F_WorkState = 14;
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #endregion



                    #endregion
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    oper.F_Message =   "市平台" + "撤回了督办工单";
                    oper.F_CreateUser = "市平台";
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }
        }
        /// <summary>
        /// 督办工单办结审核结果
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult pushConfirmDealSupervise
            (int problemCode, int did, bool flag, int progress, string reason)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{problemCode}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {

                    string type = "同意";
                    if (!flag)
                    {
                        if (progress == 11)
                        {
                            type = "拒绝并提交重办";
                            modelT_Bus_WorkOrder.IsExport = 0;
                            modelT_Bus_WorkOrder.F_WorkState = 11;//办理中
                            modelT_Bus_WorkOrder.F_Backreason = reason;
                        }
                        else
                        {
                            modelT_Bus_WorkOrder.IsExport = 0;
                            modelT_Bus_WorkOrder.F_WorkState = 9
;//办理中
                            type = "拒绝";
                        }

                    }
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = "市平台";
                    oper.F_Message = userinfo + " " + type + "了工单办结" + reason;
                    oper.F_CreateUser = "市平台";
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    //推送消息表
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }

        }

        /// <summary>
        /// 督办工单回访
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult pushhfsupervise(string problemCode, string did,string approveresult,int  progress)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{problemCode}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {

                    string type = "督办回访";
                    //if (progress == 11)
                    //{
                    //    type = "回访并提交重办";
                    //    modelT_Bus_WorkOrder.F_Result = approveresult;
                    //    modelT_Bus_WorkOrder.IsExport = 0;
                    //    modelT_Bus_WorkOrder.F_WorkState = 11;//办理中
                    //}
                    //else
                    //{
                       
                    //}
                    modelT_Bus_WorkOrder.F_WorkState = 14
;//办理中
                    type = "督办回访";
                    modelT_Bus_WorkOrder.F_Satisfaction = 2;
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                   
                    oper.F_Message = "市平台" + " " + type + "了工单" + approveresult;
                    oper.F_CreateUser = "市平台";
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    //推送消息表
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }

        }
        /// <summary>
        /// 回访审核
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult pushapproveresult(int problemCode, int did, bool flag,string remark
            , string reason, string processman, int connection=0,
            int progress=0)
        {
            var list = workorderBLL.GetModelList($"F_Caseid='{problemCode}' and F_IsDelete=0");
            var modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
            if (list != null && list.Count > 0)
                modelT_Bus_WorkOrder = list.FirstOrDefault();
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {

                    string type = "回访";
                    if (!flag)
                    {
                        type = "回访并提交重办";
                        //  modelT_Bus_WorkOrder.F_Result = remark;
                        modelT_Bus_WorkOrder.IsExport = 0;
                        modelT_Bus_WorkOrder.F_WorkState = 11;//办理中
                        modelT_Bus_WorkOrder.F_Satisfaction = 0;//郑州市满意度
                        modelT_Bus_WorkOrder.F_Backreason = reason;
                    }
                    else
                    {
                        modelT_Bus_WorkOrder.F_Satisfaction = 2;//郑州市满意度
                    }
                    if (!string.IsNullOrEmpty(remark))
                        type += "回访情况:" + remark;
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = processman;
                    oper.F_Message = userinfo + " " + type + "了工单" + reason;
                    oper.F_CreateUser = processman;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    //推送消息表
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }

        }

        /// <summary>
        /// MultipartFormData Post方式提交
        /// </summary>
        /// <param name="url"></param>
        /// <param name="kVDatas"></param>
        /// <param name="method"></param>
        /// <param name="encoding"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static string HttpPostMultipartFormData(string url, NameValueCollection kVDatas, string method = WebRequestMethods.Http.Post, string encoding = "UTF-8", int timeOut = -1)
        {
            string resultStr = "";
            try
            {
                string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundarybytes = Encoding.GetEncoding(encoding).GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endbytes = Encoding.GetEncoding(encoding).GetBytes("\r\n--" + boundary + "--\r\n");

                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
                ServicePointManager.ServerCertificateValidationCallback = delegate (
                Object obj, X509Certificate certificate, X509Chain chain,
                SslPolicyErrors errors)
                {
                    return (true);
                };

                //1.HttpWebRequest
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method = method;
                request.KeepAlive = true;
                request.Timeout = timeOut;

               



                using (Stream stream = request.GetRequestStream())
                {
                    //1.1 key/value
                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                    if (kVDatas != null)
                    {
                        foreach (string key in kVDatas.Keys)
                        {
                            stream.Write(boundarybytes, 0, boundarybytes.Length);
                            string formitem = string.Format(formdataTemplate, key, kVDatas[key]);
                            byte[] formitembytes = Encoding.GetEncoding(encoding).GetBytes(formitem);
                            stream.Write(formitembytes, 0, formitembytes.Length);
                        }
                    }
                    stream.Write(endbytes, 0, endbytes.Length);
                }

                //2.WebResponse
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                    {
                        resultStr = stream.ReadToEnd();

                    }
                }


            }
            catch (WebException ex)
            {
                var errorSr = new StreamReader(ex.Response.GetResponseStream());
                resultStr = errorSr.ReadToEnd();
            }
            return resultStr;
        }

        #region 知识库

        public class transmit_kinfo_add
        {
            public string AREA_CODE { set; get; }
            /// <summary>
            /// 标题
            /// </summary>
            public string KINFO_KNAME { set; get; }
            /// <summary>
            /// 内容
            /// </summary>
            public string KINFO_KCONTENT { set; get; }
            /// <summary>
            /// 知识分类编码
            /// </summary>
            public string KINFO_TYPECODE { set; get; }
            /// <summary>
            /// 发布时间
            /// </summary>
            public string KINFO_CREATEDATE { set; get; }
            /// <summary>
            /// 生效时间
            /// </summary>
            public string KINFO_BEGINDATE { set; get; }
            /// <summary>
            /// 失效时间
            /// </summary>
            public string KINFO_DISABLEDATE { set; get; }
            /// <summary>
            /// 知识报送附件id
            /// </summary>
            public string KINFO_ATTATH_ID { set; get; }
        }
        public class kinfo
        {
            public string code { set; get; }
            public string message { set; get; }
            public kinfobody body { set; get; }
        }
        public class kinfobody
        {
            public string KINFO_ID { set; get; }
        }
        /// <summary>
        /// </summary>
        /// 知识报送接口
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public string  kinfo_add(int id)
        {
            Model.T_RepositoryInformation model = new BLL.T_RepositoryInformation().GetModel(id);
            if (model != null)
            {
                transmit_kinfo_add paras = new transmit_kinfo_add();
                paras.AREA_CODE = "410181";
                paras.KINFO_KNAME = model.F_Title;
                if (!string.IsNullOrEmpty(model.F_Description))
                    paras.KINFO_KCONTENT = model.F_Description;
                else
                    paras.KINFO_KCONTENT = "无";
                if (model.F_Key != null)
                {
                    string key = DbHelperSQL.GetSingle(" select dbo.GetDicRemark('" + model.F_Key + "')").ToString();
                    if (!string.IsNullOrEmpty(key))
                        paras.KINFO_TYPECODE = DbHelperSQL.GetSingle(" select dbo.GetDicRemark('" + model.F_Key + "')").ToString();
                    else
                        paras.KINFO_TYPECODE = "";
                }
                else
                    paras.KINFO_TYPECODE = "";
                paras.KINFO_CREATEDATE = model.F_CreateOn.Value.ToString("yyyy-MM-dd HH:mm:ss");
                paras.KINFO_BEGINDATE = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                paras.KINFO_DISABLEDATE ="";
                string fileid = "";
                var configfj = configBll.GetModelList(" F_ParamCode='EditFilePath' ").FirstOrDefault();
                if (!string.IsNullOrEmpty(model.F_Content))
                {

                    if (!string.IsNullOrEmpty(model.F_Content))
                    {
                        string[] str = model.F_Content.Split('"');
                        for (int i = 0; i < str.Length; i++)
                        {
                            if (str[i].Contains("/js/kindeditor/upload"))
                            {
                                string path = "/Upload/kinfo/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                                var response = kinfo_upload(configfj .F_ParamValue+ str[i], System.IO.Path.GetFileName(str[i]), path);
                                List<Model.T_Sys_Accessories> acs = new List<Model.T_Sys_Accessories>();
                                Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                                model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                                model_T_Sys_Accessories.F_FileName = System.IO.Path.GetFileName(str[i]);//附件名称
                                model_T_Sys_Accessories.F_FileType = System.IO.Path.GetExtension(str[i]);//附件类
                                model_T_Sys_Accessories.F_FileUrl = path + System.IO.Path.GetFileName(str[i]);//附件地址
                                model_T_Sys_Accessories.F_UserCode = "知识附件";//上传人  
                                int accid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                                model_T_Sys_Accessories.F_FileId = accid;
                                if (string.IsNullOrEmpty(fileid))
                                    fileid = accid.ToString();
                                else
                                    fileid += "," + accid.ToString();
                            }
                        }
                    }
                }
                if (fileid!="")
                {

                    string message = kindupload(fileid, Logins ());
                    if (message != "")
                        paras.KINFO_ATTATH_ID = message;
                    else
                    {
                        string strSql = string.Format(@"INSERT INTO T_Sys_PushMsg ( [WorkOrderId], [Conent], [CreatTime], [Code], [Message], [Title], [ErrorObjs], [Remarks]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}') ;select @@IDENTITY ", "", paras.ToJson(), DateTime.Now,"500","附件上传失败", "知识报送接口", "", "推送成功数0");
                        object objres = DbHelperSQL.GetSingle(strSql);
                        return "";
                    }
                }


                Dictionary<string, object > keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("paras", paras);
                var responseString =HttpMethods . HttpPost(thirdUrl  + "/kinfo/add", keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
                if (jo["code"].ToString() == "1")
                {
                    kinfo kinfo = JsonConvert.DeserializeObject<kinfo>(responseString);
                    string strSql = string.Format(@"INSERT INTO T_Sys_PushMsg ( [WorkOrderId], [Conent], [CreatTime], [Code], [Message], [Title], [ErrorObjs], [Remarks]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}') ;select @@IDENTITY ", id, "", DateTime.Now, jo["code"].ToString(), jo["message"].ToString(), "知识报送接口", "", "推送成功数1");
                    object objres = DbHelperSQL.GetSingle(strSql);
                    string Mapping = string.Format(@"INSERT INTO T_Bus_Mapping ( [F_OldWorkOrder], [F_NewWorkOrder], [F_CreateTime], [F_Type]) 
                    values   ('{0}','{1}','{2}','{3}') ;select @@IDENTITY ", model.F_RepositoryId, kinfo.body.KINFO_ID, DateTime.Now, 0);
                    object Mappings = DbHelperSQL.GetSingle(Mapping);
                    return "";
                }
                else
                {
                    string error = "";
                    string strSql = string.Format(@"INSERT INTO T_Sys_PushMsg ( [WorkOrderId], [Conent], [CreatTime], [Code], [Message], [Title], [ErrorObjs], [Remarks]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}') ;select @@IDENTITY ", "", paras.ToJson(), DateTime.Now, jo["code"].ToString(), jo["message"].ToString(), "知识报送接口", error, "推送成功数1");
                    object objres = DbHelperSQL.GetSingle(strSql);
                    LogFactory.GetLogger("111").Warn("知识报送接口" + error);

                    return "";

                }

            }
            else
            {
                return "";
            }

        }
        public string kindupload(string F_Files, string token)
        {

            if (!string.IsNullOrEmpty(F_Files))
            {
                using (var content = new MultipartFormDataContent())
                {
                    var files = GetFileData(F_Files);
                    NameValueCollection nameValueCollection = new NameValueCollection();
                    nameValueCollection.Add("token", token);
                    string url = $"{thirdUrl}/kinfo/uploadKbFile";
                    try
                    {
                        var Postresult = PostMultipartFormData(url, null, nameValueCollection, files);
                        kindreturnvalue jo = JsonConvert.DeserializeObject<kindreturnvalue>(Postresult);
                        if (jo.code == "0")
                        {
                            return jo.fileIds ;
                        }
                        else
                        {
                            LogFactory.GetLogger("kindupload").Error(jo.message );
                            return "";

                        }
                           
                    }
                    catch (Exception e)
                    {
                        LogFactory.GetLogger("kindupload").Error(e.Message);
                        return "";
                    }

                }

            }
            return "";
        }
        public class kindreturnvalue
        {
            public string code { set; get; }
            public string fileIds { set; get; }
            public string message { set; get; }
        }

        public class transmit_kinfo_update
        {
            public string AREA_CODE { set; get; }
            /// <summary>
            /// 知识唯一标识
            /// </summary>
            public string KINFO_ID { set; get; }
            /// <summary>
            /// 标题
            /// </summary>
            public string KINFO_KNAME { set; get; }

            /// <summary>
            /// 内容
            /// </summary>
            public string KINFO_KCONTENT { set; get; }
            /// <summary>
            /// 知识分类编码
            /// </summary>
            public string KINFO_TYPECODE { set; get; }
            /// <summary>
            /// 发布时间
            /// </summary>
            public string KINFO_CREATEDATE { set; get; }
            /// <summary>
            /// 生效时间
            /// </summary>
            public string KINFO_BEGINDATE { set; get; }
            /// <summary>
            /// 失效时间
            /// </summary>
            public string KINFO_DISABLEDATE { set; get; }
            /// <summary>
            /// 知识报送附件id
            /// </summary>
            public string KINFO_ATTATH_ID { set; get; }
        }
        /// <summary>
        /// </summary>
        /// 知识变更接口
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public string  kinfo_update(int id)
        {
            Model.T_RepositoryInformation model = new BLL.T_RepositoryInformation().GetModel(id);
            if (model != null)
            {
                transmit_kinfo_update paras = new transmit_kinfo_update();

                paras.AREA_CODE = "410181";
                paras.KINFO_KNAME = model.F_Title;
                paras.KINFO_KCONTENT = model.F_Description;
                var KINFO_ID = DbHelperSQL.GetSingle(" select top 1 F_NewWorkOrder from T_Bus_Mapping  where F_OldWorkOrder='" + model.F_RepositoryId + "' order by F_CreateTime desc ");
                if (KINFO_ID != null)
                {
                    paras.KINFO_ID = KINFO_ID.ToString();
                }
                else
                {
                    return "";
                }
                if (!string.IsNullOrEmpty(model.F_Description))
                    paras.KINFO_KCONTENT = model.F_Description;
                else
                    paras.KINFO_KCONTENT = "无";
                var configfj = configBll.GetModelList(" F_ParamCode='EditFilePath' ").FirstOrDefault();
                if (model.F_Key != null)
                {
                    string key = DbHelperSQL.GetSingle(" select dbo.GetDicRemark('" + model.F_Key + "')").ToString();
                    if (!string.IsNullOrEmpty(key))
                        paras.KINFO_TYPECODE = DbHelperSQL.GetSingle(" select dbo.GetDicRemark('" + model.F_Key + "')").ToString();
                    else
                        paras.KINFO_TYPECODE = "";
                }
                else
                    paras.KINFO_TYPECODE = "";


                paras.KINFO_CREATEDATE = model.F_CreateOn.Value.ToString("yyyy-MM-dd HH:mm:ss");

                paras.KINFO_BEGINDATE = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                string fileid = "";
                if (!string.IsNullOrEmpty(model.F_Content))
                {

                    if (!string.IsNullOrEmpty(model.F_Content))
                    {
                        string[] str = model.F_Content.Split('"');
                        for (int i = 0; i < str.Length; i++)
                        {
                            if (str[i].Contains("/js/kindeditor/upload"))
                            {
                                string path = "/Upload/kinfo/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                                var response = kinfo_upload(configfj.F_ParamValue  + str[i], System.IO.Path.GetFileName(str[i]), path);
                                List<Model.T_Sys_Accessories> acs = new List<Model.T_Sys_Accessories>();
                                Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                                model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                                model_T_Sys_Accessories.F_FileName = System.IO.Path.GetFileName(str[i]);//附件名称
                                model_T_Sys_Accessories.F_FileType = System.IO.Path.GetExtension(str[i]);//附件类
                                model_T_Sys_Accessories.F_FileUrl = path + System.IO.Path.GetFileName(str[i]);//附件地址
                                model_T_Sys_Accessories.F_UserCode = "知识附件";//上传人  
                                int accid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                                model_T_Sys_Accessories.F_FileId = accid;
                                if (string.IsNullOrEmpty(fileid))
                                    fileid = accid.ToString();
                                else
                                    fileid += "," + accid.ToString();
                            }
                        }
                    }
                }
                if (fileid != "")
                {
                    string message = kindupload(fileid, Logins());
                    if (message != "")
                        paras.KINFO_ATTATH_ID = message;
                    else
                    {
                        string strSql = string.Format(@"INSERT INTO T_Sys_PushMsg ( [WorkOrderId], [Conent], [CreatTime], [Code], [Message], [Title], [ErrorObjs], [Remarks]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}') ;select @@IDENTITY ", "", paras.ToJson(), DateTime.Now, "500", "附件上传失败", "知识变更接口知识变更接口", "", "推送成功数0");
                        object objres = DbHelperSQL.GetSingle(strSql);
                        return "";
                    }
                }
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("paras", paras);
                var responseString =HttpMethods . HttpPost(thirdUrl + "/kinfo/update", keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);


                if (jo["code"].ToString() == "1")
                {
                    string strSql = string.Format(@"INSERT INTO T_Sys_PushMsg ( [WorkOrderId], [Conent], [CreatTime], [Code], [Message], [Title], [ErrorObjs], [Remarks]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}') ;select @@IDENTITY ", id, "", DateTime.Now, jo["code"].ToString(), jo["message"].ToString(), "知识变更接口", "", "推送成功数1");
                    object objres = DbHelperSQL.GetSingle(strSql);
                    return "";
                }
                else
                {
                    string error = "";

                    string strSql = string.Format(@"INSERT INTO T_Sys_PushMsg ( [WorkOrderId], [Conent], [CreatTime], [Code], [Message], [Title], [ErrorObjs], [Remarks]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}') ;select @@IDENTITY ", "", paras.ToJson(), DateTime.Now, jo["code"].ToString(), jo["message"].ToString(), "知识变更接口", error, "推送成功数1");
                    object objres = DbHelperSQL.GetSingle(strSql);
                    LogFactory.GetLogger("111").Warn("知识变更接口" + error);
                    return "";

                }

            }
            else
            {
                return "";
            }

        }


        public class transmit_kinfo_delete
        {

            /// <summary>
            /// 知识唯一标识
            /// </summary>
            public string KINFO_ID { set; get; }

            /// <summary>
            /// 知识下架原因
            /// </summary>
            public string KINFO_REASON { set; get; }

        }
        /// <summary>
        /// </summary>
        /// 知识下架接口
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public string  kinfo_delete(int id, string remark)
        {
            Model.T_RepositoryInformation model = new BLL.T_RepositoryInformation().GetModel(id);
            if (model != null)
            {
                transmit_kinfo_delete paras = new transmit_kinfo_delete();
                //var KINFO_ID = "0c45c37f-794b-449c-8c53-0357e34de7e9";
               var KINFO_ID = DbHelperSQL.GetSingle(" select top 1 F_NewWorkOrder from T_Bus_Mapping  where F_OldWorkOrder='" + model.F_RepositoryId + "' order by F_CreateTime desc ");
                if (KINFO_ID != null)
                {
                    paras.KINFO_ID = KINFO_ID.ToString();
                }
                else
                {
                    return "";
                }

                paras.KINFO_REASON = remark;
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("paras", paras);
                var responseString = HttpMethods.HttpPost(thirdUrl + "/kinfo/delete", keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);


                if (jo["code"].ToString() == "1")
                {
                    kinfo kinfo = JsonConvert.DeserializeObject<kinfo>(responseString);
                    string strSql = string.Format(@"INSERT INTO T_Sys_PushMsg ( [WorkOrderId], [Conent], [CreatTime], [Code], [Message], [Title], [ErrorObjs], [Remarks]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}') ;select @@IDENTITY ", id, "", DateTime.Now, jo["code"].ToString(), jo["message"].ToString(), "知识下架接口", "", "推送成功数1");
                    object objres = DbHelperSQL.GetSingle(strSql);
                    return "";
                }
                else
                {
                    string error = "";

                    string strSql = string.Format(@"INSERT INTO T_Sys_PushMsg ( [WorkOrderId], [Conent], [CreatTime], [Code], [Message], [Title], [ErrorObjs], [Remarks]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}') ;select @@IDENTITY ", "", paras.ToJson(), DateTime.Now, jo["code"].ToString(), jo["message"].ToString(), "知识下架接口", error, "推送成功数1");
                    object objres = DbHelperSQL.GetSingle(strSql);
                    LogFactory.GetLogger("111").Warn("知识下架接口" + error);
                    return "";

                }

            }
            else
            {
                return "";
            }

        }


        /// <summary>
        /// 知识提问接口
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult quiz()
        {
            Request.InputStream.Position = 0;
            string postString;
            using (var reader = new StreamReader(Request.InputStream))
            {
                postString = reader.ReadToEnd();
            }
            JObject paras = null;
            paras = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(postString);
            var txnBodyCom = paras["paras"].ToString();
            var result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(txnBodyCom);
            if (result["KINFO_ID"] == null)
            {
                var obj1 = new
                {
                    code = "0",
                    message = "KINFO_ID不能为空"
                };
                return Content(obj1.ToJson());
            }
            if (string.IsNullOrEmpty(result["KINFO_KNAME"].ToString()))
            {
                var obj1 = new
                {
                    code = "0",
                    message = "KINFO_KNAME不能为空"
                };
                return Content(obj1.ToJson());
            }
            if (string.IsNullOrEmpty(result["KINFO_KCONTENT"].ToString()))
            {
                var obj1 = new
                {
                    code = "0",
                    message = "KINFO_KCONTENT不能为空"
                };
                return Content(obj1.ToJson());
            }

            using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
            {
                Model.T_Sys_kinfoQuestions model = new Model.T_Sys_kinfoQuestions();
                model.KINFO_ID = result["KINFO_ID"].ToString();
                model.KINFO_KNAME = result["KINFO_KNAME"].ToString();
                model.KINFO_KCONTENT = result["KINFO_KCONTENT"].ToString();
                model.F_CreateTime = DateTime.Now;
                model.F_State = 0;
                model.F_IsDelete = 0;
                int n = new BLL.T_Sys_kinfoQuestions().Add(model);
                if (n > 0)
                {

                    var obj1 = new
                    {
                        code = "1",
                        message = "推送成功"
                    };
                    trans.Complete();
                    return Content(obj1.ToJson());

                }
                else
                {
                    var obj1 = new
                    {
                        code = "0",
                        message = "推送失败"
                    };
                    trans.Complete();
                    return Content(obj1.ToJson());
                }

            }

        }




        public class transmit_kinfo_answer
        {
            /// <summary>
            /// 知识唯一标识
            /// </summary>
            public string KINFO_ID { set; get; }
            /// <summary>
            /// 知识标题
            /// </summary>
            public string KINFO_KNAME { set; get; }
            /// <summary>
            /// 知识内容
            /// </summary>
            public string KINFO_KCONTENT { set; get; }
            /// <summary>
            /// 生效时间
            /// </summary>
            public string KINFO_BEGINDATE { set; get; }
            /// <summary>
            /// 失效时间
            /// </summary>
            public string KINFO_DISABLEDATE { set; get; }
        }
        public class bendiack
        {
            public string state;
            public string message;
        }
        /// <summary>
        /// </summary>
        /// 知识答复接口
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [Authority]
        public ActionResult kinfo_answer(string KINFO_KNAME,
         string KINFO_KCONTENT, DateTime? KINFO_BEGINDATE, DateTime? KINFO_DISABLEDATE,
         int id = 0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            Model.T_Sys_kinfoQuestions model = new BLL.T_Sys_kinfoQuestions().GetModel(id);
            if (model != null)
            {
                transmit_kinfo_answer paras = new transmit_kinfo_answer();

                paras.KINFO_ID = model.KINFO_ID;
                paras.KINFO_KNAME = KINFO_KNAME;
                paras.KINFO_KCONTENT = KINFO_KCONTENT;
                if (KINFO_BEGINDATE != null)
                    paras.KINFO_BEGINDATE = KINFO_BEGINDATE.Value.ToString("yyyy-MM-dd HH:mm:ss");
                else
                    return Error("请选择生效时间");
                if (KINFO_DISABLEDATE != null)
                    paras.KINFO_DISABLEDATE = KINFO_DISABLEDATE.Value.ToString("yyyy-MM-dd HH:mm:ss");
                else
                    paras.KINFO_DISABLEDATE = "";

                model.ReKINFO_KNAME = KINFO_KNAME;
                model.ReKINFO_KCONTENT = KINFO_KCONTENT;
                model.KINFO_BEGINDATE = KINFO_BEGINDATE;
                model.KINFO_DISABLEDATE = KINFO_DISABLEDATE;
                model.ReUser = userModel.F_UserCode;
                model.F_State = 1;
                bool n = new BLL.T_Sys_kinfoQuestions().Update(model);
                if (n)
                {

                    // string jsonParam = "paras=" + paras.ToJson() + $"&message=知识答复接口&url={zhishiurl }/oa/kinfo/answer";
                    // var responseString = HttpMethods.HttpPost(fonturl +"/third/Kinforeceive_Push", jsonParam);
                    Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                    keyValuePairs.Add("paras", paras);
                    var responseString = Kinforeceive_Push(keyValuePairs.ToJson (), $"{thirdUrl }/kinfo/answer", "知识答复接口");
                    if (responseString == "")
                        return Success("知识答复成功");
                    else
                        return Error("知识答复失败");


                }
                else
                {
                    return Error("答复失败");
                }
            }
            else
            {
                return Error("推送失败知识不存在");
            }

        }


        public class transmit_kinfo_refuse
        {
            /// <summary>
            /// 知识唯一标识
            /// </summary>
            public string KINFO_ID { set; get; }
            /// <summary>
            /// 知识拒绝答复原因
            /// </summary>
            public string KINFO_REASON { set; get; }

        }
        /// <summary>
        /// </summary>
        /// 知识拒绝答复接口
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [Authority]
        public ActionResult kinfo_refuse(string KINFO_REASON,

         int id = 0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            Model.T_Sys_kinfoQuestions model = new BLL.T_Sys_kinfoQuestions().GetModel(id);
            if (model != null)
            {
                transmit_kinfo_refuse paras = new transmit_kinfo_refuse();

                paras.KINFO_ID = model.KINFO_ID;
                paras.KINFO_REASON = KINFO_REASON;
                model.F_State = 2;
                model.KINFO_REASON = KINFO_REASON;
                model.ReUser = userModel.F_UserCode;


             
               
                    Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                    keyValuePairs.Add("paras", paras);
                    //string jsonParam = "paras=" + paras.ToJson() + $"&message=知识拒绝答复接口&url={zhishiurl }/oa/kinfo/refuse";
                    // var responseString = HttpMethods.HttpPost(fonturl + "/third/Kinforeceive_Push", jsonParam);
                    // bendiack jo = JsonConvert.DeserializeObject<bendiack>(responseString);
                    var responseString = Kinforeceive_Push(keyValuePairs.ToJson (), $"{thirdUrl }/kinfo/refuse", "知识拒绝答复接口");
                    if (responseString == "")
                    {
                        bool n = new BLL.T_Sys_kinfoQuestions().Update(model);
                    if (n)
                    {
                        return Success("知识答复成功");
                    }
                    else
                    {
                        return Error("答复失败");
                    }
                   }
                      
                    else
                        return Error("知识答复失败");


               

            }
            else
            {
                return Error("推送失败知识不存在");
            }

        }

        /// <summary>
        /// 知识审核退回接口
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult back()
        {
            Request.InputStream.Position = 0;
            string postString;
            using (var reader = new StreamReader(Request.InputStream))
            {
                postString = reader.ReadToEnd();
            }
            JObject paras = null;
            paras = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(postString);
            LogFactory.GetLogger("back").Warn(paras);
            var txnBodyCom = paras["paras"].ToString();
            var result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(txnBodyCom);
            LogFactory.GetLogger("result").Warn(result);
            if (result["KINFO_ID"] == null)
            {
                var obj1 = new
                {
                    code = "0",
                    message = "KINFO_ID不能为空"
                };
                return Content(obj1.ToJson());
            }
            if (string.IsNullOrEmpty(result["KINFO_KNAME"].ToString()))
            {
                var obj1 = new
                {
                    code = "0",
                    message = "KINFO_KNAME不能为空"
                };
                return Content(obj1.ToJson());
            }
            if (string.IsNullOrEmpty(result["KINFO_KCONTENT"].ToString()))
            {
                var obj1 = new
                {
                    code = "0",
                    message = "KINFO_KCONTENT不能为空"
                };
                return Content(obj1.ToJson());
            }

            using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
            {
                Model.T_Sys_kinfoQuestions model = new Model.T_Sys_kinfoQuestions();
                model.KINFO_ID = result["KINFO_ID"].ToString();
                model.KINFO_KNAME = result["KINFO_KNAME"].ToString();
                model.KINFO_KCONTENT = result["KINFO_KCONTENT"].ToString();
                model.KINFO_KCONTENT = result["KINFO_KCONTENT"].ToString();
                model.ReKINFO_REASON = result["KINFO_REASON"].ToString();
                model.F_CreateTime = DateTime.Now;
                model.F_State = 3;
                model.F_IsDelete = 0;
                int n = new BLL.T_Sys_kinfoQuestions().Add(model);
                if (n > 0)
                {

                    var obj1 = new
                    {
                        code = "1",
                        message = "推送成功"
                    };
                    trans.Complete();
                    return Content(obj1.ToJson());

                }
                else
                {
                    var obj1 = new
                    {
                        code = "0",
                        message = "推送失败"
                    };
                    trans.Complete();
                    return Content(obj1.ToJson());
                }

            }


        }

        /// <summary>
        /// </summary>
        /// 知识重新答复接口
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [Authority]
        public ActionResult kinfo_againanswer(string KINFO_KNAME,
         string KINFO_KCONTENT, DateTime? KINFO_BEGINDATE, DateTime? KINFO_DISABLEDATE,
         int id = 0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            Model.T_Sys_kinfoQuestions model = new BLL.T_Sys_kinfoQuestions().GetModel(id);
            if (model != null)
            {
                transmit_kinfo_answer paras = new transmit_kinfo_answer();

                paras.KINFO_ID = model.KINFO_ID;
                paras.KINFO_KNAME = KINFO_KNAME;
                paras.KINFO_KCONTENT = KINFO_KCONTENT;
                if (KINFO_BEGINDATE != null)
                    paras.KINFO_BEGINDATE = KINFO_BEGINDATE.Value.ToString("yyyy-MM-dd HH:mm:ss");
                else
                    return Error("请选择生效时间");
                if (KINFO_DISABLEDATE != null)
                    paras.KINFO_DISABLEDATE = KINFO_DISABLEDATE.Value.ToString("yyyy-MM-dd HH:mm:ss");
                else
                    paras.KINFO_DISABLEDATE = "";

                model.ReKINFO_KNAME = KINFO_KNAME;
                model.ReKINFO_KCONTENT = KINFO_KCONTENT;
                model.KINFO_BEGINDATE = KINFO_BEGINDATE;
                model.KINFO_DISABLEDATE = KINFO_DISABLEDATE;
                model.ReUser = userModel.F_UserCode;
                model.F_State = 4;
               
             
                    Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                    keyValuePairs.Add("paras", paras);
                    //string jsonParam = "paras=" + paras.ToJson() + $"&message=知识重新答复接口&url={zhishiurl }/api/transmit_kinfo_againanswer";
                    var responseString = Kinforeceive_Push(keyValuePairs.ToJson (), $"{thirdUrl }/kinfo/againAnswer", "知识重新答复接口");
                    //var responseString = HttpMethods.HttpPost(fonturl + "/third/Kinforeceive_Push", jsonParam);
                    if (responseString=="")
                    {
                        bool n = new BLL.T_Sys_kinfoQuestions().Update(model);
                    if (n)
                    {
                        return Success("知识答复成功");
                    }
                    else
                    {
                        return Error("答复失败");
                    }
                  }
                else
                {
                    return Error("答复失败");
                }
            }
                 



               
            else
            {
                return Error("推送失败知识不存在");
            }

        }
        /// <summary>
        /// 知识库列表
        /// </summary>
        /// <param name="isdc"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetKinfoList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0";
            #region 参数

            string starttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("strendtime"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            string title = HttpUtility.UrlDecode(RequestString.GetQueryString("title"));
            if (title.Trim() != "" && title != "undefined")
            {
                sql += " and (KINFO_KNAME like '%" + title + "%'or ReKINFO_KNAME like '%" + title + "%'  )";
            }
            string content = HttpUtility.UrlDecode(RequestString.GetQueryString("content"));
            if (content.Trim() != "" && content != "undefined")
            {
                sql += " and (KINFO_KCONTENT like '%" + title + "%'or ReKINFO_KCONTENT like '%" + title + "%'  )";
            }

            int state = RequestString.GetInt("state", -1);
            if (state > -1)
            {
                sql += " and F_State ='" + state + "'";
            }
            if (starttime.Trim() != "" && starttime != "undefined")
            {
                sql += " and F_CreateTime >='" + starttime + "'";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and F_CreateTime <='" + strendtime + "'";
            }

            #endregion
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Sys_kinfoQuestions a WITH(NOLOCK)",
                "F_Id",
                "*",
                sql,
                "ORDER BY F_CreateTime DESC",
                pagesize,
                pageindex,
                true,
                out recordCount);


            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 详情
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetKinfo(int id)
        {
            var model = new BLL.T_Sys_kinfoQuestions().GetModel(id);

            if (model != null)
            {
                return Success("获取成功", model);
            }

            else
            {
                return Error("获取失败");
            }


        }

        public string  Kinforeceive_Push(string paras, string url, string message, string WorkOrderId = "")
        {

            // string jsonParam = "paras=" + paras;
            var responseString =HttpMethods . HttpPost(url, paras,"application/json;charset=UTF-8");
            JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
            if (jo["code"].ToString() == "1")
            {

                string strSql = string.Format(@"INSERT INTO T_Sys_PushMsg ( [WorkOrderId], [Conent], [CreatTime], [Code], [Message], [Title], [ErrorObjs], [Remarks]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}') ;select @@IDENTITY ", WorkOrderId, paras, DateTime.Now, jo["code"].ToString(), jo["message"].ToString(), message, "", "");
                object objres = DbHelperSQL.GetSingle(strSql);
                return "";
            }
            else
            {
                string strSql = string.Format(@"INSERT INTO T_Sys_PushMsg ( [WorkOrderId], [Conent], [CreatTime], [Code], [Message], [Title], [ErrorObjs], [Remarks]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}') ;select @@IDENTITY ", WorkOrderId, paras, DateTime.Now, jo["code"].ToString(), jo["message"].ToString(), message, jo["message"].ToString(), "");
                object objres = DbHelperSQL.GetSingle(strSql);
                return jo["message"].ToString();
            }
        }
        public string kinfo_upload(string pathUrl, string newFileName, string path)
        {
            //文件下载地址
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathUrl);
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream responseStream = response.GetResponseStream();
                string Currentpath = System.Web.HttpContext.Current.Server.MapPath("..") + path;
                // 如果不存在就创建file文件夹
                if (!Directory.Exists(Currentpath))
                {
                    if (Currentpath != null) Directory.CreateDirectory(Currentpath);
                }
                Stream stream = new FileStream(Currentpath + newFileName, FileMode.Create);
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, bArr.Length);
                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, bArr.Length);
                }
                stream.Close();
                responseStream.Close();

                return "1";
            }
            catch (Exception e)
            {
                LogFactory.GetLogger("11").Warn(e.Message);
                return e.Message;
            }
        }
        #endregion
        public class contactslistGroup
        {
            /// <summary>
            /// 目录名称
            /// </summary>
            public string group_name { set; get; }
            /// <summary>
            /// 目录主键
            /// </summary>
            public string group_id { set; get; }
        }
        /// <summary>
        /// 查询通讯录分组
        /// </summary>
        /// <returns></returns>
        public ActionResult  listGroup(string name,string   id)
        {
            
            contactslistGroup contactsGroup = new contactslistGroup();
            contactsGroup.group_name = name;
            contactsGroup.group_id = id;
            try
            {
               
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("token", Logins());
                keyValuePairs.Add("contactsGroup", contactsGroup);
              
                var responseString = HttpMethods.HttpPost(thirdUrl  + "/contacts/listGroup",
                   keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject model = (JObject)JsonConvert.DeserializeObject(responseString);
                return Content(model.ToJson());

            }
           catch(Exception e)
            {
                return Error(e.Message);
            }
        }
        public class parentGroup
        {
            /// <summary>
            /// 目录名称
            /// </summary>
            public string group_name { set; get; }
            /// <summary>
            /// 目录主键
            /// </summary>
            public string parent_id { set; get; }
        }
        /// <summary>
        /// 添加通讯录分组
        /// </summary>
        /// <returns></returns>
        public ActionResult addGroup(string name, string   id)
        {
             token = Logins();
            parentGroup contactsGroup = new parentGroup();
            contactsGroup.group_name = name;
            contactsGroup.parent_id = id;
            try
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("token", Logins());
                keyValuePairs.Add("contactsGroup", contactsGroup);
              
                var responseString = HttpMethods.HttpPost(thirdUrl + "/contacts/addGroup",
                   keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject model = (JObject)JsonConvert.DeserializeObject(responseString);
                return Content(model.ToJson());

            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }
        /// <summary>
        /// 修改通讯录分组
        /// </summary>
        /// <returns></returns>
        public ActionResult editGroup(string name, string id)
        {
             token = Logins();
            contactslistGroup contactsGroup = new contactslistGroup();
            contactsGroup.group_name = name;
            contactsGroup.group_id = id;
            try
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("token", Logins());
                keyValuePairs.Add("contactsGroup", contactsGroup);
                //string jsonParam = "token=" + token + "&contactsGroup=" + contactsGroup.ToJson();
                var responseString = HttpMethods.HttpPost(thirdUrl + "/contacts/editGroup",
                   keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject model = (JObject)JsonConvert.DeserializeObject(responseString);
                return Content(model.ToJson());

            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }
        public class Groupdelete
        {
         
            /// <summary>
            /// 目录主键
            /// </summary>
            public string group_id { set; get; }
        }
        /// <summary>
        /// 删除通讯录分组
        /// </summary>
        /// <returns></returns>
        public ActionResult deleteGroup(string name, string id)
        {
             token = Logins();
            Groupdelete contactsGroup = new Groupdelete();
            contactsGroup.group_id = id;
            try
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("token", Logins());
                keyValuePairs.Add("contactsGroup", contactsGroup);
                //string jsonParam = "token=" + token + "&contactsGroup=" + contactsGroup.ToJson();
                var responseString = HttpMethods.HttpPost(thirdUrl + "/contacts/deleteGroup",
                   keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject model = (JObject)JsonConvert.DeserializeObject(responseString);
                return Content(model.ToJson());

            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }
        public class listcontact
        {
            public string group_id { set; get; }
        }
        /// <summary>
        /// 查询通讯录
        /// </summary>
        /// <returns></returns>
        public ActionResult listcontacts(string id)
        {
             token = Logins();
            listcontact contacts = new listcontact();
            contacts.group_id = id;
            try
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("token", Logins());
                keyValuePairs.Add("contacts", contacts);
                // string jsonParam = "token=" + token + "&contacts=" + contacts.ToJson();
                var responseString = HttpMethods.HttpPost(thirdUrl + "/contacts/contacts",
                   keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject model = (JObject)JsonConvert.DeserializeObject(responseString);
                return Content(model.ToJson());

            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        public class contacts
        {
            /// <summary>
            /// 单位地址
            /// </summary>
           public string unit_address { set; get; }
            /// <summary>
            /// 传真
            /// </summary>
            public string fax_number { set; get; }
            /// <summary>
            /// 备注
            /// </summary>
            public string remark { set; get; }
            /// <summary>
            /// 负责人联系方式
            /// </summary>
            public string charge_person_phone { set; get; }
            /// <summary>
            /// 负责人职务
            /// </summary>
            public string charge_person_position { set; get; }
            /// <summary>
            /// 单位名称
            /// </summary>
            public string unit_name { set; get; }
            /// <summary>
            /// 公开电话
            /// </summary>
            public string public_phone { set; get; }
            /// <summary>
            /// 办工时间
            /// </summary>
            public string office_time { set; get; }
            /// <summary>
            /// 工作职责
            /// </summary>
            public string operate_duty { set; get; }
            /// <summary>
            /// 内部电话
            /// </summary>
            public string internal_phone { set; get; }
            /// <summary>
            /// 负责人
            /// </summary>
            public string charge_person { set; get; }
            /// <summary>
            /// 本级目录
            /// </summary>
            public string group_id { set; get; }
        }
        /// <summary>
        /// 添加通讯录
        /// </summary>
        /// <returns></returns>
        public ActionResult addcontacts(contacts contact)
        {
            if (string .IsNullOrEmpty (contact.unit_name))
            {
                return Error("请输入单位名称");
            }
            if (string.IsNullOrEmpty(contact.public_phone))
            {
                return Error("请输入公开电话");
            }
            if (string.IsNullOrEmpty(contact.office_time))
            {
                return Error("请输入办工时间");
            }
            if (string.IsNullOrEmpty(contact.operate_duty))
            {
                return Error("请输入工作职责");
            }
            if (string.IsNullOrEmpty(contact.internal_phone))
            {
                return Error("请输入内部电话");
            }
            if (string.IsNullOrEmpty(contact.charge_person))
            {
                return Error("请输入负责人");
            }
            if (string.IsNullOrEmpty(contact.group_id))
            {
                return Error("请输入选择本级目录");
            }
             token = Logins();
            try
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("token", Logins());
                keyValuePairs.Add("contacts", contact);
                //string jsonParam = "token=" + token + "&contacts=" + contact.ToJson();
                var responseString = HttpMethods.HttpPost(thirdUrl + "/contacts/add",
                   keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject model = (JObject)JsonConvert.DeserializeObject(responseString);
                return Content(model.ToJson());
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        public class updatecontact
        {
            /// <summary>
            /// 单位地址
            /// </summary>
            public string unit_address { set; get; }
            /// <summary>
            /// 传真
            /// </summary>
            public string fax_number { set; get; }
            /// <summary>
            /// 备注
            /// </summary>
            public string remark { set; get; }
            /// <summary>
            /// 负责人联系方式
            /// </summary>
            public string charge_person_phone { set; get; }
            /// <summary>
            /// 负责人职务
            /// </summary>
            public string charge_person_position { set; get; }
            /// <summary>
            /// 单位名称
            /// </summary>
            public string unit_name { set; get; }
            /// <summary>
            /// 公开电话
            /// </summary>
            public string public_phone { set; get; }
            /// <summary>
            /// 办工时间
            /// </summary>
            public string office_time { set; get; }
            /// <summary>
            /// 工作职责
            /// </summary>
            public string operate_duty { set; get; }
            /// <summary>
            /// 内部电话
            /// </summary>
            public string internal_phone { set; get; }
            /// <summary>
            /// 负责人
            /// </summary>
            public string charge_person { set; get; }
            /// <summary>
            /// 业务标识
            /// </summary>
            public string id { set; get; }
        }
        /// <summary>
        /// 修改通讯录
        /// </summary>
        /// <returns></returns>
        public ActionResult updatecontacts(updatecontact contact)
        {
            if (string.IsNullOrEmpty(contact.unit_name))
            {
                return Error("请输入单位名称");
            }
            if (string.IsNullOrEmpty(contact.public_phone))
            {
                return Error("请输入公开电话");
            }
            if (string.IsNullOrEmpty(contact.office_time))
            {
                return Error("请输入办工时间");
            }
            if (string.IsNullOrEmpty(contact.operate_duty))
            {
                return Error("请输入工作职责");
            }
            if (string.IsNullOrEmpty(contact.internal_phone))
            {
                return Error("请输入内部电话");
            }
            if (string.IsNullOrEmpty(contact.charge_person))
            {
                return Error("请输入负责人");
            }
            if (string.IsNullOrEmpty(contact.id ))
            {
                return Error("请输入选择要修改的通讯录");
            }
             token = Logins();
            try
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("token", Logins());
                keyValuePairs.Add("contacts", contact);
                // string jsonParam = "token=" + token + "&contacts=" + contact.ToJson();
                var responseString = HttpMethods.HttpPost(thirdUrl + "/contacts/edit",
                   keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject model = (JObject)JsonConvert.DeserializeObject(responseString);
                return Content(model.ToJson());
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        public class deletecontact
        {
            public string id { set; get; }
        }

        /// <summary>
        /// 删除通讯录
        /// </summary>
        /// <returns></returns>
        public ActionResult deletecontacts(deletecontact contact)
        {
            if (string.IsNullOrEmpty(contact.id))
            {
                return Error("请输入选择要删除的通讯录");
            }
             token = Logins();
            try
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                keyValuePairs.Add("token", Logins());
                keyValuePairs.Add("contacts", contact);
                // string jsonParam = "token=" + token + "&contacts=" + contact.ToJson();
                var responseString = HttpMethods.HttpPost(thirdUrl + "/contacts/delete",
                   keyValuePairs.ToJson (), "application/json;charset=UTF-8");
                JObject model = (JObject)JsonConvert.DeserializeObject(responseString);
                return Content(model.ToJson());
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }
    }
}