using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.App_Start;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Controllers.Sms;
using CallCenterApi.Interface.Controllers.workorder;
using CallCenterApi.Interface.Models.Common;
using CallCenterApi.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    public class APPController : BaseController
    {
        // GET: APP


        
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Login(string usercode, string password)
        {
            DateTime ExpiredTime = DateTime.Now.AddDays(1);
            bool appResult = DateTime.Now < ExpiredTime;// Convert.ToDateTime(ReadFile(HttpRuntime.AppDomainAppPath + "tools\\hykj.hy"));
            if (appResult)
            {
                DataTable dt = new DataTable();
                try
                {
                    Dictionary<string, string> paras = new Dictionary<string, string>();
                    string sql = " select * from T_Sys_Users where F_OpenId=@F_OpenId and F_Password=@F_Password";
                    paras.Add("@F_OpenId", usercode);
                    paras.Add("@F_Password", password);

                    dt = DbHelperSQL.Query(sql, paras).Tables[0];
                    if (dt != null)
                    {
                        //写入登录日志
                        new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                        {
                            F_LoginName = dt.Rows[0]["F_OpenId"].ToString(),
                            F_LoginId = Convert.ToInt32(dt.Rows[0]["F_Id"].ToString()),
                            F_Result = "APP市民登录成功",
                            F_LoginIP = Common.DTRequest.GetIP(),
                            F_Hostname = Common.DTRequest.GetIP(),
                            F_LoginDate = DateTime.Now,
                            F_Remark = "",
                            F_State = 0
                        });

                        return Success("登录成功", new
                        {
                            usercode = dt.Rows[0]["F_OpenId"].ToString(),
                            userid = dt.Rows[0]["F_Id"].ToString()
                        });
                    }
                    else
                    {
                        //写入登录日志
                        DataTable dt1 = new CallCenterApi.BLL.T_Sys_Users().GetList("F_OpenId='" + usercode + "'").Tables[0];
                        if (dt1.Rows.Count > 0)
                        {
                            int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = dt1.Rows[0]["F_OpenId"].ToString(),
                                F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_Id"].ToString()),
                                F_Result = "APP市民登录失败：帐号-" + usercode,
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                        }
                        else
                        {
                            int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                            {
                                F_LoginName = usercode,
                                F_LoginId = -1,
                                F_Result = "APP市民登录失败：帐号-" + usercode,
                                F_LoginIP = Common.DTRequest.GetIP(),
                                F_Hostname = Common.DTRequest.GetIP(),
                                F_LoginDate = DateTime.Now,
                                F_Remark = "",
                                F_State = 0
                            });
                        }

                        return Error("账号或密码错误，请重新登录");
                    }
                }
                catch
                {
                    return Error("账号或密码错误，请重新登录");
                }
            }
            else
            {
                return Error("授权过期，请联系系统厂家。");
            }
        }

        [HttpPost]
        public ActionResult loginNologin()
        {
          
            string loginNo = RequestString.GetFormString("loginNo");//登录账号
            string loginPassword = RequestString.GetFormString("loginPassword");//登录密码
            int type = RequestString.GetInt("type", 0); ;//0自然人注册1法人注册
            DataTable dt = new DataTable();
            try
            {
                Dictionary<string, string> paras = new Dictionary<string, string>();
                string sql = "";
                sql = " select * from T_Sys_Users where F_OpenId=@F_OpenId and F_Password=@F_Password";
                paras.Add("@F_OpenId", loginNo);
                paras.Add("@F_Password", loginPassword);//login.Password

                dt = DbHelperSQL.Query(sql, paras).Tables[0];
                if (dt != null)

                {
                    if (dt.Rows.Count > 0)
                    {
                        string Smsurl = "https://zwfw.anyang.gov.cn/gsp/uc10002";
                        string  acctType = "10";
                        if (type == 1)
                        {
                             acctType = "20";
                            Smsurl = "https://zwfw.anyang.gov.cn/gsp/uc20002";
                        }

                        var dic = new SortedDictionary<string, string>
               {
                {"loginNo", loginNo},
                {"loginPassword", loginPassword},
                {"loginType", "AU01"},
                {"acctType", acctType},
                };
                        //序列化参数
                        var jsonParam = JsonConvert.SerializeObject(dic);
                        var responseString = HttpMethods.HttpPost(Smsurl, jsonParam, "application/json;charset=UTF-8");
                        JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);



                        Dictionary<string, string> Dic = new Dictionary<string, string>();
                        Dic.Add("F_OpenId", dt.Rows[0]["F_OpenId"].ToString());
                        Dic.Add("F_Name", dt.Rows[0]["F_Name"].ToString());
                        Dic.Add("F_Telphone", dt.Rows[0]["F_Telphone"].ToString());

                        new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                        {
                            F_LoginName = dt.Rows[0]["F_OpenId"].ToString(),
                            F_LoginId = Convert.ToInt32(dt.Rows[0]["F_OpenId"].ToString()),
                            F_Result = "登录成功",
                            F_LoginIP = Common.DTRequest.GetIP(),
                            F_Hostname = Common.DTRequest.GetIP(),
                            F_LoginDate = DateTime.Now,
                            F_Remark = "",
                            F_State = 0
                        });
                        var token = FormsPrincipal<Dictionary<string, string>>.GetCookieValue(Dic["F_OpenId"], Dic);
                        return Success("登录成功", new
                        {
                            token = token
                        });

                    }
                    else
                    {
                        return Error("账号或密码错误，请重新登录");
                    }


                }
                else
                {
                    return Error("账号或密码错误，请重新登录");
                }
            }
            catch (Exception ex)
            {
                return Error("错误:" + ex.Message);
            }
            finally
            {
                dt.Clear();
                dt.Dispose();
            }
           
        }
        private BLL.T_Bus_WorkOrder workorderBLL = new BLL.T_Bus_WorkOrder();
        private BLL.T_Bus_Operation operBLL = new BLL.T_Bus_Operation();



        /// <summary>
        /// 登录用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //  [HttpPost]
        public ActionResult APPSlogin(string loginNo, string loginPassword, string userMobile, string validateCode)
        {
          
               
                string mobileKey = "";
                JObject jObject = GetMobileKey(userMobile, validateCode);
                if (jObject["C-API-Status"].ToString() == "00")
                {
                    var Body = jObject["C-Response-Body"].ToString();
                    var txnBodyComresult = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(Body);
                    mobileKey = txnBodyComresult["mobileKey"] == null ? "" : txnBodyComresult["mobileKey"].ToString();
                  
                }
                else
                {
                    return Error(jObject["C-Response-Desc"].ToString());
                }
                if (mobileKey == "")
                    return Error("mobileKey获取失败");
                



                string url = appurl + "/gsp/uc11002";
                var txnBodyCom = new SortedDictionary<string, string>
               {
                {"userMobile", userMobile},
                {"loginNo",loginNo},
                 {"acctType", "10"},
                  {"loginType", "AU09"},
                  {"loginPassword", loginPassword},
                 {"mobileKey", mobileKey}
                };
                var txnCommCom = new SortedDictionary<string, string>
               {
                {"tRecInPage", "10"},
                {"txnIttChnlCgyCode", "D001C004"},
                 {"tStsTraceId", "110567980"},
                 {"tPageJump", "1"},
                 {"txnIttChnlId", "99990001000000000000000"},
                };
                var sms = new Dictionary<string, string>
                {
                     {"txnBodyCom", txnBodyCom.ToJson ()},
                {"txnCommCom", txnCommCom.ToJson ()}
                };
                //序列化参数
                var param = new
                {
                    txnBodyCom = txnBodyCom,
                    txnCommCom = txnCommCom
                };

                var jsonParam = JsonConvert.SerializeObject(param);
                var responseString = HttpMethods.HttpPost(url, jsonParam, "application/json");
                JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
         
                if (jo["C-API-Status"].ToString() == "00")
                { //写入登录日志
                Model.T_Sys_Users dModel = new Model.T_Sys_Users();
                var list = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + loginNo + "' ");
                if (list.Count > 0)
                {
                    dModel = list.First();
                }
                else
                {
                    dModel.F_OpenId = loginNo;
                    dModel.F_Password = loginPassword;
                    dModel.F_Name = loginNo;
                    dModel.F_Telphone = userMobile;
                    dModel.F_Type = (int)EnumUserType.app;//4;
                    dModel.F_CreateTime = DateTime.Now;
                    long n = new BLL.T_Sys_Users().Add(dModel);
                    dModel.F_Id = n;
                }
                new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                {
                    F_LoginName = dModel.F_OpenId .ToString(),
                    F_LoginId = (int )dModel.F_Id,
                    F_Result = "市民登录成功",
                    F_LoginIP = Common.DTRequest.GetIP(),
                    F_Hostname = Common.DTRequest.GetIP(),
                    F_LoginDate = DateTime.Now,
                    F_Remark = "",
                    F_State = 0
                });

                return Success("登录成功", new
                {
                    usercode = dModel.F_OpenId.ToString(),
                    userid = dModel.F_Id.ToString ()
                });

            }
            else
                {
              
                     DataTable dt1 = new CallCenterApi.BLL.T_Sys_Users().GetList("F_OpenId='" + loginNo + "'").Tables[0];
                    if (dt1.Rows.Count > 0)
                    {
                        int rr = new CallCenterApi.BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                        {
                            F_LoginName = dt1.Rows[0]["F_OpenId"].ToString(),
                            F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_Id"].ToString()),
                            F_Result = "市民登录失败：帐号-" + loginNo,
                            F_LoginIP = Common.DTRequest.GetIP(),
                            F_Hostname = Common.DTRequest.GetIP(),
                            F_LoginDate = DateTime.Now,
                            F_Remark = "",
                            F_State = 0
                        });
                    }
                    else
                    {
                        int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                        {
                            F_LoginName = loginNo,
                            F_LoginId = -1,
                            F_Result = "市民登录失败：帐号-" + loginNo,
                            F_LoginIP = Common.DTRequest.GetIP(),
                            F_Hostname = Common.DTRequest.GetIP(),
                            F_LoginDate = DateTime.Now,
                            F_Remark = "",
                            F_State = 0
                        });
                    }
                    return Error(jObject["C-Response-Desc"].ToString());
                }



            
        }
        public ActionResult SendCode(string mobile,string workorderid)
        {
            if (string.IsNullOrEmpty(workorderid))
                return Error("请选择工单");
            var model = new BLL.T_Bus_WorkOrder().GetModel(workorderid);
            if (model == null)
                return Error("工单不存在");
            if (!string.IsNullOrEmpty(model .F_CusPhone ))
            {
                if (model.F_CusPhone.Trim().Length > 11)
                    model.F_CusPhone = model.F_CusPhone.Substring(1, 11);
            }
            if (string.IsNullOrEmpty(mobile))
            {
                return Error("请输入将要发送的号码");
            }
            if (model.F_CusPhone != mobile)
                return Error("手机号错误");
            int codes = new Random().Next(1000, 9999);
            // string msg = codes.ToString ();
            // bool n = SMSController.AddSmS(0, msg, "你的验证码是"+ codes+".十分钟有效.", mobile, "168411", "");

            string mag = "[\"" + codes.ToString() + "\"]";
            string v = SmsNewController.AddSmS(0, "你的验证码是" + codes + ".十分钟有效.", mobile, "681240638956277760", mag,
          "");
            if (v == "")
            {
                return Success("发送成功");
            }
            else
                return Error("发送失败");

        }
        public ActionResult Verification (string phone ,string code)
        {
            if (string.IsNullOrEmpty(phone))
                return Error("请输入手机号码");
            string msgcount = "你的验证码是" + code + ".十分钟有效.";
            if (string.IsNullOrEmpty(code))
                return Error("请输入验证码");
            var sms = new BLL.T_SMS_RecvSMS().GetModelList("Content='" + msgcount + "' and CallerNum='" + phone + "'order by RecvTime desc");
            if (sms != null && sms.Count > 0)
            {
                var modelSms = sms.First();
                if ((DateTime.Now - modelSms.RecvTime).Minutes > 10)
                {
                    return Error("验证码已失效");
                }
                else
                    return Success("验证成功");
            }
            else
                return Error("请输入正确验证码");
              
        }
        /// <summary>
        /// 添加工单信息
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult AddWorkOrder()
        {
                string loginNo = RequestString.GetFormString("loginNo");
                int source = RequestString.GetInt("source", 0);
                string cusname = RequestString.GetFormString("cusname");
                string cussex = RequestString.GetFormString("cussex");
                string cusphone = RequestString.GetFormString("cusphone");
                string cusaddress = RequestString.GetFormString("cusaddress");
              
                
                string conname = RequestString.GetFormString("conname");
                string conphone = RequestString.GetFormString("conphone");
                string title = RequestString.GetFormString("title");
                string content = RequestString.GetFormString("content");
                string files = RequestString.GetFormString("files");
                int sourcearea = RequestString.GetInt("sourcearea", 0);
                string sourceaddress = RequestString.GetFormString("sourceaddress");
            string code = RequestString.GetFormString("code");
            string keys = RequestString.GetFormString("keys");
                string splituser = RequestString.GetFormString("splituser");
                int type = RequestString.GetInt("type", 0);
               
                int isprotect = RequestString.GetInt("isprotect", 0);
                int level = RequestString.GetInt("level", 0);
                int business = RequestString.GetInt("business", 0); ;//
                int township = RequestString.GetInt("township", 0);
                int village = RequestString.GetInt("village", 0);
            if (string.IsNullOrEmpty(cusphone))
                return Error("请输入手机号码");
            string msgcount = "您的验证码是" + code + "，10分钟内有效。";
            if (string.IsNullOrEmpty(code))
                return Error("请输入验证码");
            var sms = new BLL.T_SMS_RecvSMS().GetModelList("Content='" + msgcount + "' and CallerNum='" + cusphone + "'order by RecvTime desc");
            if (sms != null && sms.Count > 0)
            {
                var modelSms = sms.First();
                if ((DateTime.Now - modelSms.RecvTime).Minutes > 10)
                {
                    return Error("验证码已失效");
                }
            }
            else
                return Error("请输入正确验证码");
            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";
                    modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID(source, sourcearea, creattime, endtime);
                    modelT_Bus_WorkOrder.F_InfoSource = source;//信息来源
                    modelT_Bus_WorkOrder.F_InfoType = type;//信息类别
                   
                    modelT_Bus_WorkOrder.F_SourceArea = sourcearea;//反映地域
                    modelT_Bus_WorkOrder.F_SourceAddress = sourceaddress;//事发地址
                    modelT_Bus_WorkOrder.F_CusName = cusname;//投诉人姓名
                    modelT_Bus_WorkOrder.F_CusSex = cussex;//性别
                    modelT_Bus_WorkOrder.F_CusPhone = cusphone;//来电号码
                    modelT_Bus_WorkOrder.F_CusAddress = cusaddress;//地址
                  
                    modelT_Bus_WorkOrder.F_ConName = conname;//联系人姓名
                    modelT_Bus_WorkOrder.F_ConPhone = conphone;//联系人电话
                    
                    modelT_Bus_WorkOrder.F_ComTitle = title;//标题
                    modelT_Bus_WorkOrder.F_ComContent = content;//情况摘要（投诉内容）
                    modelT_Bus_WorkOrder.F_File = files;//附件
                    modelT_Bus_WorkOrder.F_IsProtect = isprotect;//保密方式0否1是
                    modelT_Bus_WorkOrder.F_Key = keys;
                    modelT_Bus_WorkOrder.F_SplitUser = splituser;
                    modelT_Bus_WorkOrder.F_Level = level;
                    modelT_Bus_WorkOrder.F_Township = township;
                    modelT_Bus_WorkOrder.F_Village = village;
                    Task.Run(() =>
                    {
                        saveCus(cusname, cusphone, cusaddress);
                    });
                    modelT_Bus_WorkOrder.F_Latitude = 0;//纬度
                    modelT_Bus_WorkOrder.F_Longitude = 0;//经度
                    modelT_Bus_WorkOrder.F_IsResult = 0;
                   

                    modelT_Bus_WorkOrder.F_CreateUser = loginNo;//登记人工号
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;//登记时间
                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.neworder;// 0;//工单状态0登记中
                    modelT_Bus_WorkOrder.F_IsClosed = 0;//工单是否关闭
                    modelT_Bus_WorkOrder.F_IsOverdue = 0;//是否逾期(0:否，1：是)
                    modelT_Bus_WorkOrder.F_IsDelete = 0;//是否删除(0:否，1：是)
                    modelT_Bus_WorkOrder.F_ToBereply = 0;
                   
                    //如果选择即刻答复：是，即为直办，工单结束
                    
                    #region
                    #endregion
                

                    modelT_Bus_WorkOrder.F_Id = workorderBLL.Add(modelT_Bus_WorkOrder);

                    #endregion

                    trans.Complete();
                }
                if (modelT_Bus_WorkOrder.F_Id <= 0)
                    return Error("添加失败");
                else
                {
                    string userinfo = User.depname + "(" + User.F_UserCode + ")";
                    string message = "";
                message = userinfo + " 登记了工单，工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                
                    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 = loginNo;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;
                        operBLL.Add(oper);
                        string count = "您反映的事项已受理并转交相关部门处理，感谢您拨打市长热线！";
                        //  string msg = "";
                        //   bool n = SMSController.AddSmS(0, msg, count, modelT_Bus_WorkOrder.F_CusPhone, "197387", "", modelT_Bus_WorkOrder.F_WorkOrderId);
                        string phone = modelT_Bus_WorkOrder.F_CusPhone;
                        if (phone.Length > 11)
                            phone = phone.Substring(1, 11);
                           string n = SmsNewController.AddSmS(0, count, phone, "681240256766803968", "", modelT_Bus_WorkOrder.F_WorkOrderId);
                        #endregion
                    }).ContinueWith(p => {
                        System.Diagnostics.Debug.WriteLine(DateTime.Now);
                    });
                    Task.Run(() =>
                    {
                        #region 插入推送消息

                        //推送消息表
                        if (modelT_Bus_WorkOrder.F_WorkState != (int)EnumWorkState.neworder && modelT_Bus_WorkOrder.F_WorkState != (int)EnumWorkState.audit)
                        {

                            var role = new BLL.T_Sys_RoleInfo().GetModelList(" (F_RoleCode='ZXLD' or F_RoleCode='ZXLDGLYGLY' or F_RoleCode='MTDD')  ").Select(p => p.F_RoleId);
                            var users = userBLL.GetModelList(" F_RoleId in (" + string.Join(",", role) + ")  ");

                          
                        }
                        #endregion
                    }).ContinueWith(p => {
                        System.Diagnostics.Debug.WriteLine(DateTime.Now);
                    });
                   
                    Task.Run(() =>
                    {
                        case_info(modelT_Bus_WorkOrder.F_WorkOrderId, "case_info");
                    }).ContinueWith(p => {
                        System.Diagnostics.Debug.WriteLine(DateTime.Now);
                    });
                    if (!string.IsNullOrEmpty(files))
                    {
                        Task.Run(() =>
                        {
                            material_info(modelT_Bus_WorkOrder.F_WorkOrderId, files, modelT_Bus_WorkOrder.F_SourceArea.ToString(), modelT_Bus_WorkOrder.F_Id, "10");
                        }).ContinueWith(p => {
                            System.Diagnostics.Debug.WriteLine(DateTime.Now);
                        });
                    }
                   
                }
                return Success("操作成功");

        }


        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
      //  [HttpPost]
        public ActionResult AddUser(string loginNo,string loginPassword,string userMobile,string validateCode)
        {
           
            Model.T_Sys_Users dModel = new Model.T_Sys_Users();
            var list = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + loginNo + "' ");
            if (list.Count > 0)
            {
                return Error("已经存在此账号");
            }
            else
            {
                string isFirstLogin = "";
                string mobileKey = "";
                JObject jObject = GetMobileKey(userMobile, validateCode);
                if (jObject["C-API-Status"].ToString() == "00")
                {
                    var Body = jObject["C-Response-Body"].ToString ();
                    var txnBodyComresult = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(Body);
                    mobileKey = txnBodyComresult["mobileKey"] == null ? "" : txnBodyComresult["mobileKey"].ToString();
                    isFirstLogin = txnBodyComresult["isFirstLogin"] == null ? "" : txnBodyComresult["isFirstLogin"].ToString();
                }
                else
                {
                    return Error(jObject["C-Response-Desc"].ToString());
                }
               if (mobileKey=="")
                    return Error("mobileKey获取失败");
                if (isFirstLogin == ""|| isFirstLogin=="0")
                    return Error("该手机号码已注册");


             
                string url = appurl + "/gsp/uc10041";
                var txnBodyCom = new SortedDictionary<string, string>
               {
                {"userMobile", userMobile},//用户手机号
                {"loginNo",loginNo},//33 自然人注册&登录  
                 {"loginPassword", loginPassword},
                 {"mobileKey", mobileKey}
                };
                var txnCommCom = new SortedDictionary<string, string>
               {
                {"tRecInPage", "10"},
                {"txnIttChnlCgyCode", "D001C004"},
                 {"tStsTraceId", "110567980"},
                 {"tPageJump", "1"},
                 {"txnIttChnlId", "99990001000000000000000"},
                };
                var sms = new Dictionary<string, string>
                {
                     {"txnBodyCom", txnBodyCom.ToJson ()},
                {"txnCommCom", txnCommCom.ToJson ()}
                };
                //序列化参数
                var param = new
                {
                    txnBodyCom = txnBodyCom,
                    txnCommCom = txnCommCom
                };
                
                var jsonParam = JsonConvert.SerializeObject(param);
                var responseString = HttpMethods.HttpPost(url , jsonParam, "application/json");
                JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
                if (jo["C-API-Status"].ToString() == "00")
                {
                    dModel.F_OpenId = loginNo;
                    dModel.F_Password = loginPassword;
                    dModel.F_Name = loginNo;
                    dModel.F_Telphone = userMobile;
                    dModel.F_Type = (int)EnumUserType.app;//4;
                    dModel.F_CreateTime = DateTime.Now;
                    long n = new BLL.T_Sys_Users().Add(dModel);
                    if (n > 0)
                        return Success("添加成功");
                    else
                        return Error("添加失败");
                }
                else
                {
                    return Error(jObject["C-Response-Desc"].ToString());
                }
                
            }
        }
        private string appurl = Configs.GetValue("AppUrl");

        public JObject GetMobileKey(string userMobile,string validateCode)
        {
            string Smsurl = appurl + "/gsp/uc00006";
            var txnBodyCom = new SortedDictionary<string, string>
               {
                {"userMobile", userMobile},//用户手机号
                {"validateCodeType", "33"},//33 自然人注册&登录  
                 {"validateCode", validateCode}
                };
            var txnCommCom = new SortedDictionary<string, string>
               {
                {"tRecInPage", "10"},
                {"txnIttChnlCgyCode", "D001C004"},
                 {"tStsTraceId", "110567980"},
                 {"tPageJump", "1"},
                 {"txnIttChnlId", "99990001000000000000000"},
                };
            var sms = new Dictionary<string, string>
                {
                     {"txnBodyCom", txnBodyCom.ToJson ()},
                {"txnCommCom", txnCommCom.ToJson ()}
                };
            //序列化参数
            var param = new
            {
                txnBodyCom = txnBodyCom,
                txnCommCom = txnCommCom
            };

            var jsonParam = JsonConvert.SerializeObject(param);
            var responseString = HttpMethods.HttpPost(Smsurl, jsonParam, "application/json");
            JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
            return jo;

        }
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult SendSms(string userMobile,string vcodeId,string vcode)
        {
        
                string Smsurl = appurl+ "/gsp/uc00001";
                var txnBodyCom = new SortedDictionary<string, string  >
               {
                {"userMobile", userMobile},//用户手机号
                {"validateCodeType", "33"},
                 {"vcodeId", vcodeId},
                 {"vcode", vcode}
                };
            var txnCommCom = new SortedDictionary<string, string>
               {
                {"tRecInPage", "10"},
                {"txnIttChnlCgyCode", "D001C004"},
                 {"tStsTraceId", "110567980"},
                 {"tPageJump", "1"},
                 {"txnIttChnlId", "99990001000000000000000"},
                };
            var sms = new Dictionary<string, string   >
                {
                     {"txnBodyCom", txnBodyCom.ToJson ()},
                {"txnCommCom", txnCommCom.ToJson ()}
                };
            //序列化参数
            var param = new {
                txnBodyCom= txnBodyCom,
                txnCommCom= txnCommCom
               } ;

                 var jsonParam = JsonConvert.SerializeObject(param);
            var responseString = HttpMethods.HttpPost(Smsurl, jsonParam, "application/json");
                JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
         
            if (jo["C-API-Status"].ToString() == "00")
                return Success("发送成功", jo["C-Response-Desc"].ToString ());
            else
                return Error(jo["C-Response-Desc"].ToString());

        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [APPActionFilter]
        [HttpPost]
        public ActionResult UpdateUser()
        {
            int id = RequestString.GetInt("id", 0);
            string usercode = RequestString.GetFormString("usercode");
            string password = RequestString.GetFormString("password");
            string name = RequestString.GetFormString("name");
            string phone = RequestString.GetFormString("phone");
            int sex = RequestString.GetInt("sex", 0);
            string province = RequestString.GetFormString("province");
            string city = RequestString.GetFormString("city");
            string county = RequestString.GetFormString("county");
            string address = RequestString.GetFormString("address");

            Model.T_Sys_Users dModel = new Model.T_Sys_Users();
            if (id == 0)
            {
                dModel = new BLL.T_Sys_Users().GetModel(id);
                if (dModel != null)
                {
                    var list = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + usercode + "' and F_Id!='" + id + "' ");
                    if (list.Count > 0)
                    {
                        return Error("已经存在此账号");
                    }
                    else
                    {
                        dModel.F_OpenId = usercode;
                        dModel.F_Name = name;
                        dModel.F_Telphone = phone;
                        dModel.F_Sex = sex;
                        dModel.F_Province = province;
                        dModel.F_City = city;
                        dModel.F_County = county;
                        dModel.F_Address = address;

                        if (new BLL.T_Sys_Users().Update(dModel))
                            return Success("修改成功");
                        else
                            return Error("修改失败");
                    }
                }
                else
                {
                    return Error("修改失败");
                }
            }
            else
            {
                return Error("修改失败");
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        [HttpPost]
        public ActionResult UpdatePassword()
        {
            string usercode = RequestString.GetFormString("usercode");
            string old = RequestString.GetFormString("old");
            string new1 = RequestString.GetFormString("new1");
            string new2 = RequestString.GetFormString("new2");
            if (string.IsNullOrEmpty(old) || string.IsNullOrEmpty(new1) || string.IsNullOrEmpty(new2))
            {
                return Error("请输入新旧密码");
            }
            if (new1 != new2)
            {
                return Error("两次输入的不一致");
            }

            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);
            if (old == userinfo.F_Password)
            {
                userinfo.F_Password = new1;
                new BLL.T_Sys_Users().Update(userinfo);

                return Success("修改成功");
            }
            else
            {
                return Error("原密码错误");
            }
        }

        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult GetWorkOrderList(int isdc = 0)
        {
            //string sql = " and F_IsDelete=0 ";
            string sql = " and (F_IsEnabled=0 or F_IsDelete=0) ";

        
          //  var ouid = DbHelperSQL.GetSingle(" select F_ID from T_Sys_Users where F_OpenId ='" + strusercode + "'");

          //  string sqlwhere = "select F_WorkOrderID FROM T_Bus_UserWorkOrder where F_UserId = '" + ouid.ToString() + "' ";
        //    sql += " and F_WorkOrderID in (" + sqlwhere + ")";


            DataTable dt = new DataTable();

            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));

            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);

            int deptid = RequestString.GetInt("deptid", 0);
            int dealtype = RequestString.GetInt("dealtype", -1);
            int issend = RequestString.GetInt("issend", -1);

            int isdeal = RequestString.GetInt("isdeal", -1);

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            #region sql 语句相关处理
            if (strstate.Trim() != "" && strstate != "undefined")
            {
                sql += " and F_WorkState = '" + strstate.Trim() + "' ";
            }
            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and F_WorkOrderId like '%" + strworkid + "%' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }

            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }

            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }

            if (deptid != 0)
            {
                string sqlwhere1 = "select F_WorkOrderID from T_Bus_AssignedInfo where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                sql += " and F_WorkOrderID in(" + sqlwhere1 + ")";
            }
            if (dealtype != -1)
            {
                sql += " and isnull(F_IsResult,0) = '" + dealtype + "' ";
            }
            if (issend != -1)
            {
                sql += " and isnull(F_IsRelease,0) = '" + issend + "' ";
            }

            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }
            if (isdeal != -1)
            {
                if (isdeal == 1)
                {
                    sql += " and F_WorkState = '9' ";
                }
                else
                {
                    sql += " and F_WorkState != '9' ";
                }
            }
            #endregion

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }

            string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";

            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder",
                "F_WorkOrderId",
                cols,
                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());

        }

        //市民评议
        public ActionResult Comment(string workorderid,string Satisfaction,string content)
        {
            var model = new BLL.T_Bus_WorkOrder().GetModel(workorderid);
            if (model != null)
            {
                string strStm_Src_Dsc = "";
                var DictionaryValue = new BLL.T_Sys_DictionaryValue().GetModel((int)model.F_InfoSource);
                if (DictionaryValue != null)
                {
                    strStm_Src_Dsc = DictionaryValue.F_Value;
                }
                string strSql = string.Format(@"INSERT INTO PublicComment ( [WorkOrderId], [strStm_Src_Dsc], [strWrkOrder_Cst_Ssf_Cd], [strUdt_Psn_ID], [strSsf_Cst_Ass_CntDsc], [strRltv_InsID], [strInpt_Inst_Nm], [strHpCnt], [CreateTime],[str_type]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}') ;select @@IDENTITY ", model.F_WorkOrderId, strStm_Src_Dsc, Satisfaction, "", content, "", "", "", DateTime.Now, 3);
                object objres = DbHelperSQL.GetSingle(strSql);
                if (Satisfaction == "非常满意" || Satisfaction == "满意" || Satisfaction == "基本满意")
                {
                    if (model != null)
                    {
                        Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                        keyValuePairs.Add("F_WorkState", 9);
                        keyValuePairs.Add("F_IsSatisfie", 1);
                        keyValuePairs.Add("F_IsClosed", 1);
                        keyValuePairs.Add("F_CloseUser", "");
                        keyValuePairs.Add("F_CloseTime", DateTime.Now);
                        keyValuePairs.Add("F_FinalOpinion", "市民评议满意自动结案");
                        keyValuePairs.Add("F_IsStandard", 1);
                        keyValuePairs.Add("F_StandardIDS", "");
                        keyValuePairs.Add("F_ToBereply", 0);
                        new BLL.T_Bus_WorkOrder().UpdateWorkOrder(model.F_Id, keyValuePairs);
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = model.F_WorkOrderId;
                        // oper.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                        oper.F_State = model.F_WorkState;
                        oper.F_Message = "市民网站评议满意，自动结案";
                        oper.F_CreateUser = "jianhang";
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;
                        operBLL.Add(oper);
                    }
                }
                return Success("评议成功");
            }
            else
            {
                return Error("工单不存在");
            }
          
           
        }
        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns></returns>

        public ActionResult GetList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string state = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            int ispy = RequestString.GetInt("ispy", -1);
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            #region sql 语句相关处理
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone  like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%'" +
                    " or F_Result like  '%" + strkey + "%' ) ";

            }
            if (state.Trim() != "" && state != "undefined")
            {
                if (state == "1")
                {
                    sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.submit + "," + (int)EnumWorkState.receive + (int)EnumWorkState.resubmit + ") ";
                }
                else if (state == "2")
                {
                    sql += " and F_WorkState in (" + (int)EnumWorkState.auditreback + "," + (int)EnumWorkState.dealing + "," + (int)EnumWorkState.auditdelay + (int)EnumWorkState.reload + (int)EnumWorkState.audit + (int)EnumWorkState.rejload + ") ";
                }
                else if (state == "3")
                {
                    sql += " and F_WorkState in (" + (int)EnumWorkState.visit + "," + (int)EnumWorkState.finish + "," + (int)EnumWorkState.dealed + ") ";
                }
                else if (state == "4")
                {

                    sql += " and F_WorkState not in ( 6,7,9 ) ";
                }

            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                if (strendtime.Trim() != "" && strendtime != "undefined")
                {
                    sql += " and F_CreateTime  between   '" + strstarttime +
                             "' AND  '" + strendtime + "'";
                }
                else
                {
                    sql += " and F_CreateTime>='" + strstarttime + "' ";
                }
            }
            else
            {
                if (strendtime.Trim() != "" && strendtime != "undefined")
                {
                    sql += " and F_CreateTime<='" + strendtime + "' ";
                }
            }

            if (ispy >-1)
            {
                if (ispy ==0)
                {
                    sql += "and  F_WorkOrderId not in (select WorkOrderId   from PublicComment WITH(NOLOCK)) ";
                }
                else
                {
                    sql += "and  F_WorkOrderId  in (select WorkOrderId   from PublicComment WITH(NOLOCK) )";
                }
            }
            #endregion

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
          
            string cols = "*,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";

            #region 导出
        
            #endregion
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder a WITH(NOLOCK)" ,
                "F_Id",
                cols,
                sql,
                "ORDER BY F_CreateTime DESC",
                pagesize,
                pageindex,
                true,
                out recordCount);
            #region 声音文件和交办超时
         
            foreach (DataRow dr in dt.Rows)
            {
              
            }
            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());

        }
        private BLL.T_Sys_SystemConfig configBll = new BLL.T_Sys_SystemConfig();
        public ActionResult GetWorkOrderNew()
        {
            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
           
            if (!string.IsNullOrEmpty(strworkorderid))
            {
                var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
               
                   
                        #region 基本信息
                        string sql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName1,dbo.GetAreaName(F_SourceArea) as AreaName,dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetKeyNames(F_Key) as KeyName,dbo.GetDeptName(F_MainDeptId) deptname ,dbo.GetAreaChildrenCode(F_Township) as Township , dbo.GetAreaChildrenCode(F_Village) as Village,F_DeptIdIsSms = (select F_IsSms  from T_Sys_Department WITH(NOLOCK) where F_DeptId =a.F_MainDeptId) from T_Bus_WorkOrder a WITH(NOLOCK) where F_WorkOrderId ='" + strworkorderid + "'";
                        var dt = DbHelperSQL.Query(sql).Tables[0];
                        if (dt.Rows.Count > 0)
                        {
                            #region 附件
                            if (configfj != null)
                            {
                                dt = BindFileData(dt, configfj.F_ParamValue);
                            }
                            string pysql = "select * from PublicComment WITH(NOLOCK) where  WorkOrderId ='" + strworkorderid + "' order by CreateTime";
                            var pydt = DbHelperSQL.Query(pysql).Tables[0];
                            #endregion
                            var obj = new
                            {
                                data = dt,
                                 pydt
                            };
                            return Success("获取成功", obj);
                        }
                        else
                        {
                            return Error("获取失败");
                        }
                    #endregion
                
             
                }
                return Error("获取失败");
           
        }
        private BLL.T_Sys_UserAccount userBLL = new BLL.T_Sys_UserAccount();
        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult GetOrderCount()
        {
            //string sql = " and F_IsDelete=0 ";
            string sql = " select count(1) from T_Bus_WorkOrder where F_IsDelete=0  ";
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(strusercode);
            string sqlld = "  and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";
            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG")
            {
                sqlld += " and F_CreateUser='" + userModel.F_UserCode + "')";
            }
            else
            {
                sqlld += ")";
            }
            string sqllddcl = sql + " and F_WorkState = '1' ";
            string sqlthsh = sql + " and F_WorkState = '3' " + sqlld;
            string sqlyssh = sql + " and F_WorkState = '5' " + sqlld;
            string sqlcbdjb = sql + " and F_WorkState = '11' " + sqlld;
            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG")
            {
                sqllddcl += " and (F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo WITH(NOLOCK) where F_State = 1 and F_IsDelete = 0 "
                    + "and F_CreateUser = '" + userModel.F_UserCode + "') or (select top 1 F_WorkOrderId from T_Bus_AssignedInfo WITH(NOLOCK) where"
                    + " F_State = 1 and F_IsDelete = 0 and T_Bus_AssignedInfo.F_WorkOrderId = T_Bus_WorkOrder.F_WorkOrderId) is null)";
            }
            string dw = "";
            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
            {
                dw += " and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and "
                + " ISNULL(F_FeedbackTime, '')='' and F_MainDeptId =" + userModel.F_DeptId + " and F_IsSure in (0,1))";
            }

            string dwdcs = sql + " and F_WorkState = '2' " + dw;
            string dwdbl = sql + " and F_WorkState = '4' " + dw;

            string dwthsh = sql + "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type = 3 ";
            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
            {
                dwthsh += " and F_CreateUser='" + userModel.F_UserCode + "')";
            }
            else
            {
                dwthsh += ")";
            }

            string dwyssh = sql + "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_DelayTime WITH(NOLOCK) where  F_IsDelete=0 ";
            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
            {
                dwyssh += " and F_CreateUser='" + userModel.F_UserCode + "')";
            }
            else
            {
                dwyssh += ")";
            }
            string dwspdb = sql + " and F_WorkState = '11' " + dw;

            int[] sts = new int[] { (int)EnumWorkState.dealing, (int)EnumWorkState.auditdelay };
            string ejdbl = sql + " and F_WorkState in (" + string.Join(",", sts.Select(p => p.ToString())) + ")";
            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
            {
                ejdbl += " and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo_Next WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and "
                    + " ISNULL(F_FeedbackTime, '')='' and F_MainDeptId =" + userModel.F_DeptId + " and F_IsSure in (0,1))";
            }

            string ejybl = sql + "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_Feedback_Next WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type in (1,2) ";
            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
            {
                ejybl += " and F_CreateUser='" + userModel.F_UserCode + "')";
            }
            else
            {
                ejybl += ")";
            }
            var obj = new
            {
                sqllddcl = DbHelperSQL.GetSingle(sqllddcl).ToString(),
                sqlthsh = DbHelperSQL.GetSingle(sqlthsh).ToString(),
                sqlyssh = DbHelperSQL.GetSingle(sqlyssh).ToString(),
                sqlcbdjb = DbHelperSQL.GetSingle(sqlcbdjb).ToString(),
                dwdcs = DbHelperSQL.GetSingle(dwdcs).ToString(),
                dwdbl = DbHelperSQL.GetSingle(dwdbl).ToString(),
                dwthsh = DbHelperSQL.GetSingle(dwthsh).ToString(),
                dwyssh = DbHelperSQL.GetSingle(dwyssh).ToString(),
                dwspdb = DbHelperSQL.GetSingle(dwspdb).ToString(),
                ejdbl = DbHelperSQL.GetSingle(ejdbl).ToString(),
                ejybl = DbHelperSQL.GetSingle(ejybl).ToString()
            };

            return Success("成功", obj);





        }
        /// <summary>
        /// 获取工单数量
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult GetWorkOrderCount(string usercode)
        {
            string stropenid = usercode;
            int type = RequestString.GetInt("type", 0);

            var wxuser = new BLL.T_Sys_UserAccount().GetModelList(" F_UserCode='" + stropenid.Trim() + "' and F_DeleteFlag=0 ").FirstOrDefault();

            string where = " F_WorkOrderId in (select F_WorkOrderId from T_Bus_UserWorkOrder where F_UserId='" + wxuser.F_UserId + "') ";


            string sql = " select count(1) from T_Bus_UserWorkOrder where F_UserId='" + wxuser.F_UserId + "' ";
            string sqlblz = " select count(1) from T_Bus_WorkOrder where " + where + " and F_WorkState!=9 and (F_IsEnabled=0 or F_IsDelete=0)";
            string sqlybl = " select count(1) from T_Bus_WorkOrder where " + where + " and F_WorkState =9 and (F_IsEnabled=0 or F_IsDelete=0)";

            string sqltype = " select F_ValueId,F_Value,(select COUNT(1) from T_Bus_WorkOrder where (F_IsEnabled=0 or F_IsDelete=0) ";
            if (type == 1)
            {
                sqltype += " and F_WorkState!=9";
            }
            else if (type == 2)
            {
                sqltype += " and F_WorkState=9";
            }
            sqltype += " and  F_InfoType=F_ValueId and " + where + ") Count from  dbo.T_Sys_DictionaryValue where F_ItemId=2 and F_State=0 ";

            DataTable dt = DbHelperSQL.Query(sqltype).Tables[0];

            var obj = new
            {
                total = DbHelperSQL.GetSingle(sql).ToString(),
                blzcount = DbHelperSQL.GetSingle(sqlblz).ToString(),
                yblcount = DbHelperSQL.GetSingle(sqlybl).ToString(),
                typedata = dt
            };

            return Success("成功", obj);
        }

        /// <summary>
        /// APP上传图片
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult Upload64()
        {
            //string dataurl = HttpUtility.UrlDecode(RequestString.GetFormString("dataurl"));
            string dataurl = RequestString.GetFormString("dataurl");
            string filename = RequestString.GetFormString("filename");
            if (!string.IsNullOrEmpty(dataurl))
            {
                string path = "/Upload/APP/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";

                ImageUpload iu = new ImageUpload();
                iu.SavePath = path;
                iu.DataUrl = dataurl;
                if (!string.IsNullOrEmpty(filename))
                {
                    iu.SaveType = 1;
                    iu.InFileName = filename;
                }
                iu.Upload64();

                int n = iu.Error;
                if (n == 0)
                {
                    path = path + iu.OutFileName;

                    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 = iu.OutFileName;//附件名称
                    model_T_Sys_Accessories.F_FileType = ".jpg";//附件类型
                    model_T_Sys_Accessories.F_FileUrl = path;//附件地址
                    model_T_Sys_Accessories.F_Size = iu.FileSize;
                    //model_T_Sys_Accessories.F_UserCode = userModel.F_UserCode;//上传人  
                    int id = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    model_T_Sys_Accessories.F_FileId = id;

                    return Success("成功", model_T_Sys_Accessories);
                }
                else
                {
                    string msg = string.Empty;
                    switch (n)
                    {
                        case 1: msg = "请选择要上传的文件"; break;
                        case 2: msg = "上传的文件类型不支持"; break;
                        case 3: msg = "上传的文件过大"; break;
                        case 4: msg = "未知错误"; break;
                    }
                    return Error(msg);
                }
            }
            else
            {
                return Error("请选择要上传的文件");
            }
        }
      
        /// <summary>
        /// 市民催单
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult AdditionalWorkOrder()
        {
            string usercode = RequestString.GetFormString("usercode");
            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);

            string workorderid = RequestString.GetFormString("workorderid");
            string title = RequestString.GetFormString("title");
            string content = RequestString.GetFormString("content");
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new BLL.T_Bus_WorkOrder().GetModel(workorderid);
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {

                    #region 插入附加记录
                    //批示记录
                    Model.T_Bus_Additional model_T_Bus_Additional = new Model.T_Bus_Additional();
                    model_T_Bus_Additional.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单流水号
                    model_T_Bus_Additional.F_Title = title;
                    model_T_Bus_Additional.F_Content = content;
                    model_T_Bus_Additional.F_CreateTime = DateTime.Now;
                    model_T_Bus_Additional.F_IsDelete = 0;
                    model_T_Bus_Additional.F_State = 1;
                    new BLL.T_Bus_Additional().Add(model_T_Bus_Additional);
                    #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 = "市民（" + userinfo.F_OpenId + "）催单，内容：" + content;
                    //oper.F_CreateUser = userModel.F_UserCode;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;

                    new BLL.T_Bus_Operation().Add(oper);
                    #endregion

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

        /// <summary>
        /// 获取工单信息
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult GetWorkOrder()
        {
            string usercode = RequestString.GetFormString("usercode");
            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);

            string workorderid = RequestString.GetFormString("workorderid");

            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
            //int type = RequestString.GetInt("type", 0);//0基本信息1监察意见2领导批示3办理情况4回访信息5督办信息6办理过程
            if (!string.IsNullOrEmpty(strworkorderid))
            {
                string sql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName1,"
                    + "dbo.GetAreaName(F_SourceArea) as AreaName,dbo.GetDictionaryName(F_InfoSource) as SourceName "
                    + " from T_Bus_WorkOrder where F_WorkOrderId ='" + strworkorderid + "'";
                var dt = DbHelperSQL.Query(sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

                    string jcsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_DeptId) as DeptName "
                                    + "from T_Bus_RemindRecord where F_Type=2 and F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string dbsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_DeptId) as DeptName "
                                    + "from T_Bus_RemindRecord where F_Type=1 and F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string pssql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_SubmitSuper where F_State=1 and F_IsDelete=0 and F_Type=1 and F_WorkOrderId ='" + strworkorderid + "'";
                    string zssql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_SubmitSuper where F_State=1 and F_IsDelete=0 and F_Type=2 and F_WorkOrderId ='" + strworkorderid + "'";
                    string htsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_SubmitSuper where F_State=1 and F_IsDelete=0 and F_Type=3 and F_WorkOrderId ='" + strworkorderid + "'";
                    string jbsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_MainDeptId) as DeptName,dbo.GetDeptNames(F_OtherDeptIds) as OtherDeptName "
                                    + "from T_Bus_AssignedInfo where F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string thsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_CreateDeptId) as DeptName "
                                    + "from T_Bus_Feedback where F_State=1 and F_Type=3 and F_IsDelete=0 and  F_WorkOrderId ='" + strworkorderid + "'";
                    string yssql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_DelayTime where  F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string blsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_CreateDeptId) as DeptName "
                                    + "from T_Bus_Feedback where F_State=1 and F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId ='" + strworkorderid + "'";
                    string hfsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_VisitResult where F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string gcsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_Operation where F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string cbsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_Additional where F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";


                    #region 附件
                    if (configfj != null)
                    {
                        dt = BindFileData(dt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 监察信息
                    var jcdt = DbHelperSQL.Query(jcsql).Tables[0];
                    if (configfj != null)
                    {
                        jcdt = BindFileData(jcdt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 批示信息
                    var psdt = DbHelperSQL.Query(pssql).Tables[0];
                    if (configfj != null)
                    {
                        psdt = BindFileData(psdt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 指示信息
                    var zsdt = DbHelperSQL.Query(zssql).Tables[0];
                    if (configfj != null)
                    {
                        zsdt = BindFileData(zsdt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 回退信息
                    var htdt = DbHelperSQL.Query(htsql).Tables[0];
                    #endregion

                    #region 督办信息
                    var dbdt = DbHelperSQL.Query(dbsql).Tables[0];
                    if (configfj != null)
                    {
                        dbdt = BindFileData(dbdt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 交办信息
                    var jbdt = DbHelperSQL.Query(jbsql).Tables[0];
                    if (configfj != null)
                    {
                        jbdt = BindFileData(jbdt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 退回信息
                    var thdt = DbHelperSQL.Query(thsql).Tables[0];
                    #endregion

                    #region 延时信息
                    var ysdt = DbHelperSQL.Query(yssql).Tables[0];
                    #endregion

                    #region 办理情况
                    var bldt = DbHelperSQL.Query(blsql).Tables[0];
                    if (configfj != null)
                    {
                        bldt = BindFileData(bldt, configfj.F_ParamValue);
                    }
                    #endregion

                    #region 回访信息
                    var hfdt = DbHelperSQL.Query(hfsql).Tables[0];
                    #endregion

                    #region 市民催单
                    var cbdt = DbHelperSQL.Query(cbsql).Tables[0];
                    #endregion

                    #region 办理过程
                    var gcdt = DbHelperSQL.Query(gcsql).Tables[0];
                    gcdt.Columns.Add("File", typeof(object));
                    if (configfj != null)
                    {
                        foreach (DataRow bldr in gcdt.Rows)
                        {
                            if (bldr["F_File"] != null && bldr["F_File"].ToString() != "" && configfj != null)
                            {
                                bldr["File"] = GetFileData(bldr["F_File"].ToString(), configfj.F_ParamValue);
                            }
                        }
                    }
                    #endregion


                    var obj = new
                    {
                        data = dt,
                        jcdata = jcdt,
                        psdata = psdt,
                        zsdata = zsdt,
                        htdata = htdt,
                        dbdata = dbdt,
                        jbdata = jbdt,
                        thdata = thdt,
                        ysdata = ysdt,
                        bldata = bldt,
                        hfdata = hfdt,
                        cbdata = cbdt,
                        gcdata = gcdt
                    };
                    return Success("获取成功", obj);
                }
                else
                {
                    return Error("获取失败");
                }
            }
            else
            {
                return Error("参数传输失败");
            }
        }

        /// <summary>
        /// 获取附件数据
        /// </summary>
        /// <param name="ids">附件id，多个用英文逗号,隔开</param>
        /// <param name="prefix">前缀</param>
        /// <returns></returns>
        public DataTable GetFileData(string ids, string prefix)
        {
            DataTable dt = DbHelperSQL.Query("select * from T_Sys_Accessories where F_FileId in (" + ids + ")").Tables[0];

            foreach (DataRow dr in dt.Rows)
            {
                dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
            }

            return dt;
        }

        /// <summary>
        /// 绑定附件信息
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public DataTable BindFileData(DataTable dt, string prefix)
        {
            dt.Columns.Add("File", typeof(object));
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["F_File"] != null && dr["F_File"].ToString() != "")
                {
                    dr["File"] = GetFileData(dr["F_File"].ToString(), prefix);
                }
            }
            return dt;
        }

        /// <summary>
        /// 修改工单信息
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult EditWorkOrder()
        {
            string usercode = RequestString.GetFormString("usercode");
            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);

            string workorderid = RequestString.GetFormString("workorderid");

            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new BLL.T_Bus_WorkOrder().GetModel(workorderid);
            Model.T_Bus_UserWorkOrder modelT_Bus_UserWorkOrder = new BLL.T_Bus_UserWorkOrder().GetModelList(" F_WorkOrderId='" + workorderid + "' ").FirstOrDefault();
            if (modelT_Bus_WorkOrder != null && modelT_Bus_UserWorkOrder != null && modelT_Bus_UserWorkOrder.F_UserId == userinfo.F_Id)
            {
                string cusname = RequestString.GetFormString("cusname");
                string cussex = RequestString.GetFormString("cussex");
                string cusphone = RequestString.GetFormString("cusphone");
                string cusaddress = RequestString.GetFormString("cusaddress");
                string email = RequestString.GetFormString("email");
                string zipcode = RequestString.GetFormString("zipcode");
                string conname = RequestString.GetFormString("conname");
                string conphone = RequestString.GetFormString("conphone");

                string title = RequestString.GetFormString("title");
                string content = RequestString.GetFormString("content");
                string files = RequestString.GetFormString("files");
                int sourcearea = RequestString.GetInt("sourcearea", 0);
                string sourceaddress = RequestString.GetFormString("sourceaddress");

                string keys = RequestString.GetFormString("keys");

                int type = RequestString.GetInt("type", 0);
                int bigtype = RequestString.GetInt("bigtype", 0);
                int smalltype = RequestString.GetInt("smalltype", 0);

                int isprotect = RequestString.GetInt("isprotect", 0);
                int level = RequestString.GetInt("level", 0);
                int issubmit = RequestString.GetInt("issubmit", 0);


                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存工单信息

                    modelT_Bus_WorkOrder.F_InfoType = type;//信息类别
                    modelT_Bus_WorkOrder.F_InfoConBigType = bigtype;//内容大类
                    modelT_Bus_WorkOrder.F_InfoConSmallType = smalltype;//内容小类
                    modelT_Bus_WorkOrder.F_SourceArea = sourcearea;//反映地域
                    modelT_Bus_WorkOrder.F_SourceAddress = sourceaddress;//事发地址

                    modelT_Bus_WorkOrder.F_CusName = cusname;//投诉人姓名
                    modelT_Bus_WorkOrder.F_CusSex = cussex;//性别
                    modelT_Bus_WorkOrder.F_CusPhone = cusphone;//来电号码
                    modelT_Bus_WorkOrder.F_CusAddress = cusaddress;//地址
                    modelT_Bus_WorkOrder.F_ZipCode = zipcode;//邮编
                    modelT_Bus_WorkOrder.F_ConName = conname;//联系人姓名
                    modelT_Bus_WorkOrder.F_ConPhone = conphone;//联系人电话
                    modelT_Bus_WorkOrder.F_Email = email;//E-mail

                    modelT_Bus_WorkOrder.F_ComTitle = title;//标题
                    modelT_Bus_WorkOrder.F_ComContent = content;//情况摘要（投诉内容）
                    modelT_Bus_WorkOrder.F_File = files;//附件
                    modelT_Bus_WorkOrder.F_IsProtect = isprotect;//保密方式0否1是

                    modelT_Bus_WorkOrder.F_Key = keys;
                    modelT_Bus_WorkOrder.F_Level = level;

                    new BLL.T_Bus_WorkOrder().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;
                    oper.F_CallRecordId = modelT_Bus_WorkOrder.F_CallRecordId;
                    oper.F_File = modelT_Bus_WorkOrder.F_File;

                    oper.F_Message = "市民（" + userinfo.F_OpenId + "） 修改了工单";


                    //oper.F_CreateUser = userModel.F_UserCode;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;

                    new BLL.T_Bus_Operation().Add(oper);

                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");

            }
            else
            {
                return Error("操作失败");
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [APPActionFilter]
        public ActionResult GetUserInfo()
        {
            string usercode = RequestString.GetQueryString("usercode");
            var userinfo = new BLL.T_Sys_Users().GetModel(usercode);
            return Success("获取成功", userinfo);
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [APPActionFilter]
        public ActionResult EditUser()
        {
            string usercode = RequestString.GetFormString("usercode");
            var dModel = new BLL.T_Sys_Users().GetModel(usercode);

            string name = RequestString.GetFormString("name");
            string phone = RequestString.GetFormString("phone");
            int sex = RequestString.GetInt("sex", 0);
            string province = RequestString.GetFormString("province");
            string city = RequestString.GetFormString("city");
            string county = RequestString.GetFormString("county");
            string address = RequestString.GetFormString("address");

            var list = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + usercode + "' and F_Id!='" + dModel.F_Id + "' ");
            if (list.Count > 0)
            {
                return Error("已经存在此账号");
            }
            else
            {
                dModel.F_Name = name;
                dModel.F_Telphone = phone;
                dModel.F_Sex = sex;
                dModel.F_Province = province;
                dModel.F_City = city;
                dModel.F_County = county;
                dModel.F_Address = address;

                bool n = new BLL.T_Sys_Users().Update(dModel);
                if (n)
                    return Success("修改成功", n);
                else
                    return Error("修改失败");
            }
        }
        private BLL.T_Cus_CustomerBase cusBLL = new BLL.T_Cus_CustomerBase();
        /// <summary>
        /// 保存客户档案
        /// </summary>
        /// <param name="telphone"></param>
        /// <param name="name"></param>
        /// <param name="phone"></param>
        /// <param name="countryid"></param>
        /// <param name="address"></param>
        /// <returns></returns>
        private void saveCus(string name, string phone, string address)
        {
            int res = 0;
            Model.T_Cus_CustomerBase cusmodel = new Model.T_Cus_CustomerBase();
            if (!string.IsNullOrWhiteSpace(phone))
            {
                cusmodel = cusBLL.GetModelBy(phone, name);
                if (cusmodel == null)
                {
                    cusmodel = new Model.T_Cus_CustomerBase();
                    cusmodel.F_Address = address;
                    cusmodel.F_CustomerName = name;
                    cusmodel.F_Mobile = phone;
                    cusmodel.F_DeleteFlag = 0;
                    res = cusBLL.Add(cusmodel);
                }
            }
        }
        string url = "http://172.16.0.10/Affairs/";
        //  string url = "http://localhost:63660/Affairs/";

        public void case_info(string workorderid, string parameter)
        {
            var Affairs = int.Parse(Configs.GetValue("Affairs"));
            if (Affairs > 0)
            {
                WebClient web = new WebClient();
                web.Encoding = Encoding.UTF8;
                string Dataurl = web.DownloadString(url + parameter + "?workorderid=" + workorderid);
            }

        }

        public void process_info(int id, string parameter, string title)
        {
            var Affairs = int.Parse(Configs.GetValue("Affairs"));
            if (Affairs > 0)
            {
                WebClient web = new WebClient();
                web.Encoding = Encoding.UTF8;
                string Dataurl = web.DownloadString(url + parameter + "?id=" + id + "&title=" + title);
            }
        }

        public void material_info(string WorkOrderId, string file, string area, int id, string type)
        {
            var Affairs = int.Parse(Configs.GetValue("Affairs"));
            if (Affairs > 0)
            {
                WebClient web = new WebClient();
                web.Encoding = Encoding.UTF8;
                string Dataurl = web.DownloadString(url + "case_material_info" + "?WorkOrderId=" + WorkOrderId + "&file=" + file + "&area=" + area + "&id=" + id + "&type=" + type);
            }
        }
    }
}