using CallCenter.Utility;
using CallCenterApi.BLL;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;

using CallCenterApi.Interface.Models.Common;
using CallCenterApi.Model;
using LumiSoft.Net.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography;
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.workorder
{
    //[Authority]
    public class hb_affairsController : BaseController
    {
        private BLL.T_Bus_WorkOrder workorderBLL = new BLL.T_Bus_WorkOrder();
        private BLL.T_Bus_Operation operBLL = new BLL.T_Bus_Operation();
        private BLL.T_Sys_UserAccount userBLL = new BLL.T_Sys_UserAccount();
        private information.InternalMessagesController msg = new information.InternalMessagesController();
        private BLL.T_Cus_CustomerBase cusBLL = new BLL.T_Cus_CustomerBase();
        private BLL.T_Bus_AssignedInfo assignBLL = new BLL.T_Bus_AssignedInfo();
        private BLL.T_Sys_Affairs affairsBll = new BLL.T_Sys_Affairs();
        string FrontUrl = Configs.GetValue("FrontUrl");
        string NativeURL = Configs.GetValue("NativeURL");
        /// <summary>
        /// 添加工单信息
        /// </summary>
        /// <returns></returns>
        public ActionResult receive_case_info()
        {
            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 txnBodyCom = paras["paras"].ToString();
            var result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(txnBodyCom);
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();

            using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
            {
                #region 保存工单信息
                string creattime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
                string endtime = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59";
                Model.T_Sys_Affairs affairs = new Model.T_Sys_Affairs();

                if (result["TROWGUID"] != null)
                {
                    if (!string.IsNullOrEmpty(result["TROWGUID"].ToString()))
                    {
                        affairs.TROWGUID = result["TROWGUID"].ToString();//任务单唯一标识
                    }
                    else
                    {
                        var obj = new
                        {
                            code = "0",
                            message = "请输入TROWGUID"
                        };
                        return Content(obj.ToJson());
                    }
                }
                else
                {
                    var obj = new
                    {
                        code = "0",
                        message = "TROWGUID不能为NULL"
                    };
                    return Content(obj.ToJson());
                }
                var affairslist = new BLL.T_Sys_Affairs().GetModelList("TROWGUID='" + result["TROWGUID"].ToString() + "'");
                if (affairslist != null && affairslist.Count > 0)
                {
                    var obj = new
                    {
                        code = "0",
                        message = "此工单已交办"
                    };
                    return Content(obj.ToJson());
                }
                if (result["CASE_SERIAL"] != null)
                {
                    if (!string.IsNullOrEmpty(result["CASE_SERIAL"].ToString()))
                    {
                        affairs.CASE_SERIAL = result["CASE_SERIAL"].ToString();//工单编号
                    }
                    else
                    {
                        var obj = new
                        {
                            code = "0",
                            message = "请输入CASE_SERIAL"
                        };
                        return Content(obj.ToJson());
                    }
                }
                else
                {
                    var obj = new
                    {
                        code = "0",
                        message = "CASE_SERIAL不能为NULL"
                    };
                    return Content(obj.ToJson());
                }


                modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID(2580, 1, creattime, endtime);

                modelT_Bus_WorkOrder.F_WorkOrderId = result["CASE_SERIAL"].ToString().Substring(0, 2) +
               modelT_Bus_WorkOrder.F_WorkOrderId.Substring(2, modelT_Bus_WorkOrder.F_WorkOrderId.Length - 2);



                modelT_Bus_WorkOrder.F_InfoSource = 2580;//信息来源
                var type = result["CASE_TYPE"] == null ? "" : result["CASE_TYPE"].ToString();
                if (!string.IsNullOrEmpty(type))
                {
                    if (type == "10")
                        modelT_Bus_WorkOrder.F_InfoType = 9;
                    else if (type == "15")
                        modelT_Bus_WorkOrder.F_InfoType = 12;
                    else if (type == "20")
                        modelT_Bus_WorkOrder.F_InfoType = 11;
                    else if (type == "30")
                        modelT_Bus_WorkOrder.F_InfoType = 10;
                    else if (type == "35")
                        modelT_Bus_WorkOrder.F_InfoType = 13;
                    else
                        modelT_Bus_WorkOrder.F_InfoType = 90;
                }
                else
                    modelT_Bus_WorkOrder.F_InfoType = 90;
                if (result["USER_TYPE"] != null)
                {
                    //是否营商
                    if (result["USER_TYPE"].ToString() == "20")
                        modelT_Bus_WorkOrder.F_IsBusiness = 1;
                    else
                        modelT_Bus_WorkOrder.F_IsBusiness = 0;
                }
                modelT_Bus_WorkOrder.F_SourceAddress = result["CASE_ADDRESS"] == null ? "" : result["CASE_ADDRESS"].ToString();
                modelT_Bus_WorkOrder.F_CusName = result["APPLICANT_NAME"] == null ? "" : result["APPLICANT_NAME"].ToString();
                if (string.IsNullOrEmpty(result["APPLICANT_NAME"].ToString()))
                {
                    var obj = new
                    {
                        code = "0",
                        message = "请输入APPLICANT_NAME"
                    };
                    return Content(obj.ToJson());
                }


                if (result["APPLICANT_SEX"] != null)
                {
                    if (result["APPLICANT_SEX"].ToString() == "1")
                        modelT_Bus_WorkOrder.F_CusSex = "0";//性别
                    else if (result["APPLICANT_SEX"].ToString() == "2")
                        modelT_Bus_WorkOrder.F_CusSex = "1";//性别
                }
                modelT_Bus_WorkOrder.F_CusPhone = result["APPLICANT_NUMBER"] == null ? "" : result["APPLICANT_NUMBER"].ToString();
                if (string.IsNullOrEmpty(result["APPLICANT_NUMBER"].ToString()))
                {
                    var obj = new
                    {
                        code = "0",
                        message = "请输入APPLICANT_NUMBER"
                    };
                    return Content(obj.ToJson());
                }
                modelT_Bus_WorkOrder.F_CusAddress = result["CASE_ADDRESS"] == null ? "" : result["CASE_ADDRESS"].ToString();

                modelT_Bus_WorkOrder.F_ConName = result["APPLICANT_NAME"].ToString();
                modelT_Bus_WorkOrder.F_ConPhone = result["APPLICANT_NUMBER"].ToString();//联系人电话

                modelT_Bus_WorkOrder.F_ComTitle = result["CASE_TITLE"] == null ? "" : result["CASE_TITLE"].ToString();
                modelT_Bus_WorkOrder.F_ComContent = result["CASE_CONTENT"] == null ? "" : result["CASE_CONTENT"].ToString();
                if (result["CASE_ACCORD"] != null)
                {
                    try
                    {
                        var KeyValue = DbHelperSQL.GetSingle("select top 1  F_ValueId  from T_Sys_DictionaryValue where F_Remark = '" + result["CASE_ACCORD"].ToString() + "' order by F_ValueId desc");
                        if (KeyValue != null)
                        {
                            modelT_Bus_WorkOrder.F_Key = KeyValue.ToString();
                        }
                    }
                    catch
                    {

                    }
                   

                }
                affairs.CASE_TIME = result["CASE_TIME"] == null ? "" : result["CASE_TIME"].ToString();

                if (result["CASE_ISPUBLIC"] != null)
                {
                    if (result["CASE_ISPUBLIC"].ToString() == "1")
                        modelT_Bus_WorkOrder.F_IsProtect = 0;//保密方式0否1是
                    else
                        modelT_Bus_WorkOrder.F_IsProtect = 1;//保密方式0否1是
                }

                if (result["CASE_LNGLAT"] != null)
                {
                    if (result["CASE_LNGLAT"].ToString() != "")
                    {
                        try
                        {
                            var CASE_LNGLAT = result["CASE_LNGLAT"].ToString().Substring(1, result["CASE_LNGLAT"].ToString().Length - 2);
                            if (CASE_LNGLAT.Split(',').Length > 1)
                            {
                                modelT_Bus_WorkOrder.F_Latitude = CASE_LNGLAT.Split(',')[0] != "" ? decimal.Parse(CASE_LNGLAT.Split(',')[0]) : 0;//纬度
                                modelT_Bus_WorkOrder.F_Longitude = CASE_LNGLAT.Split(',')[1] != "" ? decimal.Parse(CASE_LNGLAT.Split(',')[1]) : 0;//经度
                            }
                        }
                        catch
                        {

                        }

                    }


                }
                affairs.TSIGNTIME_BF = result["TSIGNTIME_BF"] == null ? "" : result["TSIGNTIME_BF"].ToString();
                affairs.TFDBACKTIME_BF = result["TFDBACKTIME_BF"] == null ? "" : result["TFDBACKTIME_BF"].ToString();
                affairs.TBACKTIME_BF = result["TBACKTIME_BF"] == null ? "" : result["TBACKTIME_BF"].ToString();
                affairs.SEND_TIME = result["SEND_TIME"] == null ? "" : result["SEND_TIME"].ToString();
                affairs.SEND_CONTENT = result["SEND_CONTENT"] == null ? "" : result["SEND_CONTENT"].ToString();




                // modelT_Bus_WorkOrder.F_IsOpen = isopen;
                //是否直办（即时答复）0:，否1： 是  
                if (result["CASE_ATTATH_ID"] != null)
                {
                    if (!string.IsNullOrEmpty(result["CASE_ATTATH_ID"].ToString()))
                        modelT_Bus_WorkOrder.F_File = receive_info(result["CASE_ATTATH_ID"].ToString());
                }

                if (result["SEND_ATTATH_ID"] != null)
                {
                    if (string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_File))
                    {
                        if (!string.IsNullOrEmpty(result["SEND_ATTATH_ID"].ToString()))
                            modelT_Bus_WorkOrder.F_File = receive_info(result["SEND_ATTATH_ID"].ToString());
                    }

                    else
                    {
                        if (!string.IsNullOrEmpty(result["SEND_ATTATH_ID"].ToString()))
                            modelT_Bus_WorkOrder.F_File += "," + receive_info(result["SEND_ATTATH_ID"].ToString());
                    }

                }
                //if (result["CASE_ISURGENT"] != null)
                //{
                //    if (result["CASE_ISURGENT"].ToString() == "30")
                //        modelT_Bus_WorkOrder.F_Level = 1;
                //    else
                //        modelT_Bus_WorkOrder.F_Level = 2;
                //}
                modelT_Bus_WorkOrder.F_Level = 3;
                modelT_Bus_WorkOrder.F_IsResult = 0;
                modelT_Bus_WorkOrder.F_CreateUser = "省平台";//登记人工号
                try
                {
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Parse(result["APPLICANT_TIME"].ToString());
                }
                catch
                {
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;//登记时间
                }

                modelT_Bus_WorkOrder.F_WorkState = 0;// 0;//工单状态0登记中
                modelT_Bus_WorkOrder.F_IsClosed = 0;//工单是否关闭
                modelT_Bus_WorkOrder.F_IsOverdue = 0;//是否逾期(0:否，1：是)
                modelT_Bus_WorkOrder.F_IsDelete = 0;//是否删除(0:否，1：是)


                #region
                #endregion
                modelT_Bus_WorkOrder.F_Id = workorderBLL.Add(modelT_Bus_WorkOrder);
                affairs.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;


                affairs.CreateTime = DateTime.Now;
                affairsBll.Add(affairs);
                #endregion

                trans.Complete();
            }
            if (modelT_Bus_WorkOrder.F_Id <= 0)
            {
                var obj = new
                {
                    code = "0",
                    message = "失败"
                };
                return Content(obj.ToJson());
            }
            else
            {
                string userinfo = "省平台";
                string message = "";
                message = userinfo + " 登记了工单，工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                // var curuser = User;
                Task.Run(() =>
                {
                    #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_CallRecordId = modelT_Bus_WorkOrder.F_CallRecordId;
                    oper.F_File = modelT_Bus_WorkOrder.F_File;
                    oper.F_Message = message;
                    oper.F_CreateUser = result["HWY_LOGINID"] == null ? "" : result["HWY_LOGINID"].ToString();
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);

                    #endregion
                }).ContinueWith(p => {
                    System.Diagnostics.Debug.WriteLine(DateTime.Now);
                });
                var obj = new
                {
                    code = "1",
                    message = "推送成功！"
                }
                ;
                return Content(obj.ToJson());
            }

        }


        /// <summary>
        /// 申请延时结果
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult receive_case_delay_audit()
        {
            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 txnBodyCom = paras["paras"].ToString();
            LogFactory.GetLogger("receive_case_delay_audit").Warn(txnBodyCom);
            var result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(txnBodyCom);
            if (result["TROWGUID"] == null)
            {
                var obj = new
                {
                    code = "0",
                    message = "TROWGUID不能为空"
                };
                return Content(obj.ToJson());
            }
            if (string.IsNullOrEmpty(result["TROWGUID"].ToString()))
            {
                var obj = new
                {
                    code = "0",
                    message = "TROWGUID不能为空"
                };
                return Content(obj.ToJson());
            }
            var affairs = affairsBll.GetModelList("TROWGUID='" + result["TROWGUID"].ToString() + "'");


            if (affairs != null && affairs.Count > 0)
            {
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(affairs.FirstOrDefault().F_WorkOrderId);
                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);
                var modelT_Bus_AssignedInfo_Next = new BLL.T_Bus_AssignedInfo_Next().GetModelList("F_State=1 and F_IsDelete=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'  order by F_CreateTime desc");

                if (modelT_Bus_DelayTime != null && affairs != null)
                {
                    using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
                    {

                        var autio = result["AUDIT_RESULT"] == null ? "" : result["AUDIT_RESULT"].ToString();

                        string type = "同意"; string des = "";
                        if (autio == "1")

                        {
                            if (modelT_Bus_DelayTime.F_AssignedId == 0)
                            {
                                affairs.FirstOrDefault().TBACKTIME_BF = modelT_Bus_DelayTime.F_NewTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                                des = "，原定退回时间" + modelT_Bus_DelayTime.F_OldTime + "，申请延长到" + modelT_Bus_DelayTime.F_NewTime;
                            }
                            else
                            {
                                if(modelT_Bus_DelayTime.F_IsAudit ==1)
                                {
                                    var obj = new
                                    {
                                        code = "1",
                                        message = "已推送过延时结果"
                                    };
                                    return Content(obj.ToJson());
                                }

                                affairs.FirstOrDefault().TFDBACKTIME_BF = modelT_Bus_DelayTime.F_NewTime.Value.ToString("yyyy-MM-dd HH:mm:ss");

                                TimeSpan ts = modelT_Bus_DelayTime.F_NewTime.Value.Subtract(modelT_Bus_DelayTime.F_OldTime.Value);
                                int tss = int.Parse(Math.Round(ts.TotalHours, 0).ToString());
                                if (modelT_Bus_WorkOrder.F_LimitTime!=null)
                                {
                                    modelT_Bus_WorkOrder.F_LimitTime =
                                   modelT_Bus_WorkOrder.F_LimitTime.Value
                                    .AddHours(tss);
                                }
                                des = "，原定办结时间" + modelT_Bus_DelayTime.F_OldTime + "，申请延长到" + modelT_Bus_DelayTime.F_NewTime;
                                int n = DbHelperSQL.ExecuteSql(" update T_Bus_WorkOrder set F_LimitTime='" + modelT_Bus_DelayTime.F_NewTime.Value 
                                    + "'   where F_Id ='" + modelT_Bus_WorkOrder.F_Id + "'");

                                if (modelT_Bus_AssignedInfo != null)
                                {
                                    modelT_Bus_AssignedInfo.F_LimitTime = modelT_Bus_DelayTime.F_NewTime.Value;
                                    assignBLL.Update(modelT_Bus_AssignedInfo);
                                }
                                if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_SubWorkorder1))
                                {
                                    var modellist = workorderBLL.GetModelList("F_WorkOrderId in(select col from dbo.SplitToNvarchar('" 
                                        + modelT_Bus_WorkOrder.F_SubWorkorder1 + "',',' ))  and F_IsDelete =0  ");

                                    if (modellist != null && modellist.Count > 0)
                                    {
                                        foreach (var it in modellist)
                                        {


                                            it.F_LimitTime =
                                               it.F_LimitTime.Value
                                                 .AddHours(tss);
                                            des = "，原定办结时间" + modelT_Bus_DelayTime.F_OldTime + "，申请延长到" + it.F_LimitTime;
                                            int t = DbHelperSQL.ExecuteSql(" update T_Bus_WorkOrder set  F_LimitTime='" + it.F_LimitTime
                                                + "'   where F_Id ='" + it.F_Id + "'");

                                            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo1 = assignBLL.GetNewModelByWorkOrderID(it.F_WorkOrderId);
                                            var modelT_Bus_AssignedInfo_Next1 = new BLL.T_Bus_AssignedInfo_Next().GetModelList
                                                ("F_State=1 and F_IsDelete=0 and F_WorkOrderId='"
                                                + it.F_WorkOrderId + "'  order by F_CreateTime desc");


                                            if (modelT_Bus_AssignedInfo1 != null)
                                            {
                                                modelT_Bus_AssignedInfo1.F_LimitTime = it.F_LimitTime;
                                                assignBLL.Update(modelT_Bus_AssignedInfo1);
                                            }

                                            if (modelT_Bus_AssignedInfo_Next1 != null && modelT_Bus_AssignedInfo_Next1.Count > 0)
                                            {

                                                modelT_Bus_AssignedInfo_Next1[0].F_LimitTime =
                                                     modelT_Bus_AssignedInfo_Next1[0].F_LimitTime.Value
                                                     .AddHours(tss);
                                                new BLL.T_Bus_AssignedInfo_Next().Update(modelT_Bus_AssignedInfo_Next1[0]);

                                            }
                                            Model.T_Bus_DelayTime modelT_Bus_DelayTime1 = new BLL.T_Bus_DelayTime().GetNewModelByWorkOrderID(it.F_WorkOrderId);
                                            modelT_Bus_DelayTime1.F_IsAudit = 1;//审核
                                            modelT_Bus_DelayTime1.F_AuditUser = result["AUDIT_NAME"].ToString();
                                            modelT_Bus_DelayTime1.F_AuditTime = DateTime.Now;
                                            modelT_Bus_DelayTime1.F_RefuseReason = result["AUDIT_OPINION"] == null ? "" : result["AUDIT_OPINION"].ToString();
                                            modelT_Bus_DelayTime1.F_AgreeTime = modelT_Bus_DelayTime1.F_NewTime;
                                            new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime1);


                                            Model.T_Bus_Operation oper1 = new Model.T_Bus_Operation();
                                            oper1.F_WorkOrderId = it.F_WorkOrderId;
                                            oper1.F_AssignedId = 0;
                                            oper1.F_State = it.F_WorkState;

                                            string userinfo1 = "省平台";
                                            oper1.F_Message = userinfo1 + " " + type + "了工单延时申请" + des;
                                            oper1.F_CreateUser = "省平台";
                                            oper1.F_CreateTime = DateTime.Now;
                                            oper1.F_IsDelete = 0;
                                            operBLL.Add(oper1);

                                        }
                                    }

                                }
                                if (modelT_Bus_AssignedInfo_Next != null && modelT_Bus_AssignedInfo_Next.Count > 0)
                                {

                                    modelT_Bus_AssignedInfo_Next[0].F_LimitTime =
                                         modelT_Bus_AssignedInfo_Next[0].F_LimitTime.Value
                                         .AddHours(tss);
                                    new BLL.T_Bus_AssignedInfo_Next().Update(modelT_Bus_AssignedInfo_Next[0]);

                                }
                            }

                            modelT_Bus_DelayTime.F_IsAudit = 1;//审核
                            modelT_Bus_DelayTime.F_AuditUser = result["AUDIT_NAME"].ToString();
                            modelT_Bus_DelayTime.F_AuditTime = DateTime.Now;
                            modelT_Bus_DelayTime.F_RefuseReason = result["AUDIT_OPINION"] == null ? "" : result["AUDIT_OPINION"].ToString();
                            modelT_Bus_DelayTime.F_AgreeTime = modelT_Bus_DelayTime.F_NewTime;
                            new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime);


                        }
                        else
                        {
                            type = "拒绝";
                            //if (modelT_Bus_AssignedInfo != null && modelT_Bus_DelayTime.F_AssignedId != 0)
                            //{
                            //    modelT_Bus_AssignedInfo.F_IsSure = 1;
                            //    assignBLL.Update(modelT_Bus_AssignedInfo);
                            //}

                            modelT_Bus_DelayTime.F_IsAudit = 2;//审核
                            modelT_Bus_DelayTime.F_AuditUser = result["AUDIT_NAME"] == null ? "" : result["AUDIT_NAME"].ToString();
                            modelT_Bus_DelayTime.F_AuditTime = DateTime.Now;
                            modelT_Bus_DelayTime.F_RefuseReason = result["AUDIT_OPINION"] == null ? "" : result["AUDIT_OPINION"].ToString();
                            modelT_Bus_DelayTime.F_AgreeTime = modelT_Bus_DelayTime.F_NewTime;
                            new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime);
                            if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_SubWorkorder1))
                            {
                                var modellist = workorderBLL.GetModelList("F_WorkOrderId in(select col from dbo.SplitToNvarchar('" + modelT_Bus_WorkOrder.F_SubWorkorder1 + "',',' ))  and F_IsDelete =0  ");

                                if (modellist != null && modellist.Count > 0)
                                {
                                    foreach (var it in modellist)
                                    {
                                        Model.T_Bus_DelayTime modelT_Bus_DelayTime1 = new BLL.T_Bus_DelayTime().GetNewModelByWorkOrderID(it.F_WorkOrderId);
                                        modelT_Bus_DelayTime1.F_IsAudit = 2;//审核
                                        modelT_Bus_DelayTime1.F_AuditUser = result["AUDIT_NAME"] == null ? "" : result["AUDIT_NAME"].ToString();
                                        modelT_Bus_DelayTime1.F_AuditTime = DateTime.Now;
                                        modelT_Bus_DelayTime1.F_RefuseReason = result["AUDIT_OPINION"] == null ? "" : result["AUDIT_OPINION"].ToString();
                                        modelT_Bus_DelayTime1.F_AgreeTime = modelT_Bus_DelayTime.F_NewTime;
                                        new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime1);

                                        Model.T_Bus_Operation oper1 = new Model.T_Bus_Operation();
                                        oper1.F_WorkOrderId = it.F_WorkOrderId;
                                        oper1.F_AssignedId = 0;
                                        oper1.F_State = it.F_WorkState;

                                        string userinfo1 = "省平台";
                                        oper1.F_Message = userinfo1 + " " + type + "了工单延时申请" + des;
                                        oper1.F_CreateUser = "省平台";
                                        oper1.F_CreateTime = DateTime.Now;
                                        oper1.F_IsDelete = 0;
                                        operBLL.Add(oper1);

                                    }
                                }

                            }
                        }
                        new BLL.T_Sys_Affairs().Update(affairs.FirstOrDefault());
                        #region 插入操作记录
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                        oper.F_AssignedId = 0;
                        oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                        string userinfo = "省平台";
                        oper.F_Message = userinfo + " " + type + "了工单延时申请" + des;
                        oper.F_CreateUser = "省平台";
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;
                        operBLL.Add(oper);

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

                    #endregion

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


        }
        /// <summary>
        /// 服务工单退回结果
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult receive_case_back_audit()
        {
            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 txnBodyCom = paras["paras"].ToString();
            var result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(txnBodyCom);
            if (result["TROWGUID"] == null)
            {
                var obj = new
                {
                    code = "0",
                    message = "TROWGUID不能为空"
                };
                return Content(obj.ToJson());
            }
            if (string.IsNullOrEmpty(result["TROWGUID"].ToString()))
            {
                var obj = new
                {
                    code = "0",
                    message = "TROWGUID不能为空"
                };
                return Content(obj.ToJson());
            }

            var affairs = affairsBll.GetModelList("TROWGUID='" + result["TROWGUID"].ToString() + "'");
            if (affairs != null && affairs.Count > 0)
            {
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(affairs.FirstOrDefault().F_WorkOrderId);

                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
                {
                    string Message = "省平台审核";

                    var AUDIT_RESULT = result["AUDIT_RESULT"] == null ? "" : result["AUDIT_RESULT"].ToString();
                    if (string.IsNullOrEmpty(AUDIT_RESULT))
                    {
                        var obj = new
                        {
                            code = "0",
                            message = "AUDIT_RESULT不能为空"
                        };
                        return Content(obj.ToJson());
                    }
                   


                    if (result["AUDIT_RESULT"].ToString() == "1")
                    {
                        Message += "通过了退回工单";
                        var AUDIT_OPINION = result["AUDIT_OPINION"] == null ? "" : result["AUDIT_OPINION"].ToString();
                        if (string.IsNullOrEmpty(AUDIT_OPINION))
                        {
                            Message += ",审核意见："+ AUDIT_OPINION;
                        }
                    }
                    else if (result["SUPPLY_TYPE"].ToString() == "0")
                    {

                        Message += "拒绝了退回工单";
                        var AUDIT_OPINION = result["AUDIT_OPINION"] == null ? "" : result["AUDIT_OPINION"].ToString();
                        if (string.IsNullOrEmpty(AUDIT_OPINION))
                        {
                            Message += ",审核意见：" + AUDIT_OPINION;
                        }
                        Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                        keyValuePairs.Add("F_WorkState", "0");
                        keyValuePairs.Add("F_DealDeptId",null);
                        keyValuePairs.Add("F_DealUser", "");
                        keyValuePairs.Add("F_DealTime", null);
                        keyValuePairs.Add("F_IsClosed", 0);
                        keyValuePairs.Add("F_CloseUser", "");
                        keyValuePairs.Add("F_Result", "");
                        keyValuePairs.Add("F_CloseTime",null);
                        workorderBLL.UpdateWorkOrder(modelT_Bus_WorkOrder.F_Id, keyValuePairs);
                    }
                   
                    #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 = Message;
                    oper.F_CreateUser = result["AUDIT_NAME"] == null ? "" : result["AUDIT_NAME"].ToString();
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    #endregion 
                    trans.Complete();
                }
                var obj1 = new
                {
                    code = "1",
                    message = "推送成功"
                };
                return Content(obj1.ToJson());

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


        }
        /// <summary>
        /// 服务工单交办催单/撤单/补单接口
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult receive_case_supply()
        {
            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 txnBodyCom = paras["paras"].ToString();
            var result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(txnBodyCom);
            if (result["TROWGUID"] == null)
            {
                var obj = new
                {
                    code = "0",
                    message = "TROWGUID不能为空"
                };
                return Content(obj.ToJson());
            }
            if (string.IsNullOrEmpty(result["TROWGUID"].ToString()))
            {
                var obj = new
                {
                    code = "0",
                    message = "TROWGUID不能为空"
                };
                return Content(obj.ToJson());
            }

            var affairs = affairsBll.GetModelList("TROWGUID='" + result["TROWGUID"].ToString() + "'");
            if (affairs != null && affairs.Count > 0)
            {
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(affairs.FirstOrDefault().F_WorkOrderId);

                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
                {
                    string Message = "";

                    var SUPPLY_TYPE = result["SUPPLY_TYPE"] == null ? "" : result["SUPPLY_TYPE"].ToString();
                    if (string.IsNullOrEmpty(SUPPLY_TYPE))
                    {
                        var obj = new
                        {
                            code = "0",
                            message = "SUPPLY_TYPE不能为空"
                        };
                        return Content(obj.ToJson());
                    }
                    if (result["SUPPLY_TYPE"].ToString() == "10")
                    {

                        if (result["SUPPLY_CONTENT"] != null && !string.IsNullOrEmpty(result["SUPPLY_CONTENT"].ToString()))
                            Message = "省平台催单，内容：" + result["SUPPLY_CONTENT"] == null ? "" : result["SUPPLY_CONTENT"].ToString();
                        else
                            Message = "省平台催单";

                        WebClient web = new WebClient();
                        web.Encoding = Encoding.UTF8;
                        string Dataurl = web.DownloadString(NativeURL   + "Affairs/Reminders" + "?workorderid=" + modelT_Bus_WorkOrder.F_WorkOrderId);
                    }
                    else if (result["SUPPLY_TYPE"].ToString() == "20")
                    {

                        if (result["SUPPLY_CONTENT"] != null && !string.IsNullOrEmpty(result["SUPPLY_CONTENT"].ToString()))
                            Message = "省平台撤单，内容：" + result["SUPPLY_CONTENT"] == null ? "" : result["SUPPLY_CONTENT"].ToString();
                        else
                            Message = "省平台撤单";
                        Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                        if (string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_Result))
                        {
                            // modelT_Bus_WorkOrder.F_Result = Message;
                            keyValuePairs.Add("F_Result", Message);
                        }
                        if (modelT_Bus_WorkOrder.F_DealTime == null)
                            keyValuePairs.Add("F_DealTime", DateTime.Now);
                        keyValuePairs.Add("F_WorkState", 9);
                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;
                        keyValuePairs.Add("F_IsSatisfie", 1);
                        // modelT_Bus_WorkOrder.F_IsSatisfie = 1;
                        keyValuePairs.Add("F_IsClosed", 1);
                        // modelT_Bus_WorkOrder.F_IsClosed = 1;

                        //  modelT_Bus_WorkOrder.F_CloseUser = User.F_UserCode;
                        keyValuePairs.Add("F_CloseTime", DateTime.Now);
                        //  modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;
                        if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_FinalOpinion))
                            keyValuePairs.Add("F_FinalOpinion", Message);
                        workorderBLL.UpdateWorkOrder(modelT_Bus_WorkOrder.F_Id, keyValuePairs);
                    }
                    else
                    {
                        if (result["SUPPLY_CONTENT"] != null && !string.IsNullOrEmpty(result["SUPPLY_CONTENT"].ToString()))
                            Message = "省平台补单，内容：" + result["SUPPLY_CONTENT"].ToString();
                        else
                            Message = "省平台补单";
                        Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                        keyValuePairs.Add("F_ComContent", modelT_Bus_WorkOrder.F_ComContent + " " + Message);
                        //  modelT_Bus_WorkOrder.F_ComContent += " " + Message;
                        workorderBLL.UpdateWorkOrder(modelT_Bus_WorkOrder.F_Id, keyValuePairs);
                    }
                    #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 = Message;
                    oper.F_CreateUser = result["SUPPLY_NAME"] == null ? "" : result["SUPPLY_NAME"].ToString();
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    #endregion 
                    trans.Complete();
                }
                var obj1 = new
                {
                    code = "1",
                    message = "推送成功"
                };
                return Content(obj1.ToJson());

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


        }





        /// <summary>
        /// 督查督办派发
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult receive_jcsupervise_send()
        {
            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 txnBodyCom = paras["paras"].ToString();
            var result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(txnBodyCom);
            if (result["JC_RELATION_SERIALNUM"] == null)
            {
                var obj1 = new
                {
                    code = "0",
                    message = "JC_RELATION_SERIALNUM不能为空"
                };
                return Content(obj1.ToJson());
            }
            if (string.IsNullOrEmpty(result["JC_RELATION_SERIALNUM"].ToString()))
            {
                var obj1 = new
                {
                    code = "0",
                    message = "JC_RELATION_SERIALNUM不能为空"
                };
                return Content(obj1.ToJson());
            }
            var affairs = affairsBll.GetModelList("CASE_SERIAL='" + result["JC_RELATION_SERIALNUM"].ToString() + "'");
            if (affairs != null && affairs.Count > 0)
            {
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(affairs.FirstOrDefault().F_WorkOrderId);
                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
                {
                    Model.T_Bus_Supervision model = new Model.T_Bus_Supervision();
                    model.F_Code = result["JC_SERIALNUM"] == null ? "" : result["JC_SERIALNUM"].ToString();
                    model.F_UserCode = result["JC_NAME"] == null ? "" : result["JC_NAME"].ToString();
                    model.F_SERIALNUM = result["JC_RELATION_SERIALNUM"] == null ? "" : result["JC_RELATION_SERIALNUM"].ToString();
                    model.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    model.F_Title = result["JC_TITLE"] == null ? "" : result["JC_TITLE"].ToString();
                    model.F_Level = result["JC_DEGREE"] == null ? "" : result["JC_DEGREE"].ToString();
                    model.F_State = 0;
                    model.F_Type = 0;
                    model.F_CreateTime = DateTime.Now;
                    if (result["JC_FINISHTIME_BF"] != null && !string.IsNullOrEmpty(result["JC_FINISHTIME_BF"].ToString()))
                        model.F_LimitTime = DateTime.Parse(result["JC_FINISHTIME_BF"].ToString());

                    model.F_Opinion = result["JC_OPINION"] == null ? "" : result["JC_OPINION"].ToString();
                    string des = "";
                    if (!string.IsNullOrWhiteSpace(model.F_Opinion))
                    {
                        des = ",监察意见：" + model.F_Opinion;
                    }
                    model.F_Type = 0;
                    model.F_IsDelete = 0;
                    int n = new BLL.T_Bus_Supervision().Add(model);
                    if (n > 0)
                    {

                        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 = "省平台监察督办派发了工单" + des;
                        oper.F_CreateUser = result["JC_NAME"] == null ? "" : result["JC_NAME"].ToString();
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;
                        operBLL.Add(oper);
                        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());
                    }

                }

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

        } /// <summary>
          /// 督查督办派发
          /// </summary>
          /// <returns></returns>
        //[Authority]
        public ActionResult receive_dcsupervise_send()
        {
            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 txnBodyCom = paras["paras"].ToString();
            var result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(txnBodyCom);
            if (result["DC_RELATION_SERIALNUM"] == null)
            {
                var obj = new
                {
                    code = "0",
                    message = "DC_RELATION_SERIALNUM不能为空"
                };
                return Content(obj.ToJson());
            }
            if (string.IsNullOrEmpty(result["DC_RELATION_SERIALNUM"].ToString()))
            {
                var obj = new
                {
                    code = "0",
                    message = "DC_RELATION_SERIALNUM不能为空"
                };
                return Content(obj.ToJson());
            }
            var affairs = affairsBll.GetModelList("CASE_SERIAL='" + result["DC_RELATION_SERIALNUM"].ToString() + "'");
            if (affairs != null && affairs.Count > 0)
            {
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(affairs.FirstOrDefault().F_WorkOrderId);
                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
                {
                    Model.T_Bus_Supervision model = new Model.T_Bus_Supervision();
                    model.F_Code = result["DC_SERIALNUM"] == null ? "" : result["DC_SERIALNUM"].ToString();
                    model.F_UserCode = result["DC_NAME"] == null ? "" : result["DC_NAME"].ToString();
                    model.F_SERIALNUM = result["DC_RELATION_SERIALNUM"] == null ? "" : result["DC_RELATION_SERIALNUM"].ToString();
                    model.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    model.F_Situation = result["DC_TYPE"] == null ? "" : result["DC_TYPE"].ToString();
                    model.F_Content = result["DC_CONTENT"] == null ? "" : result["DC_CONTENT"].ToString();
                    model.F_Opinion = result["DC_OPINION"] == null ? "" : result["DC_OPINION"].ToString();
                    model.F_State = 0;
                    model.F_Type = 1;
                    model.F_CreateTime = DateTime.Now;
                    if (result["DC_FINISHTIME_BF"] != null && !string.IsNullOrEmpty(result["DC_FINISHTIME_BF"].ToString()))
                        model.F_LimitTime = DateTime.Parse(result["DC_FINISHTIME_BF"].ToString());

                    if (result["DC_ATTATH_ID"] != null && !string.IsNullOrEmpty(result["DC_ATTATH_ID"].ToString()))
                    {
                        model.F_File = receive_info(result["DC_ATTATH_ID"].ToString());
                    }


                    string des = "";
                    if (!string.IsNullOrWhiteSpace(model.F_Opinion))
                    {
                        des = ",督察内容：" + model.F_Opinion;
                    }
                    model.F_Type = 1;
                    model.F_IsDelete = 0;
                    int n = new BLL.T_Bus_Supervision().Add(model);
                    if (n > 0)
                    {

                        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 = "省平台督查督办派发了工单" + des;
                        oper.F_CreateUser = result["DC_NAME"] == null ? "" : result["DC_NAME"].ToString();
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;
                        operBLL.Add(oper);
                        var obj1 = new
                        {
                            code = "1",
                            message = "推送成功"
                        };
                        trans.Complete();
                        return Content(obj1.ToJson());

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

                }

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


        }


        /// <summary>
        ///催单短信
        /// </summary>
        /// <returns></returns>

        public void Reminders(string workorderid)
        {


            List<Model.T_Bus_WorkOrder> workorder = new List<Model.T_Bus_WorkOrder>();

            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
            if (modelT_Bus_AssignedInfo != null)
            {
                if (modelT_Bus_AssignedInfo.F_IsNext == 1 || modelT_Bus_AssignedInfo.F_IsNext == 2)
                {
                    // Model.T_Bus_AssignedInfo_Next modelT_Bus_AssignedInfo_Next = new BLL.T_Bus_AssignedInfo_Next().GetNewModelByWorkOrderID(workorderid);
                    var modelT_Bus_AssignedInfo_Next = new BLL.T_Bus_AssignedInfo_Next().GetModelList("F_State=1 and F_IsDelete=0 and F_IsSure in (0,1) and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'  order by F_CreateTime desc");
                    if (modelT_Bus_AssignedInfo_Next!=null && modelT_Bus_AssignedInfo_Next.Count >0)
                    {
                        var user = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId in(" + string.Join(",", modelT_Bus_AssignedInfo_Next.Select(x => x.F_MainDeptId)) + ") and F_DeleteFlag=0");
                        if (user != null)
                        {
                            foreach (var iv in user)
                            {


                                if (!string.IsNullOrEmpty(iv.F_Mobile))
                                {
                                    string count = "您的工单" + workorderid + "收到催办，请及时处理！";
                                    string c = PushMessageController.PushApp("催单提醒", count, iv.F_UserCode, workorderid);

                                }
                            }
                        }
                    }
                   

                }
                else
                {
                    var user = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId = " + (modelT_Bus_WorkOrder.F_MainDeptId ?? 0) + " and F_DeleteFlag=0");
                    if (user != null)
                    {
                        foreach (var iv in user)
                        {


                            if (!string.IsNullOrEmpty(iv.F_Mobile))
                            {
                                string count = "您的工单" + workorderid + "收到催办，请及时处理！";
                                string c = PushMessageController.PushApp("催单提醒", count, iv.F_UserCode, workorderid);
                            }
                        }
                    }
                }

            }



        }








        public class receive
        {
            public string ATTATH_STEP_ID { set; get; }
        }
        public class receive_material_infos
        {
            public string code { set; get; }
            public string message { set; get; }
            public List<bodys> body { set; get; }
        }
        public class bodys
        {
            public string ATTATH_TYPE { set; get; }
            public string ATTATH_NAME { set; get; }
            public string ATTATH_CONTENT { set; get; }
        }
     
        /// <summary>
        /// 获取附件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private string receive_info(string ids)
        {
            string token = GetToken();
            if (string.IsNullOrEmpty(token))
                return "";
            receive paras = new receive();
            paras.ATTATH_STEP_ID = ids;
            //  values.Add("paras", paras);
            string fileid = "";
             
            //序列化参数
            string jsonParam = "access_token=" + token + "&paras=" + paras.ToJson();
            var responseString = HttpMethods.HttpPost("http://59.227.93.14:9000/share/fjcljk", jsonParam);
            receive_material_infos jo = JsonConvert.DeserializeObject<receive_material_infos>(responseString);
            if (jo.code == "1")
            {
                if (jo.body != null && jo.body.Count > 0)
                {
                    List<Model.T_Sys_Accessories> acs = new List<Model.T_Sys_Accessories>();
                    string path = "/Upload/ZhenWu/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                    foreach (var it in jo.body)
                    {
                       // byte[] data = Encoding.UTF8.GetBytes(it.ATTATH_CONTENT);
                        FileUp fu = new FileUp();
                        fu.ByteSaveFile(it.ATTATH_CONTENT, path, it.ATTATH_NAME);
                        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 = it.ATTATH_NAME;//附件名称
                        model_T_Sys_Accessories.F_FileType = System.IO.Path.GetExtension(it.ATTATH_TYPE);//附件类型
                        model_T_Sys_Accessories.F_FileUrl = path + it.ATTATH_NAME;//附件地址
                                                                                  //model_T_Sys_Accessories.F_Size = file.ContentLength;
                        model_T_Sys_Accessories.F_UserCode = "省12345平台";//上传人  
                        int id = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                        model_T_Sys_Accessories.F_FileId = id;
                        if (string.IsNullOrEmpty(fileid))
                            fileid = id.ToString();
                        else
                            fileid += "," + id.ToString();
                        acs.Add(model_T_Sys_Accessories);
                    }

                }

            }
            else
            {
                string error = "";
                error += " 获取附件失败:" + jo.message;
                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, jo.message, "获取附件失败", error, "");
                object objres = DbHelperSQL.GetSingle(strSql);

            }
            WebClient web = new WebClient();
            web.Encoding = Encoding.UTF8;
            string Dataurl = web.DownloadString(NativeURL  + "Affairs/SetFileData" + "?ids=" + fileid);
            //  string Dataurl = web.DownloadString("http://172.20.0.203:8888/" + "Affairs/SetFileData" + "?ids=" + fileid);
            return fileid;

        }

        private string GetToken()
        {

            //Dictionary<string, object> values = new Dictionary<string, object>();
            //values.Add("client_id", "d620caf2-d00f-41a9-ae99-c6dfd435875e");
            //values.Add("client_secret", "4f75914e-d517-4325-ac64-c321377b12f0");
            //values.Add("grant_type", "client_credentials");
            //var jsonParam = JsonConvert.SerializeObject(values);

            string jsonParam = "client_id=b3e2ed3b-672a-43a0-80db-21f790c0368d&client_secret=362b50d7-2aa5-4874-9363-6c0ba483dfe9&grant_type=client_credentials";
            var responseString = HttpMethods.HttpPost("http://59.227.93.14:8183/rzpt_edc/rest/oauth2/token", jsonParam);
            Token jo = JsonConvert.DeserializeObject<Token>(responseString);
            if (jo.status.code == "1")
            {
                if (!string.IsNullOrEmpty(jo.custom.access_token))
                    return jo.custom.access_token;
                else
                    return "";
            }
            else
                return "";

        }

        private string GetTokenzsk()
        {

            //Dictionary<string, object> values = new Dictionary<string, object>();
            //values.Add("client_id", "d620caf2-d00f-41a9-ae99-c6dfd435875e");
            //values.Add("client_secret", "4f75914e-d517-4325-ac64-c321377b12f0");
            //values.Add("grant_type", "client_credentials");
            //var jsonParam = JsonConvert.SerializeObject(values);

            string jsonParam = "client_id=b3e2ed3b-672a-43a0-80db-21f790c0368d&client_secret=362b50d7-2aa5-4874-9363-6c0ba483dfe9&grant_type=client_credentials";
            var responseString = HttpMethods.HttpPost("http://59.227.93.14:8183/rzpt_edc/rest/oauth2/token", jsonParam);
            Token jo = JsonConvert.DeserializeObject<Token>(responseString);
            if (jo.status.code == "1")
            {
                if (!string.IsNullOrEmpty(jo.custom.access_token))
                    return jo.custom.access_token;
                else
                    return "";
            }
            else
                return "";

        }

        public class Token
        {
            public List<Controls> controls { set; get; }
            public Custom custom { set; get; }
            public Status status { set; get; }
        }
        public class Controls
        {

        }
        public class Custom
        {
            public string access_token { set; get; }
            public string refresh_token { set; get; }
            public string jsessionid { set; get; }
            public string expires_in { set; get; }
        }


        public class Tokenbody
        {
            public string access_token { set; get; }
            public string refresh_token { set; get; }
            public string token_type { set; get; }
            public int expires_in { set; get; }
        }
        public class Status
        {
            public string code { set; get; }
        }

        /// <summary>
        /// 服务工单推送处理结果接口
        /// </summary>
        /// <returns></returns>
        //  [Authority]
        public ActionResult push_case_finish()
        {

            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 txnBodyCom = paras["paras"].ToString();
            var result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(txnBodyCom);
            if (result["CASE_SERIAL"] == null)
            {
                var obj = new
                {
                    code = "0",
                    message = "CASE_SERIAL不能为空"
                };
                return Content(obj.ToJson());
            }
            if (string.IsNullOrEmpty(result["CASE_SERIAL"].ToString()))
            {
                var obj = new
                {
                    code = "0",
                    message = "CASE_SERIAL不能为空"
                };
                return Content(obj.ToJson());
            }

            var workoder = DbHelperSQL.GetSingle(" select top 1 F_OldWorkOrder from T_Bus_Mapping  where F_NewWorkOrder='" + result["CASE_SERIAL"].ToString() + "'and F_Type=1  order by F_CreateTime desc ");
            string workoderid = result["CASE_SERIAL"].ToString();
            if (workoder != null)
            {
                workoderid = workoder.ToString()
;
            }

            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workoderid);
            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workoderid);
            Model.T_Bus_Feedback modelT_Bus_Feedback = new Model.T_Bus_Feedback();
            if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null)
            {
                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
                {
                    #region 插入反馈记录
                    Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                    modelT_Bus_Feedback.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单编号
                    modelT_Bus_Feedback.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;//交办id

                    modelT_Bus_Feedback.F_AuditUser = "";
                    modelT_Bus_Feedback.F_DealUser = result["FINISH_NAME"] == null ? "" : result["FINISH_NAME"].ToString();
                    modelT_Bus_Feedback.F_Result = result["FINISH_OUNAME"] == null ? "" : result["FINISH_OUNAME"].ToString() + "于时间（" + DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分ss秒") + "）回复：" + result["FINISH_RESULT"] == null ? "" : result["FINISH_RESULT"].ToString();
                    #region 20200114新增字段 zhengbingbing

                    modelT_Bus_Feedback.F_ProSituation = "";//处理情况/方案/进程
                    modelT_Bus_Feedback.F_IsProtect = modelT_Bus_WorkOrder.F_IsProtect;
                    modelT_Bus_Feedback.F_DealUserContact = "";//承办人联系方式
                    DateTime contime = DateTime.Now;
                    modelT_Bus_Feedback.F_IsProResult = 1;
                    #endregion
                    if (result["FINISH_ATTATH_ID"] != null && !string.IsNullOrEmpty(result["FINISH_ATTATH_ID"].ToString()))
                        keyValuePairs.Add("F_File", receive_info(result["FINISH_ATTATH_ID"].ToString()));


                    modelT_Bus_Feedback.F_IsAudit = 0;
                    modelT_Bus_Feedback.F_IsDelete = 0;
                    modelT_Bus_Feedback.F_CreateUser = result["FINISH_NAME"] == null ? "" : result["FINISH_NAME"].ToString();
                    modelT_Bus_Feedback.F_CreateTime = DateTime.Now;//办理时间
                    modelT_Bus_Feedback.F_CreateDeptId = 633;//办理部门
                    modelT_Bus_Feedback.F_IsFeedEnd = 1;
                    modelT_Bus_Feedback.F_State = 1;
                    new BLL.T_Bus_Feedback().Add(modelT_Bus_Feedback);
                    #endregion
                    if (modelT_Bus_Feedback != null && modelT_Bus_Feedback.F_State == 1)
                    {
                        string typemsg = "办理";
                        #region 保存工单信息
                        keyValuePairs.Add("F_WorkState", 6);
                        //  modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.dealed;//待回访
                        keyValuePairs.Add("F_Result", modelT_Bus_Feedback.F_Result);
                        //  modelT_Bus_WorkOrder.F_Result = modelT_Bus_Feedback.F_Result;
                        keyValuePairs.Add("F_DealDeptId", 633);
                        modelT_Bus_WorkOrder.F_DealDeptId = 633;
                        keyValuePairs.Add("F_DealUser", result["FINISH_NAME"] == null ? "" : result["FINISH_NAME"].ToString());
                        // modelT_Bus_WorkOrder.F_DealUser = result["FINISH_NAME"] == null ? "" : result["FINISH_NAME"].ToString();
                        keyValuePairs.Add("F_DealTime", DateTime.Now);
                        //  modelT_Bus_WorkOrder.F_DealTime = DateTime.Now;

                        keyValuePairs.Add("F_IsOverdue", 0);
                        // modelT_Bus_WorkOrder.F_IsOverdue = 0;

                        workorderBLL.UpdateWorkOrder(modelT_Bus_WorkOrder.F_Id, keyValuePairs);
                        #endregion
                        #region 保存交办信息
                        modelT_Bus_AssignedInfo.F_FeedbackTime = DateTime.Now;
                        modelT_Bus_AssignedInfo.F_IsOverdue = 0;
                        assignBLL.Update(modelT_Bus_AssignedInfo);
                        #endregion

                        typemsg = "主办";
                        #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 = result["FINISH_NAME"] == null ? "" : result["FINISH_NAME"].ToString();
                        oper.F_Message = userinfo + " " + typemsg + "了工单";
                        oper.F_CreateUser = userinfo;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;
                        operBLL.Add(oper);
                        //推送消息表
                       
                        #endregion
                    }

                    trans.Complete();
                }
                var obj = new
                {
                    code = "1",
                    message = "反馈成功！"
                };

                return Content(obj.ToJson());

            }
            else
            {
                var obj = new
                {
                    code = "0",
                    message = "工单不存在！"
                };
                return Content(obj.ToJson());
            }
        }


        /// <summary>
        /// HMACSHA1算法加密
        /// </summary>
        private static string Hmacsha256Encrypt(string encryptText, string encryptKey)
        {
            var encoding = new System.Text.UTF8Encoding();
            var shaKeyBytes = encoding.GetBytes(encryptKey);
            StringBuilder builder = new StringBuilder();

            using (var shaAlgorithm = new System.Security.Cryptography.HMACSHA256(shaKeyBytes))
            {
                var signatureBytes = System.Text.Encoding.UTF8.GetBytes(encryptText);
                var signatureHashBytes = shaAlgorithm.ComputeHash(signatureBytes);
                return System.Convert.ToBase64String(signatureHashBytes);
            }
        }

        /// <summary>
        /// 用种子获取密钥
        /// </summary>
        /// <param name="Seed">种子</param>
        /// <param name="KeyLen">密钥长度（默认为16）</param>
        /// <returns>密钥Key</returns>
        public static byte[] GetKeyBySeed(string Seed, int KeyLen = 16)
        {
            byte[] bySeed = Encoding.UTF8.GetBytes(Seed);
            byte[] byKeyArray = null;
            using (var st = new SHA1CryptoServiceProvider())
            {
                using (var nd = new SHA1CryptoServiceProvider())
                {
                    var rd = nd.ComputeHash(st.ComputeHash(bySeed));
                    byKeyArray = rd.Take(KeyLen).ToArray();
                }
            }
            return byKeyArray;
        }

        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="Bytes">明文（byte[]）</param>
        /// <param name="Key">密钥（byte[]）</param>
        /// <param name="Vector">向量</param>
        /// <returns>密文（byte[]）</returns>
        public static byte[] Encrypt(byte[] Bytes, byte[] Key, string Vector)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            aes.Key = Key;
            aes.IV = Encoding.UTF8.GetBytes(Vector);

            ICryptoTransform cTransform = aes.CreateEncryptor();
            return cTransform.TransformFinalBlock(Bytes, 0, Bytes.Length);
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="Bytes">密文（byte[]）</param>
        /// <param name="Key">密钥（byte[]）</param>
        /// <param name="Vector">向量</param>
        /// <returns>明文（byte[]）</returns>
        public static byte[] Decrypt(byte[] Bytes, byte[] Key, string Vector)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            aes.Key = Key;
            aes.IV = Encoding.UTF8.GetBytes(Vector);

            ICryptoTransform cTransform = aes.CreateDecryptor();
            return cTransform.TransformFinalBlock(Bytes, 0, Bytes.Length);
        }


        /// <summary>
        /// 附件材料接口
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult receive_material_info()
        {
            StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
           
            var postString = reader.ReadToEnd();
            JObject paras = null;
            paras = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(postString);

            LogFactory.GetLogger("receive_material_info").Warn (paras);
            var txnBodyCom = paras["paras"].ToString();
            var result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(txnBodyCom);
            LogFactory.GetLogger("receive_material_info").Warn(result);
            var body = GetFileData(result["ATTATH_STEP_ID"].ToString());
            if (body != null)
            {
                var obj = new
                {
                    code = "1",
                    message = "获取附件成功！",
                    body = body
                };

                return Content(obj.ToJson());

            }
            else
            {
                var obj = new
                {
                    code = "0",
                    message = "获取附件失败！该附件不存在",
                    body = ""
                };

                return Content(obj.ToJson());

            }

        }
        /// <summary>
        /// 获取附件数据
        /// </summary>
        /// <param name="ids">附件id，多个用英文逗号,隔开</param>
        /// <param name="prefix">前缀</param>
        /// <returns></returns>
        public List<bodys> GetFileData(string ids)
        {


            DataTable dt = DbHelperSQL.Query("select * from T_Sys_Accessories WITH(NOLOCK) where F_FileId in (" + ids + ")").Tables[0];
            List<bodys> bodys = new List<bodys>();
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["F_UserCode"].ToString() != "知识附件")
                {
                    string url = Upload(FrontUrl + dr["F_FileUrl"].ToString(), dr["F_FileName"].ToString(), "/" + dr["F_FileUrl"].ToString().Replace(dr["F_FileName"].ToString(), ""));
                    if (url != "1")
                        return null;
                }


                bodys body = new bodys();
                body.ATTATH_TYPE = dr["F_FileType"].ToString();
                body.ATTATH_NAME = dr["F_FileName"].ToString();
                FileStream fs = new FileStream(System.Web.HttpContext.Current.Server.MapPath("..") + dr["F_FileUrl"].ToString(), FileMode.Open);
                byte[] filebyte = new byte[fs.Length];
                fs.Read(filebyte, 0, filebyte.Length);
                fs.Close();
                body.ATTATH_CONTENT = Convert.ToBase64String(filebyte);
                bodys.Add(body);
            }

            return bodys;
        }
        public string 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)
            {
                return e.Message;
            }
        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
        /// <summary>
        /// 知识审核退回接口
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult transmit_kinfo_back()
        {
            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 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());
            }


            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>
        /// <returns></returns>
        //[Authority]
        public ActionResult transmit_kinfo_quiz()
        {
            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 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());
            }



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

            }

        }

    }
}