using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.App_Start;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Controllers.workorder;
using CallCenterApi.Interface.Models.Enum;
using CallCenterApi.Interface.Models.Input;
using CallCenterApi.Model;
using CallCenterAPI.WechatSDK;
using CallCenterAPI.WechatSDK.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using qcloudsms_csharp;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Xml;

namespace CallCenterApi.Interface.Controllers.weixin
{
    public class WxLoginController : BaseController
    {
        private readonly BLL.T_Sys_UserAccount userAccountBLL = new BLL.T_Sys_UserAccount();
        private readonly BLL.T_Sys_RoleInfo roleBLL = new BLL.T_Sys_RoleInfo();
        private readonly BLL.T_Cus_CustomerBaseNew customerBaseBLL = new BLL.T_Cus_CustomerBaseNew();
        private readonly BLL.T_Cus_CustomerFinance finbll = new BLL.T_Cus_CustomerFinance();
        private readonly BLL.T_Wo_WorkOrder woBLL = new BLL.T_Wo_WorkOrder();
        private readonly BLL.T_Sys_Department departmentBLL = new BLL.T_Sys_Department();
        private readonly BLL.T_Wo_WorkOrderItem_New itembll = new BLL.T_Wo_WorkOrderItem_New();
        private readonly BLL.T_Wo_WorkOrder_Logs blllogs = new BLL.T_Wo_WorkOrder_Logs();
        private readonly BLL.T_Sys_RoleInfo rolebll = new BLL.T_Sys_RoleInfo();
        private readonly BLL.T_Sys_DictionaryValue dicvalueBll = new BLL.T_Sys_DictionaryValue();
        private readonly BLL.T_Wo_MaterialManage mmBLL = new BLL.T_Wo_MaterialManage();
        BLL.T_Wo_QuestionManage quesBLL = new BLL.T_Wo_QuestionManage();

        ///// <summary>
        ///// 绑定微信号
        ///// </summary>
        ///// <param name="wxLoginDto"></param>
        ///// <returns></returns>
        //public ActionResult Login(WxLoginDto wxLoginDto)
        //{
        //    var res = Redirect("获取微信openId", wxLoginDto.RedirectUrl);
        //    var temp = WxHelper.GetOpenId(wxLoginDto);
        //    if (string.IsNullOrWhiteSpace(temp.OpenId))
        //        return res;

        //    //openId => 用户

        //    //如果不存在，跳转至登录页面
        //    res = Redirect("绑定微信号", "");
        //    return res;
        //}

        /// <summary>
        /// 绑定微信号 - 员工和业主分开登陆
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public ActionResult Login(WxLoginDto login)
        {
            #region 把其他OpenId更新为空
            var userAccount = userAccountBLL.GetModelByOpenid(login.OpenId);
            if (userAccount != null)
            {
                userAccount.F_WxOpenId = "";
                //userAccountBLL.Update(userAccount);
                string sql = $"update T_Sys_UserAccount set F_WxOpenId='' where F_UserId=" + userAccount.F_UserId;
                DbHelperSQL.ExecuteSql(sql);

            }
            var modelcustomer = customerBaseBLL.GetModelList(" F_WxOpenId='" + login.OpenId + "'").FirstOrDefault(); //customerBaseBLL.GetModelByOpenid(login.OpenId);
            if (modelcustomer != null)
            {
                modelcustomer.F_WxOpenId = "";
                //customerBaseBLL.Update(modelcustomer);
                string strsql = $"update T_Cus_CustomerBaseNew set F_WxOpenId='' where F_CustomerId=" + modelcustomer.F_CustomerId;
                DbHelperSQL.ExecuteSql(strsql);
            }
            #endregion

            if (string.IsNullOrEmpty(login.UserCode))
                return Error("账号不能为空！");
            if (string.IsNullOrEmpty(login.Password))
                return Error("密码不能为空！");
            Model.T_Sys_UserAccount loginCode = new BLL.T_Sys_UserAccount().LoginGetModel(login.UserCode, login.Password);
            Model.T_Sys_UserAccount loginwork = new BLL.T_Sys_UserAccount().LogworkGetModel(login.UserCode, login.Password);
            if (loginCode != null || loginwork != null)
            {
                Model.T_Sys_UserAccount loginUser = null;
                string deptcode = "";
                if (loginCode != null)
                    loginUser = loginCode;
                else
                    loginUser = loginwork;
                loginUser.F_WxOpenId = login.OpenId;
                int UserType = 0; string rolecode = ""; string UserName = ""; string rolename = "";
                UserName = loginUser.F_UserName;

                //部门
                Model.T_Sys_Department modelDep = new BLL.T_Sys_Department().GetModel(loginUser.F_DeptId);
                if (modelDep == null)
                    return Error("获取失败!");


                #region 读取角色code
                var rolemodel = roleBLL.GetModel(loginUser.F_RoleId);
                if (rolemodel != null)
                    rolecode = rolemodel.F_RoleCode;
                string area="", offic = "", region = "";
                region = loginUser.F_Remark;
                if (rolemodel.F_RoleCode == "DQJL")
                {
                    area = modelDep.F_DeptName;
                  
                }
                else if (rolemodel.F_RoleCode == "FGSJL")
                {
                    var dept = departmentBLL.GetModel(modelDep.F_ParentId);
                    if (dept != null)
                    {
                        area = dept.F_DeptName;
                      
                        offic = modelDep.F_DeptName;
                    }
                }
                else if (rolemodel.F_RoleCode == "YWY")
                {
                    if (modelDep != null)
                    {
                        if (modelDep.F_Layer == 2)
                        {
                                var dept = departmentBLL.GetModel(modelDep.F_ParentId);
                                if (dept != null)
                                {
                                area = dept.F_DeptName;
                             
                                offic = modelDep.F_DeptName;
                            }
                        }
                        if (modelDep.F_Layer == 1)
                        {
                            area = modelDep.F_DeptName;
                           
                        }
                    }
                }
                #endregion
                #region 部门角色
                //部门角色（-1管理员，1接待部，2案场经理、项目负责人,3销售部总经理、物业部总经理、工程总经理、设计总经理,4区域客服，5业主（客户档案））
                if (loginUser.F_RoleId == 17)
                {
                    //-1管理员
                    return Error("无操作权限");
                }
                else
                {
                    if (loginUser.F_RoleId == 60)
                    {
                        UserType = 0;
                        rolename = "分公司经理";
                    }
                    else if (loginUser.F_RoleId == 62)
                    {
                        UserType = 0;
                        rolename = "大区经理";
                    }
                    else if (loginUser.F_RoleId == 61)
                    {
                        UserType = 2;
                        rolename = "高层";
                    }
                    else if (loginUser.F_RoleId == 58)
                    {
                        UserType = 4;
                        rolename = "业务员";
                    }
                    else if (rolemodel.F_RoleCode== "BLRY")
                    {
                        UserType = 3;
                        rolename = "办理人员";
                    }
                    //else if (loginUser.F_RoleId == 59)
                    //{
                    //    UserType = 3;
                    //    rolename = "办理人员";
                    //}
                    else
                    {
                        return Error("无操作权限");
                    }
                 
                    #region
                    ////部门操作权限：1接待部，2办理人员，3区域客服，4监管
                    //IF (MODELDEP.F_TYPE == 1)
                    //{
                    //    //1--接待部
                    //    USERTYPE = 1;
                    //}
                    //ELSE IF (MODELDEP.F_TYPE == 2)
                    //{
                    //    //2--办理人员
                    //    USERTYPE = 2;
                    //}
                    //ELSE IF (MODELDEP.F_TYPE == 3)
                    //{
                    //    //3--区域客服
                    //    USERTYPE = 3;
                    //}
                    //ELSE IF (MODELDEP.F_TYPE == 4)
                    //{
                    //    //4--监管
                    //    USERTYPE = 4;
                    //}
                    //ELSE
                    //{
                    //    USERTYPE = 0;
                    //}
                    #endregion
                }
                #endregion
                var obj = new
                {
                    openid = login.OpenId,
                    usercode = login.UserCode,
                    usertype = UserType,
                    UserName = UserName,
                    rolename = rolename,
                    rolecode = rolecode,
                    area = area ,
                    offic =offic ,
                    region =region ,
                    flag= loginUser.F_Flag
                };

                if (userAccountBLL.Update(loginUser))
                    return Success("绑定成功", obj);
                else
                    return Error("绑定失败");
            }
            return Error("账号或密码错误，请重新登录");

            //else if (login.UserType == 5)
            //{
            //    //客户档案登录 - 用戶信息不存在时，登录客户档案业主账号
            //    Dictionary<string, string> paras_Customer = new Dictionary<string, string>();
            //    // F_RelationShipClassID IN (1,2) 用户类型：0来电用户; 1准业主; 2不是准业主或是亲戚朋友
            //    //首次密码默认为身份证后6位信息
            //    //F_CustomerClassID >= 0 为业主或租户，且F_RelationShipClassID = 0为会员账号 2、登录最早的信息
            //    string sql_Customer = " select * from dbo.T_Cus_CustomerBaseNew (NOLOCK) where F_CustomerCode=@F_UserCode and F_WxPassword=@F_PassWord and F_DeleteFlag = 0 ORDER BY F_CreatedOn ASC ";
            //    paras_Customer.Add("@F_UserCode", login.UserCode);
            //    paras_Customer.Add("@F_PassWord", login.Password);
            //    var dt_Customer = DbHelperSQL.Query(sql_Customer, paras_Customer).Tables[0];

            //    if (dt_Customer != null && dt_Customer.Rows.Count > 0)
            //    {
            //        //var customer = customerBaseBLL.GetModel(login.UserCode);  //20180926 次方法查询有漏洞
            //        var customer = customerBaseBLL.DataTableToList(dt_Customer).ToList().FirstOrDefault();
            //        customer.F_WxOpenId = login.OpenId;

            //        #region 新加 - 登录后同时获取用户账号，openid，和角色
            //        //5--业主（客户档案会员） 
            //        //int UserType = 5;
            //        var obj = new
            //        {
            //            openid = login.OpenId,
            //            usercode = login.UserCode,
            //            companyname = customer.F_CompanyName,
            //            //companyaddress=customer.F_CompanyAddress,
            //        };
            //        #endregion
            //        if (customerBaseBLL.Update(customer))
            //            return Success("绑定成功！", obj);
            //        else
            //            return Error("绑定失败！");
            //    }
            //    return Error("账号或密码错误或者没有注册，请重新登录");
            //}
            return Error("绑定失败");
        }

        /// <summary>
        /// 绑定微信号 - 员工和业主统一登陆 - 不用
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        [WechatActionFilter]
        public ActionResult Login2(WxLoginDto login)
        {
            Dictionary<string, string> paras = new Dictionary<string, string>();
            string sql = " select * from T_Sys_UserAccount (NOLOCK) where F_UserCode=@F_UserCode and F_PassWord=@F_PassWord and F_DeleteFlag = 0 ";
            paras.Add("@F_UserCode", login.UserCode);
            paras.Add("@F_PassWord", login.Password);
            var dt = DbHelperSQL.Query(sql, paras).Tables[0];

            #region 把其他OpenId更新为空
            var userAccount = userAccountBLL.GetModelByOpenid(login.OpenId);
            if (userAccount != null)
            {
                userAccount.F_WxOpenId = "";
                userAccountBLL.Update(userAccount);
            }
            var modelcustomer = customerBaseBLL.GetModelList(" F_WxOpenId='" + login.OpenId + "'").FirstOrDefault();//.GetModelByOpenid(login.OpenId);
            if (modelcustomer != null)
            {
                modelcustomer.F_WxOpenId = "";
                customerBaseBLL.Update(modelcustomer);
            }
            #endregion

            if (dt != null && dt.Rows.Count > 0)
            {
                var user = userAccountBLL.GetModel(login.UserCode);
                user.F_WxOpenId = login.OpenId;
                //int UserType = 0;

                //部门
                Model.T_Sys_Department modelDep = new BLL.T_Sys_Department().GetModel(user.F_DeptId);
                if (modelDep == null)
                    return Error("获取失败!");

                #region 部门角色
                ////部门角色（-1管理员，1接待部，2案场经理、项目负责人,3销售部总经理、物业部总经理、工程总经理、设计总经理,4区域客服，5业主（客户档案））
                //if (user.F_RoleId == 17)
                //{
                //    //-1管理员
                //    UserType = -1;
                //}
                //else
                //{
                //    //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                //    if (modelDep.F_Type == 1)
                //    {
                //        //1--接待部
                //        UserType = 1;
                //    }
                //    else if (modelDep.F_Type == 2)
                //    {
                //        //2--办理人员
                //        UserType = 2;
                //    }
                //    else if (modelDep.F_Type == 3)
                //    {
                //        //3--区域客服
                //        UserType = 3;
                //    }
                //    else if (modelDep.F_Type == 4)
                //    {
                //        //4--监管
                //        UserType = 4;
                //    }
                //    else
                //    {
                //        UserType = 0;
                //    }
                //}
                #endregion
                var obj = new
                {
                    openid = login.OpenId,
                    usercode = login.UserCode,
                    //usertype = UserType
                };

                if (userAccountBLL.Update(user))
                {
                    return Success("绑定成功", obj);
                }
                else
                {
                    return Error("绑定失败");
                }
            }
            else
            {
                //客户档案登录 - 用戶信息不存在时，登录客户档案业主账号
                Dictionary<string, string> paras_Customer = new Dictionary<string, string>();
                // F_RelationShipClassID IN (1,2) 用户类型：0来电用户; 1准业主; 2不是准业主或是亲戚朋友
                //首次密码默认为身份证后6位信息
                //F_CustomerClassID >= 0 为业主或租户，且F_RelationShipClassID = 0为会员账号 2、登录最早的信息
                string sql_Customer = " select * from dbo.T_Cus_CustomerBaseNew (NOLOCK) where F_CustomerCode=@F_UserCode and F_PassWord=@F_PassWord and F_DeleteFlag = 0 ";
                paras_Customer.Add("@F_UserCode", login.UserCode);
                paras_Customer.Add("@F_PassWord", login.Password);
                var dt_Customer = DbHelperSQL.Query(sql_Customer, paras_Customer).Tables[0];
                if (dt_Customer != null && dt_Customer.Rows.Count > 0)
                {
                    var customer = customerBaseBLL.GetModelList(" F_CustomerCode='" + login.UserCode + "'").FirstOrDefault(); //customerBaseBLL.GetModel(login.UserCode);
                    customer.F_WxOpenId = login.OpenId;

                    #region 新加 - 登录后同时获取用户账号，openid，和角色
                    //5--业主（客户档案会员） 
                    //int UserType = 5;
                    var obj = new
                    {
                        openid = login.OpenId,
                        usercode = login.UserCode,
                        //usertype = UserType
                    };
                    #endregion
                    if (customerBaseBLL.Update(customer))
                    {
                        return Success("绑定成功！", obj);
                    }
                    else
                    {
                        return Error("绑定失败！");
                    }
                }
                else
                {
                    return Error("账号或密码错误，请重新登录");
                }
                //return Error("账号或密码错误，请重新登录");
            }
        }
        /// <summary>
        /// 随机字符串数组集合
        /// </summary>
        private static readonly string[] NonceStrings = new string[]
                                    {
                                    "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
                                    "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
                                    };

        /// <summary>
        /// 生成签名的随机串
        /// </summary>
        /// <returns></returns>
        public static string CreateNonceStr()
        {
            Random random = new Random();
            var sb = new StringBuilder();
            var length = NonceStrings.Length;

            //生成15位数的随机字符串，当然也可以通过控制对应字符串大小生成，但是至多不超过32位
            for (int i = 0; i < 16; i++)
            {
                sb.Append(NonceStrings[random.Next(length - 1)]);//通过random获得的随机索引到，NonceStrings数组中获取对应数组值
            }
            return sb.ToString();
        }
       /// <summary>
       /// 获取签名
       /// </summary>
       /// <param name="url"></param>
       /// <returns></returns>
        public ActionResult GetJsSdk(string url)
        {
            var timestamp = GetCurrentUinxTime();
            var nonceStr = CreateNonceStr();
            var obj = new
            {
                state = "success",
                message = "成功",
                appId = AppId,
                timestamp = timestamp,
                nonceStr = nonceStr,
                token = GetToken(),
                ticket= Getticket(GetToken()),
                url,
                signature = GetSignature(Getticket(GetToken()), nonceStr, timestamp, url)
            };
            return Content(obj.ToJson()); ;
        }
      
       string     AppId = Configs.GetValue("WechatAppid");
        string   AppSecret = Configs.GetValue("WechatAppsecret");
        public class Token
        {
            public string token;
            public DateTime time;
        }
       
        public class AssedToken
        {
          
            public string access_token { get; set; }
          
            public int expires_in { get; set; }
          
          
        }
        public string  GetToken()
        {
            WebClient web = new WebClient();
            web.Encoding = Encoding.UTF8;
            string msg = "";
            var model = new BLL.T_Sys_AssToken().GetModelList("F_IsDelete=0 order by F_ID desc").FirstOrDefault();
            if (model!=null )
            {
                System.TimeSpan id = DateTime.Now - DateTime.Parse(model.F_CreatTime .ToString());
                if (id.TotalMinutes>=120)
                {
                    string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId + "&secret=" + AppSecret;
                    string Dataaa = web.DownloadString(url);//这一句话就能请求到数据了
                    JObject jo = (JObject)JsonConvert.DeserializeObject(Dataaa);
                    string access_token = jo["access_token"].ToString();
                   
                    var asser = new Model.T_Sys_AssToken();
                    asser.F_CreatTime = DateTime.Now;
                    asser.F_IsDelete = 0;
                    asser.F_Token = access_token;
                    int a = new BLL.T_Sys_AssToken().Add(asser);
                    if (a >0)
                    {
                        msg = access_token;
                    }
                }
                else
                {
                    msg = model.F_Token ;
                }
            }
            else
            {
                string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId + "&secret=" + AppSecret;
                string Dataaa = web.DownloadString(url);//这一句话就能请求到数据了
                JObject jo = (JObject)JsonConvert.DeserializeObject(Dataaa);
                string access_token = jo["access_token"].ToString();
                var asser = new Model.T_Sys_AssToken();
                asser.F_CreatTime = DateTime.Now;
                asser.F_IsDelete = 0;
                asser.F_Token = access_token;
                int a = new BLL.T_Sys_AssToken().Add(asser);
                if (a > 0)
                {
                    msg = access_token;
                }
            }
            
            return msg;
        }
       
        public string  Getticket(string token)
        {
            WebClient web = new WebClient();
            web.Encoding = Encoding.UTF8;
            string msg = "";
            string urltoken = " https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
            string Dataaasig = web.DownloadString(urltoken);//这一句话就能请求到数据了
            JObject jo = (JObject)JsonConvert.DeserializeObject(Dataaasig);
            string ticket = jo["ticket"].ToString();
            string errmsg = jo["errmsg"].ToString();
           
            return ticket;
        }
  
        public class Accesstoken
        {
            public string access_token;
            public int  expires_in;
        }
        /// <summary>
        /// 获取jsapi_ticket
        /// </summary>
        /// <param name="jsapi_ticket">微信公众号调用微信JS临时票据</param>
        /// <param name="nonceStr">随机串</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="url">当前网页URL</param>
        /// <returns></returns>
        public static string GetSignature(string jsapi_ticket, string nonceStr, long timestamp, string url)
        {

            var string1Builder = new StringBuilder();
            //注意这里参数名必须全部小写，且必须有序
            string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
                          .Append("noncestr=").Append(nonceStr).Append("&")
                          .Append("timestamp=").Append(timestamp).Append("&")
                          .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);

            return Sha1Sign(string1Builder.ToString());
        }

        public static string Sha1Sign(string data)
        {
            byte[] temp1 = Encoding.UTF8.GetBytes(data);
            SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
            byte[] temp2 = sha.ComputeHash(temp1);
            sha.Clear();
            // 注意， 不能用这个
            // string output = Convert.ToBase64String(temp2);// 不能直接转换成base64string
            var output = BitConverter.ToString(temp2);
            output = output.Replace("-", "");
            output = output.ToLower();
            return output;
        }

 

        /// <summary>
        /// 获取当前时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetCurrentUinxTime()
        {
            DateTime currentDate = DateTime.Now;//当前时间
            //转化为时间戳
          DateTime localTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
           return long.Parse((currentDate - localTime).TotalSeconds.ToString().Split('.')[0]);
           // var ticks = currentDate.ToUniversalTime().Ticks - new DateTime(1970, 1, 1, 0, 0, 0, //DateTimeKind.Utc).Ticks;
           // var timeSpan = ticks / TimeSpan.TicksPerSecond;
            //return timeSpan;

        }
        /// <summary>
        /// 获取微信openid
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public ActionResult GetOpenId(WxLoginDto wld)
        {
            //wld.RedirectUrl = RequestString.GetUrlReferrer();
            if (string.IsNullOrEmpty(wld.OpenId))
            {
                var temp = WxHelper.GetOpenId(wld);
                if (string.IsNullOrWhiteSpace(temp.OpenId))
                {

                    //Request.QueryString[ ] == null

                    return Redirect("请求", temp.RedirectUrl);
                }
                wld.OpenId = temp.OpenId;

                #region 获取是否绑定用户表
                //获取是否绑定用户表
                var usertemp = new BLL.T_Sys_UserAccount().GetModelByOpenid(wld.OpenId);

                if (usertemp != null)
                {
                    //部门
                    Model.T_Sys_Department modelDep = new BLL.T_Sys_Department().GetModel(usertemp.F_DeptId);
                    if (modelDep == null)
                        return Error("获取失败!");
                    wld.UserCode = usertemp.F_UserCode;
                    wld.Flag = usertemp.F_Flag;
                    #region 读取角色code
                    var rolemodel = roleBLL.GetModel(usertemp.F_RoleId);
                    if (rolemodel != null)
                        wld.RoleCode = rolemodel.F_RoleCode;
                    #endregion
                    #region 部门角色

                    if (usertemp.F_RoleId == 17)
                    {
                        //-1管理员
                        wld.UserType = -1;
                    }
                    else
                    {
                        if (usertemp.F_RoleId == 60 || usertemp.F_RoleId == 62)
                        {
                            wld.UserType = 0;
                        }
                        else if (usertemp.F_RoleId == 61)
                        {
                            wld.UserType = 2;
                        }
                        else if (usertemp.F_RoleId == 58)
                        {
                            wld.UserType = 4;
                        }
                        else if (rolemodel.F_RoleCode== "BLRY")
                        {
                            wld.UserType = 3;
                        }
                        else
                        {
                            wld.UserType = 1;
                        }

                        #region
                        ////部门操作权限：1接待部，2办理人员，3区域客服，4监管
                        //IF (MODELDEP.F_TYPE == 1)
                        //{
                        //    //1--接待部
                        //    USERTYPE = 1;
                        //}
                        //ELSE IF (MODELDEP.F_TYPE == 2)
                        //{
                        //    //2--办理人员
                        //    USERTYPE = 2;
                        //}
                        //ELSE IF (MODELDEP.F_TYPE == 3)
                        //{
                        //    //3--区域客服
                        //    USERTYPE = 3;
                        //}
                        //ELSE IF (MODELDEP.F_TYPE == 4)
                        //{
                        //    //4--监管
                        //    USERTYPE = 4;
                        //}
                        //ELSE
                        //{
                        //    USERTYPE = 0;
                        //}
                        #endregion


                        #region
                        ////部门操作权限：1接待部，2办理人员，3区域客服，4监管
                        //if (modelDep.F_Type == 1)
                        //{
                        //    //1--接待部
                        //    wld.UserType = 1;
                        //}
                        //else if (modelDep.F_Type == 2)
                        //{
                        //    //2--办理人员
                        //    wld.UserType = 2;
                        //}
                        //else if (modelDep.F_Type == 3)
                        //{
                        //    //3--区域客服
                        //    wld.UserType = 3;
                        //}
                        //else if (modelDep.F_Type == 4)
                        //{
                        //    //4--监管
                        //    wld.UserType = 4;
                        //}
                        //else
                        //{
                        //    wld.UserType = 0;
                        //}
                        #endregion
                    }
                    #endregion
                }
                else
                {
                    var customertemp = customerBaseBLL.GetModelByOpenid(wld.OpenId);
                    if (customertemp != null)
                    {
                        wld.UserCode = customertemp.F_CustomerCode;
                        //5--业主（客户档案会员）
                        wld.UserType = 5;
                    }
                    else
                    {
                        wld.UserCode = "";
                    }
                    //wld.UserCode = "";
                }
                #endregion
            }
            var model = new BLL.T_Sys_Users().GetModel(wld.OpenId);
            if (model == null)
            {
                model = new Model.T_Sys_Users();
                model.F_OpenId = wld.OpenId;
                model.F_Type = 1;
                model.F_CreateTime = DateTime.Now;
                new BLL.T_Sys_Users().Add(model);
            }
            var newobj = new
            {
                openid = wld.OpenId,
                usercode = wld.UserCode,
                usertype = wld.UserType,
                rolecode = wld.RoleCode,
                flag=wld.Flag
            };
            return Success("成功", newobj);
        }
        /// <summary>
        ///退回工单列表
        /// </summary>
        public string GetBackid(Model.T_Sys_UserAccount ua)
        {
            string str = string.Empty;

            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType in(" + (int)EnumItemType.deal + "," + (int)EnumItemType.audit + ")"
                + " and "
                    + "F_OptType in(" + (int)EnumItemOpt.abreback + "," + (int)EnumItemOpt.reback + ") and F_NextUser='" + ua.F_UserCode + "'"
                + ""
                + " and isnull(F_IsUsed,'0')='0' ";

            return str;
        }
        /// <summary>
        ///工单列表
        /// </summary>
        /// 

        public ActionResult GetList(string handler,string description,string OpenId, string code, string cusname, string keywords, string cusphone, string companyname, string province, string city,string createby,string createtel,
            string country, string township, string category, string salebase, string touser, int source = 0, int state = -1, int status = -1, int type = 0,int condition=-1, int pageindex = 1, int pagesize = 10)
        {
            //  int userId = CurrentUser.UserData.F_UserId;
            if (!string.IsNullOrEmpty(OpenId))
            {
                //  Model.T_Sys_UserAccount ua = userAccountBLL.GetModel(userId);
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
               // if (source != 3)
               // {
                   // if (ua == null)
                  //  {
                      //  return Error("你的账号已在别处登录，你确定要再次登录吗？");
                   // }
              // }
                //  Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                string sql = $" and F_IsDelete=0";
                DataTable dt = new DataTable();
                #region 筛选条件
                if (type > 0 && type < 6)//工单类型
                    sql += $" and F_Type=" + type;
                if (source > 0)//工单来源
                {
                    if (source == 1)
                        sql += $"  and (F_Source in (1,'')or F_Source is null )";
                    else
                        sql += $" and F_Source='" + source + "'";
                }
                if (!string.IsNullOrWhiteSpace(description))//问题描述
                    sql += $" and F_Description like '%" + description.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(touser))//参与人
                    sql += $" and F_DealBy like '%" + touser.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(code))//工单编号
                    sql += $" and F_WorkOrderCode like '%" + code.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(keywords))//关键字搜索
                    sql += $"  and  (F_QuestionType like '%" + keywords.Trim()
                         + "%' or F_ZX_Area like '%" + keywords.Trim() + "%' or F_ZX_Branch like '%" + keywords.Trim()
                         + "%' or F_CusName like '%" + keywords.Trim() + "%' or F_WorkOrderCode like '%" + keywords.Trim() + "%'or F_CusPhone like '%" + keywords.Trim() + "%' ) ";
                if (!string.IsNullOrWhiteSpace(cusname))//客户姓名
                    sql += $" and F_CusName like '%" + cusname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(cusphone))//客户电话
                    sql += $" and F_CusPhone like '%" + cusphone.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(companyname))//公司名称
                    sql += $" and F_CompanyName like '%" + companyname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(category))//产品名称
                    sql += $" and F_TS_Category like '%" + category.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(salebase))//销售基地
                    sql += $" and F_SalesBase like '%" + salebase.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//省
                    sql += $" and F_IncidentProvince like '%" + province.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//市
                    sql += $" and F_IncidentCity like '%" + city.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//县
                    sql += $" and F_IncidentCountry like '%" + country.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//乡
                    sql += $" and F_IncidentTownship like '%" + township.Trim() + "%'";
                if (condition>-1)
                {
                   
                        if (condition == 5)
                        {
                            sql += $" and F_State in (2,3,4,5)";
                        }
                        else if (condition == 6)
                        {
                            sql += $" and F_State in (11)";
                            sql += $" and F_IsVisit=" + 1; ;
                            sql += $"and F_DealType != '当即办理'  and F_VisitBy != ''";
                        }
                        else if (condition == 10)
                        {
                            sql += $" and F_State in (10,11)";
                        }
                        else if (condition == 12)
                        {
                            sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_IsVisit = '" + "1" + "' ";
                        }
                        else
                        {
                            sql += $" and F_State=" + condition;
                        }
                     if (ua != null)
                    {
                        Model.T_Sys_RoleInfo re = rolebll.GetModel(ua.F_RoleId);
                        if (re.F_RoleCode == "QTJS" || re.F_RoleCode == "YWY")
                            sql += $" and F_CreateBy like '%" + ua.F_UserCode.Trim() + "%'";
                        else if (re.F_RoleCode == "DQJL" || re.F_RoleCode == "FGSJL" || re.F_RoleCode == "BLRY" || re.F_RoleCode == "ZG")
                        {
                            string detpid = "" + ua.F_DeptId;
                            var deparmentlist = new List<Model.T_Sys_Department>();
                            Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                            if (dModel != null)
                            {
                                if (dModel.F_Layer == 1)
                                {
                                    deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                    if (deparmentlist.Count > 0)
                                    {
                                        foreach (var it in deparmentlist)
                                        {
                                            if (detpid != "")
                                            {
                                                detpid += "," + it.F_DeptId;
                                            }
                                            else
                                            {
                                                detpid = "" + it.F_DeptId;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    detpid = ua.F_DeptId.ToString();
                                }
                                if (state >= 0)
                                {
                                    if (GetDeptWorkOrderID(detpid) != "")
                                    {

                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") ";
                                    }
                                    else
                                    {

                                        return Success("暂无工单"); ;
                                    }
                                }
                                else
                                {
                                    if (GetDeptWorkOrderID(detpid) != "")
                                    {

                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") ";
                                    }
                                    else
                                    {

                                        return Success("暂无工单"); ;
                                    }
                                }

                            }
                            else
                            {
                                return Error("加载失败");
                            }
                        }
                    }

                }
                if (!string.IsNullOrWhiteSpace(createby))//创建人
                {
                    sql += $" and F_CustomerID  in(select F_CustomerCode from T_Cus_CustomerBaseNew where F_Salesman like '%" +createby+ "%' and F_IsDelete =0) ";
             }
                if (!string.IsNullOrWhiteSpace(createtel))//创建人
                {
                    sql += $" and F_CustomerID  in(select F_CustomerCode from T_Cus_CustomerBaseNew where F_SalesPhone like '%" + createtel + "%' and F_IsDelete =0) ";
                }
                if (!string .IsNullOrEmpty (handler))
                {
                    Model.T_Sys_UserAccount user = userAccountBLL .GetworkModel(handler);
                    if (user != null)
                    {
                        if (GetParticipate(user.F_UserCode) != "")
                        {

                            sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetParticipate(user.F_UserCode) + ") ";
                        }
                    }
                    else
                    {
                        Model.T_Sys_UserAccount userer = userAccountBLL.GetName(handler);
                        if (userer != null)
                        {
                            if (GetParticipate(userer.F_UserCode) != "")
                            {

                                sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetParticipate(userer.F_UserCode) + ") ";
                            }
                        }
                    }
                }
                //   sql += " and (F_CreateBy= '" + ua.F_UserCode + "' or T_Wo_WorkOrder.F_ID in ( " + GetCYWorkOrderID(ua.F_UserCode) + ")) ";
                if (source == 3)
                {
                    sql += $" and F_WxOpenId ='" + OpenId + "'";
                }
                else   if (ua != null)
                {
                    Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                   
                    if (state >-1)
                    {
                        switch (state)
                        {
                            case 0://待审批
                                string uwhere = "";

                                if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL")
                                {
                                    if (GetApprovalOrderID(ua, OpenId, ro.F_RoleCode) != "")
                                    {
                                        sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetApprovalOrderID(ua, OpenId, ro.F_RoleCode) + ") ";
                                    }
                                    else
                                    {
                                        return Success("暂无工单");
                                    }
                                }
                                else
                                {
                                    return Success("无操作权限");
                                }
                                break;
                            case 11://已创单
                                sql += $" and F_CreateBy  ='" + ua.F_UserCode + "'";
                                break;
                            case 12://退单
                                if (GetBackid(ua) != "")
                                {
                                    sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetBackid(ua) + ") ";
                                }
                                else
                                {
                                    return Success("暂无工单");
                                }
                                break;
                            case 1://已审核
                                if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "GC")
                                {
                                    if (GetApprovedOrderID(ua.F_UserCode) != "")
                                    {
                                        sql += $"  and F_ID in ( " + GetApprovedOrderID(ua.F_UserCode) + ") "; ;
                                    }
                                    else
                                    {
                                        return Error("暂无工单");
                                    }
                                }
                                else
                                {
                                    return Success("暂无工单");
                                }
                                break;
                            case 2://待完成的(待接单)
                                string strsql = GetDeptWorkOrderID(ua.F_DeptId, ua.F_UserCode, ua.F_Flag);
                                if (strsql != "")
                                {
                                    if (ua.F_Flag == 1)
                                    {
                                        sql += $" and F_State in(" + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.assign + ")  ";
                                    }
                                    else if (ua.F_Flag == 2)
                                    {
                                        sql += $" and F_State2 in(" + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.assign + ") ";
                                    }
                                    sql += " and T_Wo_WorkOrder.F_ID in ( " + strsql + ")";
                                }
                                else
                                {

                                    return Success("暂无工单"); ;
                                }

                                break;
                            case 5://待审批
                                if (ro.F_RoleCode == "GC")
                                {
                                    if (GetHApproval(ua.F_UserCode) != "")
                                    {
                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetHApproval(ua.F_UserCode) + ") "; ;
                                    }
                                }
                                else
                                {
                                    return Success("暂无工单"); ;
                                }
                                break;
                            case 4://待完成的(待处理)
                                string dealstr = GetDWCWorkOrderID(ua.F_UserCode, ua.F_DeptId, ua.F_Flag);
                                if (!string.IsNullOrEmpty(dealstr))
                                {
                                    if (ua.F_Flag == 1)
                                    {
                                        sql += " and (F_State in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.revoke + ")";
                                    }
                                    else if (ua.F_Flag == 2)
                                    {
                                        sql += " and (F_State2 in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.revoke + ")";
                                    }
                                    sql += "  and T_Wo_WorkOrder.F_ID in ( " + dealstr + ") ";
                                    if (!string.IsNullOrEmpty(GetRevokeWo(ua.F_UserCode)))
                                    {
                                        if (ua.F_Flag == 1)
                                        {
                                            sql += " or (F_State=" + (int)EnumWorkOrderState.assign + " and T_Wo_WorkOrder.F_ID in (" + GetRevokeWo(ua.F_UserCode) + ")))";
                                        }
                                        else if (ua.F_Flag == 2)
                                        {
                                            sql += " or (F_State2=" + (int)EnumWorkOrderState.assign + " and T_Wo_WorkOrder.F_ID in (" + GetRevokeWo(ua.F_UserCode) + ")))";
                                        }
                                    }
                                    else
                                    {
                                        sql += $")";
                                    }
                                }
                                else
                                {
                                    return Success("暂无工单"); ;
                                }
                                break;
                            case 10://已完成的
                                if (GetDeptUserCode(ua.F_DeptId) != "")
                                {
                                    if (ua.F_Flag == 1)
                                    {
                                        sql += " and F_State in(10,11)";
                                    }
                                    else if (ua.F_Flag == 2)
                                    {
                                        sql += " and F_State2 in(10,11)";
                                    }
                                    sql += "  and F_DealBy in(" + GetDeptUserCode(ua.F_DeptId) + ") ";
                                }
                                //  sql += " and F_State in(10,11) and F_DealBy = '" + ua.F_UserCode + "' ";
                                break;
                            case 3://我参与的
                                if (GetParticipateID(ua.F_UserCode) != "")
                                {
                                    sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetParticipateID(ua.F_UserCode) + ") ";
                                }
                                else
                                {
                                    return Error("暂无工单");
                                }

                                break;
                            case 6://待回访
                                if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX")
                                {
                                    uwhere = $" and F_Type <> 3";
                                }
                                else
                                {
                                    return Success("无操作权限"); ;
                                }
                                sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_State2=" + (int)EnumWorkOrderState.finish + " and F_IsVisit = '" + "1" + "' " + uwhere; ;
                                break;
                            case 7://已回访
                                if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX")
                                {
                                    if (GetCYWorkOrderID(ua.F_UserCode) != "")
                                    {
                                        sql += " and (F_CreateBy= '" + ua.F_UserCode + "' or T_Wo_WorkOrder.F_ID in ( " + GetCYWorkOrderID(ua.F_UserCode) + ")) ";
                                    }
                                    else
                                    {
                                        return Success("暂无工单"); ;
                                    }
                                    sql += $" and F_State=" + (int)EnumWorkOrderState.evaluate;
                                }
                                else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "ZG")
                                {
                                    string detpid = "" + ua.F_DeptId;
                                    var deparmentlist = new List<Model.T_Sys_Department>();
                                    Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                                    if (dModel != null)
                                    {
                                        if (dModel.F_Layer == 1)
                                        {
                                            deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                            if (deparmentlist.Count > 0)
                                            {
                                                foreach (var it in deparmentlist)
                                                {
                                                    if (detpid != "")
                                                    {
                                                        detpid += "," + it.F_DeptId;
                                                    }
                                                    else
                                                    {
                                                        detpid = "" + it.F_DeptId; ;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            detpid = ua.F_DeptId.ToString();
                                        }
                                        if (GetDeptWorkOrderID(detpid, "" + (int)EnumWorkOrderState.evaluate + "") != "")
                                        {
                                            sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid, "" + (int)EnumWorkOrderState.evaluate + "") + ") "; ;
                                        }
                                        else
                                        {

                                            return Success("暂无工单"); ;
                                        }

                                    }
                                    else
                                    {
                                        return Error("加载失败");
                                    }
                                }
                                else
                                {
                                    return Success("无操作权限"); ;
                                }
                                sql += $" and F_State=" + (int)EnumWorkOrderState.evaluate;
                                break;
                            case 8://待完结
                                if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX")
                                {
                                    uwhere = ""; ;
                                }
                                else
                                {
                                    return Success("无操作权限"); ;
                                }
                                sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_State2=" + (int)EnumWorkOrderState.finish + " and ( F_IsVisit = '" + "0" + "' or  F_Type = 3)"; ;
                                break;
                            case 9://待接单

                                string strsql2 = GetDeptWorkOrderID(ua.F_DeptId, ua.F_UserCode, ua.F_Flag);
                                if (strsql2 != "")
                                {
                                    if (ua.F_Flag == 1)
                                    {
                                        sql += $" and F_State in(" + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.assign + ")  ";
                                    }
                                    else if (ua.F_Flag == 2)
                                    {
                                        sql += $" and F_State2 in(" + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.assign + ") ";
                                    }
                                    sql += " and T_Wo_WorkOrder.F_ID in ( " + strsql2 + ")";
                                }
                                else
                                {

                                    return Success("暂无工单"); ;
                                }

                                break;
                            case 20: //抄送工单列表
                                sql += $" and T_Wo_WorkOrder.F_ID in (select F_WorkOrderID from T_Wo_WorkCopy where F_SendCopyUser like '%{ua.F_UserCode}%'"
                                    + $" or (F_Flag=1 and F_SendCopyDepts={ua.F_DeptId} )) ";
                                break;
                        }
                    }
                    else
                    {
                        if (ro.F_RoleCode == "QTJS" || ro.F_RoleCode == "YWY")
                            sql += $" and F_CreateBy like '%" + ua.F_UserCode.Trim() + "%'";
                        else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "BLRY" || ro.F_RoleCode == "ZG")
                        {
                            string detpid = "" + ua.F_DeptId;
                            var deparmentlist = new List<Model.T_Sys_Department>();
                            Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                            if (dModel != null)
                            {
                                if (dModel.F_Layer == 1)
                                {
                                    deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                    if (deparmentlist.Count > 0)
                                    {
                                        foreach (var it in deparmentlist)
                                        {
                                            if (detpid != "")
                                            {
                                                detpid += "," + it.F_DeptId;
                                            }
                                            else
                                            {
                                                detpid = "" + it.F_DeptId;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    detpid = ua.F_DeptId.ToString();
                                }
                                if (state >= 0)
                                {
                                    if (GetDeptWorkOrderID(detpid) != "")
                                    {

                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") ";
                                    }
                                    else
                                    {

                                        return Success("暂无工单"); ;
                                    }
                                }
                                else
                                {
                                    if (GetDeptWorkOrderID(detpid) != "")
                                    {

                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") ";
                                    }
                                    else
                                    {

                                        return Success("暂无工单"); ;
                                    }
                                }

                            }
                            else
                            {
                                return Error("加载失败");
                            }
                        }
                    }
                 
                }
                else
                {
                    sql += $" and F_WxOpenId ='" + OpenId + "'";
                }

                #endregion
                int recordCount = 0;
                if (!string.IsNullOrWhiteSpace(sql))
                {

                    dt = BLL.PagerBLL.GetListPager(
                        "T_Wo_WorkOrder",
                        "F_ID",
                        "*",
                        sql,
                        "ORDER BY T_Wo_WorkOrder.F_ID desc",
                        pagesize,
                        pageindex,
                        true,
                        out recordCount);
                }
                List<Model.T_Wo_WorkOrder> modlelist = new BLL.T_Wo_WorkOrder().DataTableToList(dt);
                if (modlelist.Count > 0)
                {
                    List<WorkOrderNewInput> Input = modeltooip(modlelist, ua);
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = Input,
                        total = recordCount
                    };

                    return Content(obj.ToJson()); ;
                }
                else
                {
                    return Success("暂无工单"); ;
                }
            }
            else
            {
                return Success("暂无工单"); ;
            }
        }


        /// <summary>
        /// 指派工单时撤回
        /// </summary>
        /// <param name="usercode"></param>
        /// <returns></returns>
        public string GetRevokeWo(string usercode, int flag = 0)
        {
            string str = string.Empty;

            str = $"Select F_WoID from T_Wo_WorkOrderItem_New where F_IsUsed=0 and  F_OptType=" + (int)EnumItemOpt.assign +
                  $" and F_CreateUser='{usercode}'  group by F_WoID HAVING COUNT(*) >{flag}";
            var modetab = DbHelperSQL.Query(str).Tables[0];
            var modelarray = modetab.AsEnumerable().Select(c => c.Field<long>("F_WoID")).ToArray(); ;
            str = string.Join(",", modelarray);
            return str;
        }

        public string GetDeptUserCode(int deptid)
        {
            string deptuser = string.Empty;
            var dept = userAccountBLL .GetModelList("F_DeptId=" + deptid);
            if (dept != null)
            {
                foreach (var it in dept)
                {
                    if (deptuser != "")
                        deptuser += "," + it.F_UserCode;
                    else
                        deptuser += it.F_UserCode;
                }
            }
            return deptuser;
        }

        /// <summary>
        /// 市场管理科 和质量管理科可以看到整个事业部的工单
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="pdeptid"></param>
        /// <returns></returns>
        public string GetAllDepts(int deptid)
        {
            string sql = " F_State=1 ";
            string dptcode = departmentBLL.GetModel(deptid).F_ParentCode;
            string arrsql = " select F_DeptId from T_Sys_Department where F_DeptCode LIKE '" + dptcode + "%' ";
            var deptlist = departmentBLL.GetModelList(sql).Select(p => p.F_DeptId).ToArray();
            if (deptlist.Count() > 0)
                return string.Join(",", deptlist);
            else return "";
        }

        /// <summary>
        ///  市场管理科 和质量管理科可以看到整个事业部的工单
        /// </summary>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public string GetDeptAllWorkOrderID(int deptid)
        {
            string sql = " ";
            string dptcode = departmentBLL.GetModel(deptid).F_ParentCode;
            string arrsql = $"select F_DeptId from T_Sys_Department where F_DeptCode LIKE '" + dptcode + "%' ";
            string ua = $"select F_UserCode from T_Sys_UserAccount where F_DeptId in ( " + arrsql + ") ";
            sql = "select F_WoID from T_Wo_WorkOrderItem_New where (F_CreateUser in(" + ua + ") or F_NextDept in(" + arrsql + "))";
            return sql;
        }

        /// <summary>
        /// 高层可以看到本事业部的所有工单
        /// </summary>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public string judgmentDept(int deptid)
        {
            string deptcode = "";
            string sql = " ";

            if (CirculMarket(deptid, 11))
            {
                deptcode = "|0|1|11|";
            }
            else if (CirculMarket(deptid, 14))
            {
                deptcode = "|0|1|14|";
            }
            else if (CirculMarket(deptid, 15))
            {
                deptcode = "|0|1|15|";
            }
            else if (CirculMarket(deptid, 16))
            {
                deptcode = "|0|1|16|";
            }
            else if (CirculMarket(deptid, 18))
            {
                deptcode = "|0|1|18|";

            }
            else if (CirculMarket(deptid, 20))
            {
                deptcode = "|0|1|20|";
            }
            if (!string.IsNullOrEmpty(deptcode))
            {
                string arrsql = $"select F_DeptId from T_Sys_Department where F_DeptCode LIKE '" + deptcode + "%' ";
                string ua = $"select F_UserCode from T_Sys_UserAccount where F_DeptId in ( " + arrsql + ") ";
                sql = "select F_WoID from T_Wo_WorkOrderItem_New where (F_CreateUser in(" + ua + ") or F_NextDept in(" + arrsql + "))";
            }
            return sql;
        }

        /// <summary>
        ///综合查询列表
        /// </summary>
        public ActionResult GetComprehensive(string description,string OpenId, string code, string createby, string createtel, string cusname, string keywords, string cusphone, string companyname, string province, string city,
            string country, string township, string category, string salebase, string touser, int source = 0, int state = -1, int type = 0, int pageindex = 1, int pagesize = 10)
        {

            if (!string.IsNullOrEmpty(OpenId))
            {
                //  Model.T_Sys_UserAccount ua = userAccountBLL.GetModel(userId);
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
              //  if (ua == null)
             //   {
              //      return Error("你的账号已在别处登录，你确定要再次登录吗？");
            //    }
                string sql = $" and F_IsDelete=0";
                DataTable dt = new DataTable();
                #region 筛选条件
                if (type > 0 && type < 6)//工单类型
                    sql += $" and F_Type=" + type;
                if (state >= 0)//
                {
                    if (state == 5)
                    {
                        sql += $" and F_State in (2,3,4,5)";
                    }
                    else if (state == 6)
                    {
                        sql += $" and F_State in (11)";
                        sql += $" and F_IsVisit=" + 1; ;
                        sql += $"and F_DealType != '当即办理'  and F_VisitBy != ''";
                    }
                    else if (state == 10)
                    {
                        sql += $" and F_State in (10,11)";
                    }
                    else if (state == 12)
                    {
                        sql += $" and F_State=" + (int)EnumWorkOrderState.finish + " and F_IsVisit = '" + "1" + "' ";
                    }
                    else
                    {
                        sql += $" and F_State=" + state;
                    }

                }
                if (source > 0)//工单来源
                {
                    if (source == 1)
                        sql += $" and F_Source in (1,'')";
                    else
                        sql += $" and F_Source='" + source + "'";
                }
                if (!string.IsNullOrWhiteSpace(createby))//创建人
                {
                    sql += $" and F_CustomerID  in(select F_CustomerCode from T_Cus_CustomerBaseNew where F_Salesman like '%" + createby + "%' and F_IsDelete =0) ";
                }
                if (!string.IsNullOrWhiteSpace(createtel))//创建人
                {
                    sql += $" and F_CustomerID  in(select F_CustomerCode from T_Cus_CustomerBaseNew where F_SalesPhone like '%" + createtel + "%' and F_IsDelete =0) ";
                }             
                if (!string.IsNullOrWhiteSpace(description))//问题描述
                    sql += $" and F_Description like '%" + description.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(createby))//创建人
                    sql += $" and F_CreateBy like '%" + createby.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(touser))//参与人
                    sql += $" and F_DealBy like '%" + touser.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(code))//工单编号
                    sql += $" and F_WorkOrderCode like '%" + code.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(keywords))//关键字搜索
                    sql += $"  and ( F_QuestionType like '%" + keywords.Trim()
                         + "%' or F_ZX_Area like '%" + keywords.Trim() + "%' or F_ZX_Branch like '%" + keywords.Trim()
                         + "%' or F_CusName like '%" + keywords.Trim() + "%'or F_CusPhone like '%" + keywords.Trim() + "%')  ";
                if (!string.IsNullOrWhiteSpace(cusname))//客户姓名
                    sql += $" and F_CusName like '%" + cusname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(cusphone))//客户电话
                    sql += $" and F_CusPhone like '%" + cusphone.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(companyname))//公司名称
                    sql += $" and F_CompanyName like '%" + companyname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(category))//产品名称
                    sql += $" and F_TS_Category like '%" + category.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(salebase))//销售基地
                    sql += $" and F_SalesBase like '%" + salebase.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//省
                    sql += $" and F_IncidentProvince like '%" + province.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(city))//市
                    sql += $" and F_IncidentCity like '%" + city.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(country))//县
                    sql += $" and F_IncidentCountry like '%" + country.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(township))//乡
                    sql += $" and F_IncidentTownship like '%" + township.Trim() + "%'";
                if (ua != null)
                {
                    Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                    if (ro.F_RoleCode == "QTJS" || ro.F_RoleCode == "YWY")
                    {
                        sql += $" and F_CreateBy like '%" + ua.F_UserCode.Trim() + "%'";
                    }
                    else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "BLRY" || ro.F_RoleCode == "ZG" || ro.F_RoleCode == "GC")
                    {
                        string markdepts = "37,57,74,88,268,422,339";
                        string qualdepts = "12,36,295";
                        string detpid = "" + ua.F_DeptId;
                        var deparmentlist = new List<Model.T_Sys_Department>();
                        Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                        if (dModel != null)
                        {

                            #region  工单查询- 综合查询模块，权限增加，市场部和质管部可以看到事业部所有的工单，包含未经办的  20220519
                            if (markdepts.Contains(ua.F_DeptId.ToString()) || qualdepts.Contains(ua.F_DeptId.ToString()))
                            {
                                //detpid += "," + GetAllDepts(ua.F_DeptId);
                                sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptAllWorkOrderID(ua.F_DeptId) + ") ";
                            }
                            #endregion
                            #region 高层可以看到本事业部的所有工单
                            else if (ro.F_RoleCode == "GC")
                            {
                                string strsq = judgmentDept(ua.F_DeptId);
                                if (!string.IsNullOrEmpty(strsq))
                                {
                                    sql += $"  and T_Wo_WorkOrder.F_ID in ( " + strsq + ") ";
                                }
                            }
                            #endregion
                            else
                            {
                                if (dModel.F_Layer == 1)
                                {
                                    deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                    if (deparmentlist.Count > 0)
                                    {
                                        foreach (var it in deparmentlist)
                                        {
                                            if (detpid != "")
                                            {
                                                detpid += "," + it.F_DeptId;
                                            }
                                            else
                                            {
                                                detpid = "" + it.F_DeptId;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    detpid = ua.F_DeptId.ToString();
                                }
                                #region 人员更换部门后，仍然需要查看、处理自己原部门的历史工单 20220307
                                //if (!string.IsNullOrEmpty(ua.F_Origdepts))
                                //{
                                //    detpid += "," + ua.F_Origdepts;
                                //}
                                #endregion
                                if (state >= 0)
                                {
                                    if (GetDeptWorkOrderID(detpid, "" + state + "") != "")
                                    {

                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid, "" + state + "") + ") ";
                                    }
                                    else
                                    {

                                        return Success("暂无工单"); ;
                                    }
                                }
                                else
                                {
                                    if (GetDeptWorkOrderID(detpid, "" + (int)EnumWorkOrderState.neworder + ", " + (int)EnumWorkOrderState.assign + "," +
                        (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.finish
                        + "," + (int)EnumWorkOrderState.evaluate + "") != "")
                                    {

                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid, "" + (int)EnumWorkOrderState.neworder + ", " + (int)EnumWorkOrderState.assign + "," +
                        (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.finish
                        + "," + (int)EnumWorkOrderState.evaluate + "") + ") ";
                                    }
                                    else
                                    {

                                        return Success("暂无工单"); ;
                                    }
                                }
                            }

                        }
                        else
                        {
                            return Error("加载失败");
                        }
                    }
                }
                else
                {
                    return Error("无操作权限");
                }

                #endregion
                int recordCount = 0;
                if (!string.IsNullOrWhiteSpace(sql))
                {

                    dt = BLL.PagerBLL.GetListPager(
                        "T_Wo_WorkOrder",
                        "F_ID",
                        "*",
                        sql,
                        "ORDER BY T_Wo_WorkOrder.F_ID desc",
                        pagesize,
                        pageindex,
                        true,
                        out recordCount);
                }
                List<Model.T_Wo_WorkOrder> modlelist = new BLL.T_Wo_WorkOrder().DataTableToList(dt);
                if (modlelist.Count > 0)
                {
                    List<WorkOrderNewInput> Input = modeltooip(modlelist, ua);
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = Input,
                        total = recordCount
                    };

                    return Content(obj.ToJson()); ;
                }
                else
                {
                    return Success("暂无工单"); ;
                }
            }
            else
            {
                return Error("无操作权限！");
            }
        }
        /// <summary>
        /// 根据部门获取工单号
        /// </summary>
        /// <returns></returns>
        public string GetDeptWorkOrderID(string user)
        {
            string sql = " ";
            string ua = "";
            DataTable dt = new DataTable();
            if (user != "")
            {
                sql += " and F_DeptId in ( " + user + ") ";
            }
            int recordCount;
            dt = BLL.PagerBLL.GetListPager(
                                     "T_Sys_UserAccount",
                                     "F_UserId",
                                     "*",
                                     sql,
                                     "ORDER BY F_UserId desc",
                                      10000,
                                      1,
                                     true,
                                     out recordCount);
            List<Model.UserAccount> modelList = new BLL.UserAccount().DataTableToList(dt);
            if (modelList != null)
            {
                foreach (var it in modelList)
                {
                    if (ua != "")
                        ua += "," + it.F_UserCode;
                    else
                        ua += it.F_UserCode;
                }
            }
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where (F_CreateUser in(" + ua + ")  or F_NextDept in(" + user + "))"
             ;

            return str;
        }
        /// <summary>
        /// 根据部门获取工单号
        /// </summary>
        /// <returns></returns>
        public string GetDeptWorkOrderID(string user, string F_ItemType)
        {
            string sql = " ";
            string ua = "";
            DataTable dt = new DataTable();
            if (user != "")
            {
                sql += " and F_DeptId in ( " + user + ") ";
            }
            int recordCount;
            dt = BLL.PagerBLL.GetListPager(
                                     "T_Sys_UserAccount",
                                     "F_UserId",
                                     "*",
                                     sql,
                                     "ORDER BY F_UserId desc",
                                      10000,
                                      1,
                                     true,
                                     out recordCount);
            List<Model.UserAccount> modelList = new BLL.UserAccount().DataTableToList(dt);
            if (modelList != null)
            {
                foreach (var it in modelList)
                {
                    if (ua != "")
                        ua += "," + it.F_UserCode;
                    else
                        ua += it.F_UserCode;
                }
            }
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_OptType in(" + F_ItemType + ")"
                + " and  "
                     + "F_CreateUser in(" + ua + ")"
               ;

            return str;
        }
        /// <summary>
        /// 获取待完成的工单编号
        /// </summary>
        /// <returns></returns>
        public string GetDWCWorkOrderID(string user, int deptid, int flag = 1)
        {
            string str = string.Empty;
            string strsql = "";

            if (flag == 1)
            {
                strsql = "and F_Type in(1,3)";
            }
            else if (flag == 2)
            {
                strsql = "and F_Type in(2,3)";
            }
            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
               + " and (F_WoState in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.revoke + ") and "
               + "(F_CreateUser='" + user + "' or F_NextDept='" + deptid + "')) "//办理中和接单状态的操作人，退回下一步操作人，撤回下一步操作人
               + " and isnull(F_IsUsed,'0')='0' " + strsql + "";
            return str;
        }
        public string GetHApproval(string user)
        {
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where   F_ItemType=" + (int)EnumItemType.audit + " and  F_OptType=" + (int)EnumItemOpt.audit + "and F_NextUser= '" + user + "'" + "and F_IsUsed=2";
            return str;
        }
        /// <summary>
        /// 获取部门待完成的工单编号
        /// </summary>
        /// <returns></returns>
        public string GetDeptWorkOrderID(int deptid, string user, int flag = 1)
        {
            string str = string.Empty;
            string deptuser = string.Empty;
            var dept = userAccountBLL.GetModelList("F_DeptId=" + deptid);
            if (dept != null)
            {
                foreach (var it in dept)
                {
                    //if (it.F_UserCode != user)
                    //{
                    if (deptuser != "")
                        deptuser += "','" + it.F_UserCode;
                    else
                        deptuser += it.F_UserCode;
                    //}
                }
            }
            if (!string.IsNullOrEmpty(deptuser))
            {
                if (flag == 1)
                {
                    // string deptuser = "select F_WoID from T_Sys_UserAccount where F_DeptId=" + deptid;
                    str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
                        + " and isnull(F_IsUsed,'0')='0'  and F_Type in(1,3)" + " and "
                       + " F_WoState in(" + (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.abreback + ") and (F_NextUser in('" + deptuser + "') or  F_NextDept =" + deptid + ") "; //办理中和接单状态的操作人


                }
                else if (flag == 2) //内线
                {
                    // string deptuser = "select F_WoID from T_Sys_UserAccount where F_DeptId=" + deptid;
                    str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
                        + " and isnull(F_IsUsed,'0')='0'  and F_Type in(2,3)" + " and "
                        + " F_WoState in(" + (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.abreback + ") and (F_NextUser in('" + deptuser + "') or F_NextDept =" + deptid + ") ";//办理中和接单状态的操作人
                                                                                                                                                                                                  
                }
            }
            else
            {
                if (flag == 1)
                {
                    str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
                       + " and "
                           + "F_WoState in(" + (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.abreback + ") and F_NextDept =" + deptid + " "//办理中和接单状态的操作人
                            + " and isnull(F_IsUsed,'0')='0' and F_Type in(1,3)";
                }
                else if (flag == 2)
                {
                    str = "select F_WoID from T_Wo_WorkOrderItem_New where F_ItemType=" + (int)EnumItemType.deal
                      + " and "
                          + "F_WoState in(" + (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.abreback + ") and F_NextDept =" + deptid + " "//办理中和接单状态的操作人
                           + " and isnull(F_IsUsed,'0')='0' and F_Type in(2,3)";
                }
            }

            return str;
        }
        /// <summary>
        /// 获取工单数量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkCount(string OpenId)
        {

              if (string .IsNullOrEmpty (OpenId) )
                return Success   ("你的账号已在别处登录，你确定要再次登录吗？");
              var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
              if (ua == null)
                {
                    return Success("你的账号已在别处登录，你确定要再次登录吗？");
                }
                DataTable dt = new DataTable();
                #region 筛选条件
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                string uwhere = " ";
                string sql = "";
                if (!Refresh() || !Refresh2())
                {
                    return Error("查询失败");
                }
                int  YCD = 0, DJD = 0, DCL = 0, DSP = 0, YCL = 0, GCDBL = 0, YBL = 0, CQGD = 0,  TD = 0,YFP=0, ZHCX = 0, CSGD=0;
                for (int i = 0; i <= 9; i++)
                {
               
                switch (i)
                    {
                    case 0://待接单的
                        sql = "";
                        sql += $"  F_IsDelete=0";
                        string strsql = GetDeptWorkOrderID(ua.F_DeptId, ua.F_UserCode, ua.F_Flag);
                        if (strsql != "")
                        {
                            if (ua.F_Flag == 1)
                            {
                                sql += $" and F_State in(" + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.assign + ")  ";
                            }
                            else if (ua.F_Flag == 2)
                            {
                                sql += $" and F_State2 in(" + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.assign + ") ";
                            }
                            sql += " and T_Wo_WorkOrder.F_ID in ( " + strsql + ")";

                        }
                        else
                        {
                            DJD = 0;
                            break;
                        }
                        DJD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//接单
                        break;
                    case 1://待完成的(待处理)
                        sql = "";
                        sql += $"  F_IsDelete=0";
                        string dealstr = GetDWCWorkOrderID(ua.F_UserCode, ua.F_DeptId, ua.F_Flag);
                        if (!string.IsNullOrEmpty(dealstr))
                        {
                            if (ua.F_Flag == 1)
                            {
                                sql += " and (F_State in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.revoke + ")";
                            }
                            else if (ua.F_Flag == 2)
                            {
                                sql += " and (F_State2 in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.revoke + ")";
                            }
                            sql += "  and T_Wo_WorkOrder.F_ID in ( " + dealstr + ") ";
                            if (!string.IsNullOrEmpty(GetRevokeWo(ua.F_UserCode)))
                            {
                                if (ua.F_Flag == 1)
                                {
                                    sql += " or (F_State=" + (int)EnumWorkOrderState.assign + " and T_Wo_WorkOrder.F_ID in (" + GetRevokeWo(ua.F_UserCode) + ")))";
                                }
                                else if (ua.F_Flag == 2)
                                {
                                    sql += " or (F_State2=" + (int)EnumWorkOrderState.assign + " and T_Wo_WorkOrder.F_ID in (" + GetRevokeWo(ua.F_UserCode) + ")))";
                                }
                            }
                            else
                            {
                                sql += $")";
                            }

                        }
                        else
                        {
                            DCL = 0;
                            break;
                        }
                        DCL = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//已接单

                        break;
                    case 2://已完成的
                        sql = "";
                        sql += $"  F_IsDelete=0";
                        if (ua.F_Flag == 1)
                        {
                            sql += " and F_State in(10,11)";
                        }
                        else if (ua.F_Flag == 2)
                        {
                            sql += " and F_State2 in(10,11)";
                        }
                        if (GetDeptUserCode(ua.F_DeptId) != "")
                        {
                            sql += "  and F_DealBy in(" + GetDeptUserCode(ua.F_DeptId) + ") ";
                        }
                        //   sql += " and F_State in(10,11) and F_DealBy = '" + ua.F_UserCode + "' ";
                        YCL = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//已完成的

                        break;

                    case 3://待审批
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "GC")
                            {
                                if (GetHApproval(ua.F_UserCode) != "")
                                {
                                    sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetHApproval(ua.F_UserCode) + ") "; ;
                                }
                            }
                            else
                            {

                                GCDBL = 0;
                                break; ;
                            }
                            GCDBL = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//高层待审批
                            break;
                        case 4://已审批
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "GC")
                            {
                                if (GetApprovedOrderID(ua.F_UserCode) != "")
                                {
                                    sql += $"  and F_ID in ( " + GetApprovedOrderID(ua.F_UserCode) + ") "; ;
                                }
                                else
                                {
                                    YBL = 0;
                                    break; ;
                                }
                            }
                            else
                            {
                                YBL = 0;
                                break; ;
                            }
                            YBL = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//已审批
                            break;
                        case 5://待审批
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL")
                            {
                                if (GetApprovalOrderID(ua, OpenId, ro.F_RoleCode) != "")
                                {
                                    sql += " and  T_Wo_WorkOrder.F_ID in ( " + GetApprovalOrderID(ua, OpenId, ro.F_RoleCode) + ") ";
                                }
                                else
                                {
                                    DSP = 0;
                                    break; ;
                                }
                            }
                            else
                            {
                                DSP = 0;
                                break; ;
                            }

                            DSP = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//待审批
                            break;
                        case 6:
                            sql = "";
                            sql += $"  F_IsDelete=0";
                            sql += $" and F_CreateBy  ='" + ua.F_UserCode + "'";
                            YCD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//业务员已创单
                            break;

                        case 7://超期
                        sql = "";
                        sql += $"  F_IsDelete=0";
                        //sql += $" and (F_IsOver=1 or F_IsOver=2)";
                        //sql += $" and F_State !=" + 11;
                        if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                        {
                            sql += $" and((F_IsOver in(1,3) and F_State !=11) or ( F_IsOver in (2,3) and  F_State2!=11))";
                        }
                        else if (ua.F_Flag == 1)
                        {
                            sql += $" and F_IsOver in (1,3)";
                            sql += $" and F_State !=" + 11;
                        }
                        else if (ua.F_Flag == 2)
                        {
                            sql += $" and  F_IsOver in (2,3)";
                            sql += $" and F_State2 !=" + 11;
                        }
                        #region 退换货的工单按未超期处理 20220302
                        sql += $" and  F_ID not in (select F_ID from T_Wo_WorkOrder where F_SC_PreliminaryOpinion='退换货')";
                        #endregion
                        if (ro.F_RoleCode == "YWY" || ro.F_RoleCode == "BLRY")
                        {
                            sql += $" and F_DealBy like '%" + ua.F_UserCode.Trim() + "%'";
                        }
                        else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "ZG")
                        {
                            string detpid = "" + ua.F_DeptId;
                            var deparmentlist = new List<Model.T_Sys_Department>();
                            Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                            if (dModel != null)
                            {
                                if (dModel.F_Layer == 1)
                                {
                                    deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                    if (deparmentlist.Count > 0)
                                    {
                                        foreach (var it in deparmentlist)
                                        {
                                            if (detpid != "")
                                            {
                                                detpid += "," + it.F_DeptId;
                                            }
                                            else
                                            {
                                                detpid = "" + it.F_DeptId; ;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    detpid = ua.F_DeptId.ToString();
                                }
                                if (GetDeptWorkOrderID(detpid) != "")
                                {
                                    sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") "; ;
                                }
                                else
                                {

                                    CQGD = 0;
                                    break; ;
                                }

                            }
                            else
                            {
                                CQGD = 0;
                                break; ;
                            }
                        }

                        else if (ro.F_RoleCode == "QTJS")
                        {
                            CQGD = 0;
                            break; ;
                        }
                        CQGD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//超期
                        break;
                    case 8://综合查询
                        sql = "";
                        sql += $"  F_IsDelete=0";
                        if (ro.F_RoleCode == "QTJS" || ro.F_RoleCode == "YWY")
                            sql += $" and F_CreateBy like '%" + ua.F_UserCode.Trim() + "%'";
                        else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "BLRY" || ro.F_RoleCode == "ZG" || ro.F_RoleCode == "GC")
                        {

                            string markdepts = "37,57,74,88,268,422,339";
                            string qualdepts = "12,36,295";
                            string detpid = "" + ua.F_DeptId;
                            var deparmentlist = new List<Model.T_Sys_Department>();
                            Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                            if (dModel != null)
                            {

                                #region  工单查询- 综合查询模块，权限增加，市场部和质管部可以看到事业部所有的工单，包含未经办的  20220519
                                if (markdepts.Contains(ua.F_DeptId.ToString()) || qualdepts.Contains(ua.F_DeptId.ToString()))
                                {
                                    sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptAllWorkOrderID(ua.F_DeptId) + ") ";
                                }
                                #endregion
                                #region 高层可以看到本事业部的所有工单
                                else if (ro.F_RoleCode == "GC")
                                {
                                    string strsq = judgmentDept(ua.F_DeptId);
                                    if (!string.IsNullOrEmpty(strsq))
                                    {
                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + strsq + ") ";
                                    }
                                }
                                #endregion
                                else
                                {
                                    if (dModel.F_Layer == 1)
                                    {
                                        deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                                        if (deparmentlist.Count > 0)
                                        {
                                            foreach (var it in deparmentlist)
                                            {
                                                if (detpid != "")
                                                {
                                                    detpid += "," + it.F_DeptId;
                                                }
                                                else
                                                {
                                                    detpid = "" + it.F_DeptId;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        detpid = ua.F_DeptId.ToString();
                                    }
                                    #region 人员更换部门后，仍然需要查看、处理自己原部门的历史工单 20220307
                                    //if (!string.IsNullOrEmpty(ua.F_Origdepts))
                                    //{
                                    //    detpid += "," + ua.F_Origdepts;
                                    //}
                                    #endregion

                                    if (GetDeptWorkOrderID(detpid) != "")
                                    {

                                        sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid) + ") ";
                                    }
                                    else
                                    {

                                        ZHCX = 0;
                                        break;
                                    }
                                }


                            }
                            else
                            {
                                ZHCX = 0;
                                break;
                            }
                        }
                        ZHCX = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;//综合查询
                        break;
                    case 9: //抄送工单列表
                        sql = "";
                        sql += $"  F_IsDelete=0";
                        sql += $" and T_Wo_WorkOrder.F_ID in (select F_WorkOrderID from T_Wo_WorkCopy where F_SendCopyUser like '%{ua.F_UserCode}%'"
                            +$" or (F_Flag=1 and F_SendCopyDepts={ua.F_DeptId} )) "; 
                        CSGD = new BLL.T_Wo_WorkOrder().GetModelList(sql).Count;
                        break; 
                }
                }

                #endregion

                var obj = new
                {
                    state = "success",
                    message = "成功",
                    DJD = DJD,//待接单
                    DCL = DCL,//已接单（待处理）
                    YCL = YCL,//已完成的
                    GCDBL = GCDBL,//高层待审批
                    YBL = YBL,//已审批
                    DSP = DSP,//待审批
                    YCD = YCD,//业务员已创单
                    TD = TD,//退单
                    CQGD = CQGD,//超期
                    YFP= YFP,
                    ZHCX= ZHCX , //综合查询
                    CSGD= CSGD
                };
                return Content(obj.ToJson()); ;
           

        }
        /// <summary>
        /// 注解
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="cont"></param>
        /// <returns></returns>
        public ActionResult Annotation(string OpenId, int orderid, string cont, int flag = 0)
        {
            //注解给超级管理员开通编辑删除修改权限 20220221
            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = woBLL .GetModel(orderid);
                    Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                    //验证信息 
                    if (model != null)
                    {
                        if (flag == 1)
                        {
                            if (ro.F_RoleCode == "XTGLY")
                            {
                                model.F_Annotation = cont + "-" + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(model.F_Annotation))
                                {
                                    model.F_Annotation = cont + "-" + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                }
                                else
                                {
                                    model.F_Annotation = model.F_Annotation + "\n" + cont + "-" + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ; ;
                                }
                            }


                        }
                        else
                        {
                            if (string.IsNullOrEmpty(model.F_Annotation))
                            {
                                model.F_Annotation = cont + "-" + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            }
                            else
                            {
                                model.F_Annotation = model.F_Annotation + "\n" + cont + "-" + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ;
                            }
                        }
                        var res = woBLL.Update(model);
                        if (res)
                        #region 增加注解通知市场部功能  20220216
                        {
                            string touser = "";
                            string strwhere = "";
                            string contens = "";
                            strwhere = $" F_DeptId in (select top 1 F_NextDept  from T_Wo_WorkOrderItem_New where F_WoID={model.F_ID} and F_NextDept in(37,57,74,88,268,295,339) order by F_CreateTime desc)";
                            var deptmodel = departmentBLL.GetModelList(strwhere).FirstOrDefault();
                            if (deptmodel != null)
                            {
                                var userlist = userAccountBLL.GetModelList("F_DeptId=" + deptmodel.F_DeptId);
                                if (userlist.Count > 0)
                                {
                                    if (flag == 1)
                                       
                                    contens = $" 修改注解,工单编号" + model.F_WorkOrderCode;
                                    else
                                        contens =$" 附加注解,工单编号" + model.F_WorkOrderCode; 
                                    foreach (var item in userlist)
                                    {
                                        touser = item.F_UserCode; ;
                                        Model.T_Msg_List msg = new Model.T_Msg_List();
                                        msg.Type = (int)Model.MSGType.Annotation;
                                        msg.ToUser = touser;
                                        msg.ToID = (int)model.F_ID;
                                        msg.Detail = ua.F_UserName + contens;
                                        msg.State = 0;
                                        msg.IsDel = 0;
                                        msg.CreateDate = DateTime.Now;
                                        msg.ReadDate = DateTime.Now;
                                        new BLL.T_Msg_List().Add(msg);
                                        //sendsysmsg(model, ua, touser, (int)model.F_ID, "增加注解");
                                    }
                                }
                            }
                            return Success("注解成功");
                        }
                        #endregion
                        else
                            return Error("注解失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }

        /// <summary>
        /// 抄送工单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="content"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        [WechatActionFilter]
        public ActionResult SendCopy(string OpenId, int id = 0, string content = "", string users = "")
        {

            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                if (id <= 0)
                    return Error("请选择工单");
                var model = woBLL.GetModel(id);
                if (string.IsNullOrEmpty(users))
                    return Error("请选择抄送部门");
                JavaScriptSerializer Serializer = new JavaScriptSerializer();   //实例化⼀个能够序列化数据的类
                List<CopyMessage> list = Serializer.Deserialize<List<CopyMessage>>(users);
                if (model != null)
                {
                    string userstr = "";
                    string deptmessage = "", deptname1 = "";
                    var dept1 = new BLL.T_Sys_Department().GetModel(ua.F_DeptId);
                    if (dept1 != null)
                        deptname1 = dept1.F_DeptName;
                    if (list != null && list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            string username = string.Empty;
                            var deptmodel = new BLL.T_Sys_Department().GetModel(Convert.ToInt32(item.deptid));
                            if (deptmodel == null)
                                return Error("抄送部门不存在！");
                            var clus = item.ucodelist;
                            Model.T_Wo_WorkCopy t_Wo_WorkCopy = new Model.T_Wo_WorkCopy();
                            if (clus.Count > 0)
                            {
                                t_Wo_WorkCopy.F_Flag = 0;
                                t_Wo_WorkCopy.F_SendCopyUser = string.Join(",", clus.ToArray());
                            }
                            else
                            {
                                t_Wo_WorkCopy.F_Flag = 1;
                                t_Wo_WorkCopy.F_SendCopyUser = "";
                            }
                            t_Wo_WorkCopy.F_WorkOrderID = model.F_ID;
                            t_Wo_WorkCopy.F_CreateOn = DateTime.Now;
                            t_Wo_WorkCopy.F_Content = content;
                            t_Wo_WorkCopy.F_CreateBy = ua.F_UserId.ToString();
                            t_Wo_WorkCopy.F_SendCopyOn = DateTime.Now;
                            t_Wo_WorkCopy.F_State = model.F_State;
                            t_Wo_WorkCopy.F_SendCopyDepts = Convert.ToInt32(item.deptid);
                            if (new BLL.T_Wo_WorkCopy().Add(t_Wo_WorkCopy) > 0)
                            {
                                #region 发送短信
                                int sms = 0;
                                if (clus.Count > 0)
                                {
                                    foreach (var noticlus in clus)
                                    {
                                        var usermodel = new BLL.T_Sys_UserAccount().GetModel(noticlus);
                                        username = string.IsNullOrEmpty(username) ? usermodel.F_UserName : username + "，" + usermodel.F_UserName;
                                        string[] mag = { };
                                        if (!string.IsNullOrEmpty(usermodel.F_Mobile))
                                        {
                                            //SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, noticlus.F_Mobile.Trim());
                                            //bool n = new SMSController().AddSmS(noticlus.F_Mobile.Trim(), "抄送工单", ua.F_UserId);
                                        }
                                    }
                                }
                                else
                                {
                                    var usermodel = new BLL.T_Sys_UserAccount().GetModelList($"F_DeptId={Convert.ToInt32(item.deptid)}");
                                    if (usermodel.Count > 0)
                                    {
                                        foreach (var user in usermodel)
                                        {
                                            username = string.IsNullOrEmpty(username) ? user.F_UserName : username + "，" + user.F_UserName;
                                            string[] mag = { };
                                            if (!string.IsNullOrEmpty(user.F_Mobile))
                                            {
                                                //SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, noticlus.F_Mobile.Trim());
                                                //bool n = new SMSController().AddSmS(noticlus.F_Mobile.Trim(), "抄送工单", ua.F_UserId);
                                            }
                                        }
                                    }
                                }
                                #endregion
                            }
                            deptmessage = string.IsNullOrEmpty(deptmessage) ? deptmodel.F_DeptName + "-" + username : deptmessage + "；" + deptmodel.F_DeptName + "-" + username;
                        }
                        string message = "抄送工单给" + deptmessage;
                        if (!string.IsNullOrEmpty(content))
                            message += "，抄送内容：" + content;
                        AddLog(model.F_ID, model.F_State.Value, deptname1 + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + message, (int)EnumItemType.Copy, (int)EnumItemOpt.Copy, "", 0, ua, 0, 0, "", 1);
                        return Success("抄送成功");
                    }
                }
                else
                    return Error("工单不存在");

            }
            return Error("无操作权限！");
        }

        /// <summary>
        /// 审核工单
        /// </summary>
        public ActionResult GetApproval(string OpenId, long orderid, string AuditCont, int IsAudit = 0, int AuditState = 0, float overtime = 0, int sms = 0)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
                    if (model != null)
                    {
                        var itemlast = itembll.GetModelList("   F_WoID='" + model.F_ID + "' order by F_ID desc").FirstOrDefault();
                        if (itemlast!=null )
                         sms = (int)itemlast.F_IsSMS;
                        var res = Approval(OpenId, orderid, AuditCont, ua, model, overtime, sms, IsAudit, AuditState);
                        if (res)
                            return Success("审核成功");
                        else
                            return Error("审核失败");
                    }
                    else
                        return Error("工单不存在");
                }
            }
            return Error("OpenId不能为空");
        }
        /// <summary>
        /// 填写超时原因
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [WechatActionFilter]
        public ActionResult Reasontimeout(string OpenId, long orderid, string cont)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        model.F_Reasontimeout = cont;
                        bool n = woBLL.Update(model);
                        if (n)
                            return Success("填写成功");
                        else
                            return Error("填写失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 审核工单
        /// </summary>
        [WechatActionFilter]
        public bool Approval(string OpenId, long orderid, string AuditCont, Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, float overtime = 0, int sms = -1, int IsAudit = 0, int AuditState = 0)
        {
            bool res = true;
            string touser = ""; string tousername = "";
            string opt = "审核";
            #region 获取接收人
            string deptname = "";
            string deptmodelsname = "";
            int wostate = 0;
            var toussers = "";
            #region 上报
            if (IsAudit != 0)
            {
                if (GetUser(OpenId) != null)
                {
                    var user = GetUser(OpenId);
                    var deptmodel = departmentBLL.GetModel(user.F_DeptId);
                    var deptmodels = departmentBLL.GetModel(nowUser.F_DeptId);
                    if (deptmodel != null)
                    {
                        deptname = deptmodel.F_DeptName + "-";
                    }
                    if (deptmodels != null)
                    {
                        deptmodelsname = deptmodels.F_DeptName + "-";
                    }
                    var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.audit + " and  F_CreateUser!=" + user.F_UserCode + " and  F_OptType=" + (int)EnumItemOpt.audit + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
                    if (itemlast != null)
                    {
                        toussers = itemlast.F_CreateUser;
                        if (sms == -1)
                        {
                            sms = (int)itemlast.F_IsSMS;
                        }
                    }
                    else
                    {
                        if (sms == -1)
                        {
                            sms = 0;
                        }
                    }
                    wostate = 16;
                    if (AuditState == 0)
                    {
                        opt = "同意上报";
                        var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：同意上报" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.reaudit, user.F_UserCode, user.F_DeptId, nowUser, overtime, sms);
                        var uaid = AddLog(model.F_ID, model.F_State.Value, deptname + user.F_UserName + "(" + user.F_WorkNumber + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, user.F_UserCode, user.F_DeptId, nowUser, overtime, sms);
                        if (userid <= 0 || uaid <= 0)
                            res = false;
                        else
                        {
                            if (sms ==1&& !string .IsNullOrEmpty(user .F_Mobile ))
                            {
                                SendSms(model.F_Type, user.F_Mobile, nowUser.F_UserId);
                            }
                        }

                    }
                    else if (AuditState == 1)
                    {
                        opt = "驳回修订";
                        var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：驳回修订" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.reback, toussers, 0, nowUser, overtime, sms);
                        if (userid <= 0)
                            res = false;
                    }
                    else
                    {
                        opt = "强制结案";
                        wostate = 11;
                        var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：强制结案" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.visit, "", 0, nowUser, overtime, sms);
                        if (userid <= 0)
                            res = false;
                    }
                }
                else
                {
                    Model.T_Sys_RoleInfo ro = rolebll.GetModel(nowUser.F_RoleId);
                    if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL")
                    {
                        var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.audit + " and  F_OptType=" + (int)EnumItemOpt.audit + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
                        if (itemlast != null)
                        {
                            toussers = itemlast.F_CreateUser;
                            if (sms == -1)
                            {
                                sms = (int)itemlast.F_IsSMS;
                            }
                        }
                        else
                        {
                            if (sms == -1)
                            {
                                sms = 0;
                            }
                        }


                        if (AuditState == 0)
                        {
                            opt = "同意上报";
                            var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：同意上报" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.reaudit, "", 0, nowUser, overtime, sms);
                            res = GetDaQucirCulation(AuditCont, nowUser, DateTime.Now.ToString(), model.F_ID, true);
                            if (userid <= 0 || !res)
                                res = false;
                            wostate = 1;
                        }
                        else if (AuditState == 1)
                        {
                            opt = "驳回修订";
                            var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：驳回修订" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.reback, toussers, 0, nowUser, overtime, sms);
                            if (userid <= 0)
                                res = false;
                            
                            wostate = 16;
                        }
                        else
                        {
                            opt = "强制结案";
                            var userid = AddLog(model.F_ID, model.F_State.Value, deptmodelsname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "工单审批：强制结案" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.visit, "", 0, nowUser, overtime, sms);
                            if (userid <= 0)
                                res = false;
                            wostate = 11;
                        }

                    }
                    else
                    {
                        res = false;
                    }
                }
            }

            #endregion
            #endregion
            if (res)
            {
                model.F_State = wostate;
                model.F_State2 = wostate;
                //处理内容
                if (!string.IsNullOrEmpty(AuditCont))
                    model.F_AuditCont += AuditCont + "；";
                model.F_IsAudit = IsAudit;
                model.F_AuditState = AuditState;
                model.F_AuditBy = nowUser.F_UserCode;
                model.F_AuditOn = DateTime.Now;
                woBLL.Update(model);
                if (nowUser.F_UserCode != model.F_CreateBy)
                {
                    sendsysmsg(model, nowUser, model.F_CreateBy, (int)model.F_ID, opt);//
                }

                #region 向下一级操作人员推送消息
                if (!string.IsNullOrWhiteSpace(touser))
                {
                    sendsysmsg(model, nowUser, touser, (int)model.F_ID, opt);//
                }
                #endregion 向下一级操作人员推送消息
            }
            else
                return false;
            return true;
        }
        public bool SendSms(string type,string F_Mobile,int userid)
        {
             string smscont = "";
            if (type == "1")
            {
                smscont = "咨询";
            }
            else if (type == "2")
            {
                smscont = "投诉";
            }
            else if (type == "3")
            {
                smscont = "抽检";
            }
            else if (type == "5")
            {
              smscont  = "业务协办";
            }
            else
            {
                smscont = "建议";
            }
            string[] mag = { smscont };
          string smsmsg = "您好，您有一条新的" + smscont + "工单，请及时接单处理！";
           SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, F_Mobile.Trim());
            bool n = new SMSController().AddSmS(F_Mobile.Trim(), smsmsg, userid);
            return n;
            
        }
        /// <summary>
        /// 大区经理未审批流转市场管理科
        /// </summary>
        /// <param name="ua"></param>
        /// <param name="time"></param>
        /// <param name="id"></param>
        public bool GetDaQucirCulation(string AuditCont, Model.T_Sys_UserAccount ua, string time, long id, bool istrue)
        {
            DateTime times = DateTime.Parse(time).AddHours(24);
            Model.T_Wo_WorkOrder model = woBLL.GetModel(id);
            List<Model.T_Wo_WorkOrder> modeLlist = new List<Model.T_Wo_WorkOrder>();
            modeLlist.Add(model);
            List<WorkOrderNewInput> Input = modeltooip(modeLlist, ua);
            string cont = "";
            int dapt = 0, nextda = 0; string opt = ""; int nextda2 = 0; string opt2 = ""; string cont2 = "";
            var itemlast = itembll.GetModelList("   F_WoID='" + model.F_ID + "' order by F_ID desc").FirstOrDefault();
            int sms = (int)itemlast.F_IsSMS;
            var deptmodel1 = departmentBLL.GetModel(ua.F_DeptId);
            string deptname = "";
            if (deptmodel1 != null)
            {
                dapt = deptmodel1.F_ParentId;
                deptname = deptmodel1.F_DeptName;
            }
            int isbl = 0;
            Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
            //if (dapt != 0)
            //{
            if (CirculMarket(ua.F_DeptId, 11))
            {
                isbl = 1;
                nextda = 37;
                opt = "流转市场管理科";
                nextda2 = 36;
                opt2 = "流转质量管理科";
            }
            else if (CirculMarket(ua.F_DeptId, 14))
            {
                isbl = 1;
                nextda = 57;
                opt = "流转营销管理处";
            }
            else if (CirculMarket(ua.F_DeptId, 15))
            {
                isbl = 1;
                nextda = 74;
                opt = "流转策划推广";
            }
            else if (CirculMarket(ua.F_DeptId, 16))
            {
                isbl = 1;
                nextda = 88;
                opt = "流转销售部";
            }
            else if (CirculMarket(ua.F_DeptId, 18))
            {
                nextda = 268;
                opt = "流转车用尿素";

            }
            else if (CirculMarket(ua.F_DeptId, 20))
            {
                nextda = 295;
                opt = "流转新乡黑科质检";
            }
            else if (CirculMarket(ua.F_DeptId, 332))
            {
                nextda = 339;
                opt = "流转营销管理处";

            }
            else if (ua.F_DeptId == 17 || ua.F_DeptId == 19 || ua.F_DeptId == 20 || ua.F_DeptId == 21)
            {
                isbl = 1;
                nextda = ua.F_DeptId;
                opt = "流转" + deptname;
            }

            //}
            if (istrue)
            {
                if (ro.F_RoleCode == "DQJL")
                {
                    cont = "大区经理已审批:" + AuditCont + "," + opt;
                    if (!string.IsNullOrEmpty(opt2))
                    {
                        cont2 = "大区经理已审批: " + AuditCont + "," + opt2;
                    }
                }
                else
                {
                    cont = "分公司经理已审批:" + AuditCont + "," + opt;
                    if (!string.IsNullOrEmpty(opt2))
                    {
                        cont2 = "分公司经理已审批: " + AuditCont + "," + opt2;
                    }
                }
            }
            else
            {
                if (ro.F_RoleCode == "DQJL")
                {
                    cont = "大区经理未审批" + opt;
                    if (!string.IsNullOrEmpty(opt2))
                    {
                        cont2 = "大区经理未审批" + opt2;
                    }
                }
                else
                {
                    cont = "分公司经理未审批" + opt;
                    if (!string.IsNullOrEmpty(opt2))
                    {
                        cont2 = "分公司经理未审批" + opt2;
                    }
                }
            }
            if (nextda != 0 || nextda2 != 0)
            {
                var res = AssignWO(ua, model, Input[0], cont, "", nextda, 0, model.F_limit, sms, 0, 0, 0, time.ToString(), isbl);
                if (nextda2 != 0)
                {
                    var res2 = AssignWO(ua, model, Input[0], cont2, "", nextda2, 0, model.F_limit, sms, 0, 0, 0, time.ToString(), isbl,2);
                }
                return true;
            }
            else return false;
        }

        /// <summary>
        /// 判断市场管理科
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="pdeptid"></param>
        /// <returns></returns>
        public bool CirculMarket(int deptid, int pdeptid)
        {
            string sql = " F_State=1 ";
            string dptcode = departmentBLL.GetModel(pdeptid).F_DeptCode;
            string arrsql = " select F_DeptCode from T_Sys_Department where F_DeptCode LIKE '" + dptcode + "%' ";
            sql += $" and F_DeptCode in ({arrsql}) and F_DeptId=" + deptid;
            var modellist = departmentBLL.GetModelList(sql);
            if (modellist.Count > 0)
                return true;
            else return false;
        }
        /// <summary>
        /// 查询工单详情
        /// </summary>
        [WechatActionFilter]
        public ActionResult GetCustomDetails(string OpenId, int id)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                string sqlstr = "";
                if (id <= 0)
                {
                    return Error("请输入正确的id");
                }
                DataTable FileUrl = new DataTable();
                var list = new List<Model.T_Wo_WorkOrder>();
                var model = woBLL.GetModel(id);
                if (model != null)
                    list.Add(model);
                var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                if (!string.IsNullOrEmpty(model.F_Files))
                {
                    FileUrl = GetFileData(model.F_Files, configfj.F_ParamValue);
                }
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                var itemlasts = itembll.GetModelList("  F_WoID=" + id + " and  F_Type=" + ua.F_Flag + " ");
                //var itemlasts = itembll.GetModelList("  F_WoID=" + +id + " ");
                if (list.Count > 0)
                {
                    List<WorkOrderNewInput> Input = modeltooip(list, ua);
                    if (Input != null)
                    {
                        var obj = new
                        {
                            state = "success",
                            message = "成功",
                            rows = Input,
                            FileUrl,
                            total = itemlasts,
                        };
                       
                        return Content(obj.ToJson());
                    }
                    else
                    {
                        return Error("没有查询到此工单");
                    }
                }
                else
                    return Error("没有查询到此工单");

            }
            else
            {
                return Error("无操作权限！");
            }
        }
        /// <summary>
        /// 查询工单详情
        /// </summary>
        [WechatActionFilter]
        public ActionResult GetDetails(string OpenId, int id,int flag=1)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                if (id <= 0)
                {
                    return Error("请输入正确的id");
                }
                DataTable FileUrl = new DataTable();
                var list = new List<Model.T_Wo_WorkOrder>();
                var model = woBLL.GetModel(id);
                if (model != null)
                {
                    if (model.F_SC_PreliminaryOpinion == "退换货")
                    {
                        List<T_Wo_MaterialItems> materlist = new BLL.T_Wo_MaterialItems().GetModelList($" F_WoID={model.F_ID}");
                        if (materlist != null)
                        {
                            model.MaterialItems = materlist;
                        }
                    }
                    list.Add(model);
                }
                var itemlasts = itembll.GetModelList("  F_WoID=" + id + " ");
                ; var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                if (!string.IsNullOrEmpty(model.F_Files))
                {
                    FileUrl = GetFileData(model.F_Files, configfj.F_ParamValue);
                }
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                if (model.F_Source != "3")
                {
                    if (ua == null)
                    {
                        return Success("你的账号已在别处登录，你确定要再次登录吗？");
                    }
                }
                if (list.Count > 0)
                {
                    List<WorkOrderNewInput> Input = modeltooip(list, ua);
                    if (Input != null)
                    {
                        var obj = new
                        {
                            state = "success",
                            message = "成功",
                            rows = Input,
                            FileUrl,
                            total = itemlasts,
                        };

                        return Content(obj.ToJson());
                    }
                    else
                    {
                        return Error("没有查询到此工单");
                    }
                }
                else
                    return Error("没有查询到此工单");

            }
            else
            {
                return Error("无操作权限！");
            }
        }
        public string GetID(string str, long id)
        {
            if (str != "")
            {
                str += "," + id;
            }
            else
            {
                str += id;
            }
            return str;
        }
        public string GetDeptment(Model.T_Sys_UserAccount ua)
        {
            string detpid = "" + ua.F_DeptId;
            Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
            var deparmentlist = new List<Model.T_Sys_Department>();
            if (dModel != null)
            {
                if (dModel.F_Layer == 1)
                {
                    deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                    if (deparmentlist.Count > 0)
                    {
                        foreach (var it in deparmentlist)
                        {
                            if (detpid != "")
                            {
                                detpid += "," + it.F_DeptId;
                            }
                            else
                            {
                                detpid = "" + it.F_DeptId;
                            }
                        }
                    }
                }
                else
                {
                    detpid = ua.F_DeptId.ToString();
                }
            }
            return detpid;
        }

        /// <summary>
        /// 获取待审批的工单
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetApprovalOrderID(Model.T_Sys_UserAccount ua, string OpenId, string F_RoleCode)
        {

            string str = string.Empty;
            #region 查询自己名下未审批的工单列表
            var itemlast = itembll.GetModelList(" isnull(F_IsUsed,'0')='0' and F_OptType in(" + (int)EnumItemOpt.audit + ")" + " and "
                    + "F_WoState in(" + (int)EnumWorkOrderState.audit + ") and F_NextUser='" + ua.F_UserCode + "' "
                + "" + " ");

            foreach (var it in itemlast)
            {
                float hours = (DateTime.Now - DateTime.Parse(it.F_CreateTime.ToString())).Hours;
                int overtime = 0;
                if (!string .IsNullOrEmpty (it.F_LimitTime))
                {
                 overtime = int.Parse(it.F_LimitTime);
                }
                int sms = int.Parse (it.F_IsSMS.ToString ());
                if (F_RoleCode == "DQJL" || F_RoleCode == "FGSJL")
                {
                    if (hours >= 24)
                    {
                        GetDaQucirCulation("", ua, it.F_CreateTime.ToString(), it.F_WoID, false);
                    }
                    else
                    {
                        str = GetID(str, it.F_WoID);
                    }

                }
                else
                {
                    //var user = GetUser(OpenId);
                    //string deptname = "";
                    //string deptmodelsname = "";
                    //var deptmodel = departmentBLL.GetModel(user.F_DeptId);
                    //var deptmodels = departmentBLL.GetModel(ua.F_DeptId);
                    //if (deptmodel != null)
                    //{
                    //    deptname = deptmodel.F_DeptName + "-";
                    //}
                    //if (deptmodels != null)
                    //{
                    //    deptmodelsname = deptmodels.F_DeptName + "-";
                    //}
                    if (hours >= 24)
                    {
                        var user = GetUser(OpenId);
                        string deptname = "";
                        string deptmodelsname = "";
                        string namestr = "";
                        Model.T_Sys_RoleInfo ro = rolebll.GetModel(user.F_RoleId);
                        if (ro.F_RoleCode == "DQJL")
                        {
                            namestr = "大区经理";
                        }
                        else
                        {
                            namestr = "分公司经理";
                        }
                        var deptmodel = departmentBLL.GetModel(user.F_DeptId);
                        var deptmodels = departmentBLL.GetModel(ua.F_DeptId);
                        if (deptmodel != null)
                        {
                            deptname = deptmodel.F_DeptName + "-";
                        }
                        if (deptmodels != null)
                        {
                            deptmodelsname = deptmodels.F_DeptName + "-";
                        }
                        DateTime time = DateTime.Parse(it.F_CreateTime.ToString()).AddHours(24);
                        Model.T_Wo_WorkOrder model = woBLL.GetModel(it.F_WoID);
                        AddLog(model.F_ID, model.F_State.Value, deptmodelsname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "未审批流转"+ namestr + "", (int)EnumItemType.audit, (int)EnumItemOpt.audit, user.F_UserCode, user.F_DeptId, ua, overtime, sms);
                        AddLog(model.F_ID, model.F_State.Value, deptname + user.F_UserName + "(" + user.F_WorkNumber + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, user.F_UserCode, user.F_DeptId, user, overtime, sms);
                    }
                    else if (hours >= 48)
                    {
                        var user = GetUser(OpenId);
                        GetDaQucirCulation("", user, it.F_CreateTime.ToString(), it.F_WoID, false);
                    }
                    else
                    {
                        str = GetID(str, it.F_WoID);
                    }
                }
            }
            #endregion
            if (F_RoleCode == "DQJL")
            {
                if (!string.IsNullOrEmpty(GetDeptment(ua)))
                {
                    var itemlasts = itembll.GetModelList(" isnull(F_IsUsed,'0')='0' and F_OptType in(" + (int)EnumItemOpt.audit + ")" + " and "
                                      + "F_WoState in(" + (int)EnumWorkOrderState.audit + ") and F_NextUser in ( " + GetDeptment(ua) + ") ");
                    foreach (var it in itemlasts)
                    {
                        int overtime = 0;
                        if (!string.IsNullOrEmpty(it.F_LimitTime))
                        {
                            overtime = int.Parse(it.F_LimitTime);
                        }
                        int sms = int.Parse(it.F_IsSMS.ToString());
                        float hours = (DateTime.Now - DateTime.Parse(it.F_CreateTime.ToString())).Hours;
                        if (F_RoleCode == "DQJL")
                        {
                            if (hours >= 24)
                            {

                                Model.T_Sys_UserAccount user = userAccountBLL.GetModel(it.F_CreateUser);
                                DateTime time = DateTime.Parse(it.F_CreateTime.ToString()).AddHours(24);
                                Model.T_Wo_WorkOrder model = woBLL.GetModel(it.F_WoID);
                                string deptname = "";
                                string deptmodelsname = "";
                                var deptmodel = departmentBLL.GetModel(user.F_DeptId);
                                var deptmodels = departmentBLL.GetModel(ua.F_DeptId);
                                if (deptmodel != null)
                                {
                                    deptname = deptmodel.F_DeptName + "-";
                                }
                                if (deptmodels != null)
                                {
                                    deptmodelsname = deptmodels.F_DeptName + "-";
                                }
                                AddLog(model.F_ID, model.F_State.Value, deptmodelsname + user.F_UserName + "(" + user.F_WorkNumber + ")" + "未审批流转大区经理", (int)EnumItemType.audit, (int)EnumItemOpt.audit, ua.F_UserCode, ua.F_DeptId, user, overtime, sms);
                                AddLog(model.F_ID, model.F_State.Value, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, ua.F_UserCode, ua.F_DeptId, ua, overtime, sms );
                                if (hours < 48)
                                {
                                    str = GetID(str, it.F_WoID);
                                }
                                else
                                {
                                    GetDaQucirCulation("", ua, time.ToString(), it.F_WoID, false);
                                }
                            }
                        }
                    }
                }




            }
            return str;
        }
        /// <summary>
        /// 获取已审批的工单列表
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetApprovedOrderID(string user)
        {
            string str = string.Empty;

            str = "select F_WoID from T_Wo_WorkOrderItem_New where  F_OptType=" + (int)EnumItemOpt.reaudit
               + " and F_CreateUser=" + user + "  "//
                 ;
            return str;
        }
        /// <summary>
        /// 获取已审批的工单列表
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetApprovedOrderID()
        {
            string str = string.Empty;

            str = "select F_WoID from T_Wo_WorkOrderItem_New where  F_OptType=" + (int)EnumItemOpt.reaudit
                 //
                 ;
            return str;
        }
        /// <summary>
        /// 根据model返回CustomerBaseNewInput对象
        /// </summary>
        private List<WorkOrderNewInput> modeltooip(List<Model.T_Wo_WorkOrder> model1, Model.T_Sys_UserAccount ua)
        {
            if (model1 != null && model1.Count > 0)
            {
                List<WorkOrderNewInput> Input = new List<WorkOrderNewInput>(model1.Count);
                for (int i = 0; i < model1.Count; i++)
                {
                    WorkOrderNewInput model = new WorkOrderNewInput();
                    Model.T_Cus_CustomerBaseNew cuModel = new Model.T_Cus_CustomerBaseNew();
                    if (!string.IsNullOrEmpty(model1[i].F_CustomerID))
                    {
                        cuModel = customerBaseBLL.GetModel(model1[i].F_CustomerID.ToString());//通过客户编号获取客户资料
                    }
                    else
                    {
                        var sql = $" and  F_LegalPhone ='" + model1[i].F_CusPhone.Trim() + "'";
                        cuModel = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_IsDelete = 0 " + sql).FirstOrDefault();
                    }
                    if (cuModel != null)
                    {
                        if (!string.IsNullOrEmpty(cuModel.F_AreaID))
                        {
                            Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                            try
                            {
                                pdModel = departmentBLL.GetModel(int.Parse(cuModel.F_AreaID));//通过公司id获取部门
                            }
                            catch
                            {
                                pdModel = departmentBLL.GetModel(cuModel.F_AreaID);//通过公司id获取部门
                            }

                            if (pdModel != null)
                            {
                                model.F_AreaName = pdModel.F_DeptName;
                            }
                        }
                        if (!string.IsNullOrEmpty(cuModel.F_BranchID))
                        {
                            Model.T_Sys_Department pdModel1 = new Model.T_Sys_Department();
                            try
                            {
                                pdModel1 = departmentBLL.GetModel(int.Parse(cuModel.F_BranchID));//通过公司id获取部门
                            }
                            catch
                            {
                                pdModel1 = departmentBLL.GetModel(cuModel.F_BranchID);//通过公司id获取部门
                            }
                            if (pdModel1 != null)
                            {
                                model.F_BranchName = pdModel1.F_DeptName;
                            }
                        }
                        model.F_CompanyName = cuModel.F_CompanyName;//公司名称
                        model.F_CustomerID = cuModel.F_CustomerCode;//客户编码
                        model.F_Salesman = cuModel.F_Salesman;
                        model.F_SalesPhone = cuModel.F_SalesPhone;
                        model.F_Legal = cuModel.F_Legal;
                        model.F_LegalPhone = cuModel.F_LegalPhone;
                        model.F_AddressProvince = cuModel.F_AddressProvince;
                        model.F_AddressCity = cuModel.F_AddressCity;
                        model.F_AddressCountry = cuModel.F_AddressCountry;
                        model.F_AddressTownship = cuModel.F_AddressTownship;
                        model.F_AddressFull = cuModel.F_AddressFull;
                        model.F_Brands = cuModel.F_Brands;
                        model.F_Channel = cuModel.F_Channel;
                        model.F_IsRunXLX = cuModel.F_IsRunXLX;
                        model.F_AnnualSales = cuModel.F_AnnualSales;
                        model.F_Formula = cuModel.F_Formula;
                        model.F_RaiseCrops = cuModel.F_RaiseCrops;
                        model.F_PlantingArea = cuModel.F_PlantingArea;
                        model.F_FertilizerBrand = cuModel.F_FertilizerBrand;
                    }
                    if (valcode(model1[i].F_MaterialID.ToString(), 11))
                    {
                        model.F_MaterialID = model1[i].F_MaterialID;//验证物料编码为11位纯数字
                        Model.T_Wo_MaterialManage maModel = mmBLL.GetModel(model1[i].F_MaterialID.ToString());//通过物料编码获取物料信息
                        if (maModel != null)
                        {
                            model.F_MaterialName = maModel.F_MaterialName;
                            model.F_Model = maModel.F_Model;
                            model.F_Specs = maModel.F_Specs;
                            model.F_Level1 = maModel.F_Level1;
                            model.F_Level2 = maModel.F_Level2;
                            model.F_Level3 = maModel.F_Level3;
                            model.F_Brand = maModel.F_Brand;
                            model.F_MaterialEffect = maModel.F_MaterialEffect;
                            model.F_Pipeline = maModel.F_Pipeline;
                            model.F_Craft = maModel.F_Craft;
                        }
                    }
                    #region 基本字段
                    model.F_ID = model1[i].F_ID;//
                    model.F_WorkOrderCode = model1[i].F_WorkOrderCode;//工单编号
                    #region
                    if (!string.IsNullOrEmpty(model1[i].F_Source))
                    {
                        model.F_Source = int.Parse(model1[i].F_Source);//工单来源
                    }
                    if (model1[i].F_Source == "1")
                    {
                        model.F_SourceName = "电话";
                    }
                    else if (model1[i].F_Source == "2")
                    {
                        model.F_SourceName = "微信业务员";
                    }
                    else if (model1[i].F_Source == "3")
                    {
                        model.F_SourceName = "微信客户";
                    }
                    else
                    {
                        model.F_SourceName = "官网";
                    }

                    model.F_Type = int.Parse(model1[i].F_Type);//工单来源
                    if (model1[i].F_Type == "1")
                    {
                        model.F_TypeName = "咨询";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                    }
                    else if (model1[i].F_Type == "2")
                    {
                        model.F_TypeName = "投诉";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                    }
                    else if (model1[i].F_Type == "3")
                    {
                        model.F_TypeName = "抽检";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                    }
                    else if (model1[i].F_Type == "5")
                    {
                        model.F_TypeName = "业务协办";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                    }
                    else
                    {
                        model.F_TypeName = "建议及其他";//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
                    }
                    model.F_State = model1[i].F_State;
                    if (model1[i].F_State == 0)//工单状态
                    {
                        model.F_StateName = "待指派";
                    }
                    else if (model1[i].F_State == 1)
                    {
                        model.F_StateName = "待接单";
                    }
                    else if (model1[i].F_State == 2)
                    {
                        model.F_StateName = "待处理";
                    }
                    else if (model1[i].F_State == 3)
                    {
                        model.F_StateName = "已退回";
                    }
                    else if (model1[i].F_State == 4)
                    {
                        model.F_StateName = "异常退回";
                    }
                    else if (model1[i].F_State == 5)
                    {
                        model.F_StateName = "处理中";
                    }
                    else if (model1[i].F_State == 6)
                    {
                        model.F_StateName = "待回访";
                    }
                    else if (model1[i].F_State == 7)
                    {
                        model.F_StateName = "待完结";
                    }
                    else if (model1[i].F_State == 10)
                    {
                        model.F_StateName = "已处理";
                    }
                    else if (model1[i].F_State == 11)
                    {
                        model.F_StateName = "已评价";
                    }
                    else if (model1[i].F_State == 12)
                    {
                        model.F_StateName = "已退回";
                    }
                    else if (model1[i].F_State == 14)
                    {
                        model.F_StateName = "待办理";
                    }
                    else if (model1[i].F_State == 15)
                    {
                        model.F_StateName = "微信未通过";
                    }
                    else if (model1[i].F_State == 16)
                    {
                        model.F_StateName = "待审批";
                    }
                    else if (model1[i].F_State == 17)
                    {
                        model.F_StateName = "已撤回待指派";
                    }

                    #region  内线工单状态
                    model.F_State2 = model1[i].F_State2;
                    if (model1[i].F_State2 == 0)//工单状态
                    {
                        model.F_StateName2 = "待指派";
                    }
                    else if (model1[i].F_State2 == 1)
                    {
                        model.F_StateName2 = "待接单";
                    }
                    else if (model1[i].F_State2 == 2)
                    {
                        model.F_StateName2 = "待处理";
                    }
                    else if (model1[i].F_State2 == 3)
                    {
                        model.F_StateName2 = "已退回";
                    }
                    else if (model1[i].F_State2 == 4)
                    {
                        model.F_StateName2 = "异常退回";
                    }
                    else if (model1[i].F_State2 == 5)
                    {
                        model.F_StateName2 = "处理中";
                    }
                    else if (model1[i].F_State2 == 6)
                    {
                        model.F_StateName2 = "待回访";
                    }
                    else if (model1[i].F_State2 == 7)
                    {
                        model.F_StateName2 = "待完结";
                    }
                    else if (model1[i].F_State2 == 10)
                    {
                        model.F_StateName2 = "已处理";
                    }
                    else if (model1[i].F_State2 == 11)
                    {
                        model.F_StateName2 = "已回访";
                    }
                    else if (model1[i].F_State2 == 12)
                    {
                        model.F_StateName2 = "已退回";
                    }
                    else if (model1[i].F_State2 == 13)
                    {
                        model.F_StateName2 = "导入工单";
                    }
                    else if (model1[i].F_State2 == 14)
                    {
                        model.F_StateName2 = "待办理";
                    }
                    else if (model1[i].F_State2 == 15)
                    {
                        model.F_StateName2 = "微信未通过";
                    }
                    else if (model1[i].F_State2 == 16)
                    {
                        model.F_StateName2 = "待审批";
                    }
                    else if (model1[i].F_State2 == 17)
                    {
                        model.F_StateName2 = "已撤回待指派";
                    }
                    #endregion 内线工单状态

                    #endregion
                    model.F_CusName = model1[i].F_CusName;//客户姓名
                    model.F_CusPhone = model1[i].F_CusPhone;//客户电话
                    model.F_Canal = model1[i].F_Canal;//
                    model.F_IncidentProvince = model1[i].F_IncidentProvince;//事发地-省
                    model.F_IncidentCity = model1[i].F_IncidentCity;//事发地-市
                    model.F_IncidentCountry = model1[i].F_IncidentCountry;//事发地-县
                    model.F_IncidentTownship = model1[i].F_IncidentTownship;//事发地-乡
                    model.F_IncidentDetailed = model1[i].F_IncidentDetailed;//事发地-详细
                    model.F_SalesBase = model1[i].F_SalesBase;//销售基地:新乡、新疆、九江、东北、其他(其它手动输入别的点选)
                    model.F_Description = model1[i].F_Description;//问题描述
                    model.F_Files = "0";//附件上传ids
                    model.F_DealType = model1[i].F_DealType;//处理方式:当即办理、电话转接、网络转办（点选）
                    #endregion
                    if (!string.IsNullOrEmpty(model1[i].F_QuestionType))
                    {
                        try
                        {
                            int b = int.Parse(model1[i].F_QuestionType.Trim());
                            Model.T_Wo_QuestionManage manage = quesBLL.GetModel(b);
                            if (manage != null)
                            {
                                model.F_QuestionType = manage.F_QuestionName;//问题类别3
                                model.F_QuestionTypeid = manage.F_Id;
                                #region 20220304 修改 肥效类增加作物字段
                                if (manage.F_Label == "3")
                                {
                                    Model.T_Wo_QuestionManage Manage1 = quesBLL.GetModel(int.Parse(manage.F_ParentId.ToString()));//获取问题类别2
                                    Model.T_Wo_QuestionManage Manage2 = quesBLL.GetModel(int.Parse(Manage1.F_ParentId.ToString()));//获取问题类别1
                                    model.F_QuestionTypeone = Manage2.F_QuestionName;//问题类别1
                                    model.F_QuestionTypeoneid = Manage2.F_Id;//问题类别1
                                    model.F_QuestionTypetwo = Manage1.F_QuestionName;//问题类别2
                                    model.F_QuestionTypetwoid = Manage1.F_Id;//问题类别2
                                    var cropid = 0;
                                    if (int.TryParse(model1[i].F_Crops.Trim(), out cropid))
                                    {
                                        model.F_QuestionTypefour = new BLL.T_Sys_DictionaryValue().GetModel(cropid)?.F_Name ?? "";//问题类别4
                                        model.F_QuestionTypefourid = cropid;//问题类别4
                                    }
                                }
                                #endregion
                                #region 修改前
                                //if (manage.F_Label == "3")
                                //   {
                                //    Model.T_Wo_QuestionManage Manage1 = quesBLL.GetModel(int.Parse(manage.F_ParentId.ToString()));//获取问题类别
                                //    Model.T_Wo_QuestionManage Manage2 = quesBLL.GetModel(int.Parse(Manage1.F_ParentId.ToString()));//获取问题类别
                                //    model.F_QuestionTypeone = Manage2.F_QuestionName;//问题类别1
                                //    model.F_QuestionTypeoneid = Manage2.F_Id ;//问题类别1
                                //    model.F_QuestionTypetwo = Manage1.F_QuestionName;//问题类别2
                                //    model.F_QuestionTypetwoid = Manage1.F_Id;//问题类别2

                                //}
                                #endregion
                            }

                        }
                        catch (Exception)
                        {
                            model.F_QuestionType = model1[i].F_QuestionType; //问题类别（投诉抽捡和咨询类别不一样）
                        }
                    }
                    model.F_Annotation = model1[i].F_Annotation; ;//注解
                    #region 投诉类
                    model.F_BatchNumber = model1[i].F_BatchNumber;//生产批次号
                    model.F_TS_Formula = model1[i].F_TS_Formula;// 投诉-配方
                    model.F_TS_Category = model1[i].F_TS_Category;//投诉-产品种类：化肥、化工、其他
                    if (!string.IsNullOrEmpty(model1[i].F_TS_Quantity))
                    {
                        model.F_TS_Quantity = model1[i].F_TS_Quantity ;//投诉-问题数量（吨）
                    }
                    else
                        model.F_TS_Quantity = "";
                    model.F_TS_Level = model1[i].F_TS_Level;//投诉-重要级别：轻微、一般、较大、重大
                    if (model1[i].MaterialItems != null)
                    {
                        model.MaterialItems = model1[i].MaterialItems;  //退换货多物料信息
                    }
                    else
                        model.MaterialItems = null;
                    model.F_CarNumber = model1[i].F_CarNumber;
                    model.F_LoadingFee = model1[i].F_LoadingFee;
                    model.F_UnLoadingFee = model1[i].F_UnLoadingFee;
                    model.F_MaterialFee = model1[i].F_MaterialFee;
                    model.F_EventReason = model1[i].F_EventReason;
                    model.F_EventReason2 = model1[i].F_EventReason2;
                    #endregion
                    #region 咨询类
                    //  model.F_ZX_ProName = model1[i].F_ZX_ProName;//咨询-产品名称：三聚氰胺、甲醇、液氨、二甲醚、糠醇、其他
                    model.F_ZX_Quantity = model1[i].F_ZX_Quantity;// 咨询-问题数量（吨）
                    model.F_ZX_Area = model1[i].F_ZX_Area;// 咨询-大区
                    model.F_ZX_Branch = model1[i].F_ZX_Branch;// 咨询-分公司
                    #endregion
                    #region 抽检类
                    model.F_CJ_Time = model1[i].F_CJ_Time;// 抽检-抽检时间
                    model.F_CJ_Level = model1[i].F_CJ_Level;// 抽检-抽检级别：乡镇级、县级、市级、省级及以上、个人送检
                    model.F_CJ_Unit = model1[i].F_CJ_Unit;// 抽检-抽检单位：市场监督、农业部、土肥站、工商、联合执法、其他
                    model.F_CJ_TestUnit = model1[i].F_CJ_TestUnit;//抽检-化验单位
                    model.F_CJ_Tonnage = model1[i].F_CJ_Tonnage;//抽检-抽检吨数
                    model.F_CJ_BagNo = model1[i].F_CJ_BagNo;//抽检-抽检袋数
                    model.F_CJ_Outlay = model1[i].F_CJ_Outlay;//抽检-公关费用金额：单位元
                    model.F_Production = model1[i].F_Production;
                    model.F_WorkerBrand = model1[i].F_Brand;//工单品牌
                    model.F_DealBy = model1[i].F_DealBy;//处理人
                    model.F_DealTime = model1[i].F_DealTime;//处理时间  
                    model.F_DealContent = model1[i].F_DealContent;//处理内容---外线
                    model.F_DealContent2 = model1[i].F_DealContent2;//处理内容---内线
                    model.F_DealResult = model1[i].F_DealResult;//处理结果
                    model.F_DealReasons = model1[i].F_DealReasons;//未处理原因
                    model.F_SC_ProductBase = model1[i].F_SC_ProductBase;//市场管理科-生产基地（新乡、新疆、九江、东北、贴牌、无法确定）
                    model.F_SC_PreliminaryOpinion = model1[i].F_SC_PreliminaryOpinion;// 市场管理科-初审意见:退货、换货、补偿、自行处理
                    model.F_SC_QualityMonth = model1[i].F_SC_QualityMonth;//市场管理科-超出质保期限（算法：工单创建日期-生产日期，生产日期根据生产批次号获取，单位：月）
                    model.F_SC_CJ_SpotResult = model1[i].F_SC_CJ_SpotResult;/// 市场管理科-抽检-抽检结果（视同合格、合格、不合格、复检后合格、未送检）
                    model.F_SC_CJ_SelfResult = model1[i].F_SC_CJ_SelfResult;//市场管理科-抽检-自检结果
                    model.F_SC_CJ_ApprovalNo = model1[i].F_SC_CJ_ApprovalNo;// 市场管理科-抽检-对应审批工作流单号
                    model.F_SC_CJ_ReturnAccount = model1[i].F_SC_CJ_ReturnAccount;//市场管理科-抽检-确认返账金额（元）
                    model.F_ZL_QualityEventLevel = model1[i].F_ZL_QualityEventLevel;// 质量管理科-质量事件等级（未遂、一般、较大、重大）
                    model.F_ZL_ClaimAmount = model1[i].F_ZL_ClaimAmount;//质量管理科-索赔金额（单位元，对应责任单位）
                    model.F_ZL_ResponsibleUnit = model1[i].F_ZL_ResponsibleUnit;//质量管理科-责任单位（需列出，可选多个）
                    model.F_ZL_ApprovalOpinions = model1[i].F_ZL_ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
                    model.F_ZL_ApprovalDisagree = model1[i].F_ZL_ApprovalDisagree;// 质量管理科-审批不同意意见
                    model.F_ZL_CompensationMethod = model1[i].F_ZL_CompensationMethod;//质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
                    model.F_ZL_CompensationMoney = model1[i].F_ZL_CompensationMoney;// 质量管理科-补偿钱款
                    model.F_ZL_CResponsibleUnits = model1[i].F_ZL_CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
                    model.F_ZL_Fquantity = model1[i].F_ZL_Fquantity;// 质量管理科-确认实收数量（吨）
                    model.F_ZL_ImprovementRequirements = model1[i].F_ZL_ImprovementRequirements;//质量管理科-改进要求
                    model.F_ZL_CApprovalNo = model1[i].F_ZL_CApprovalNo;//质量管理科-对应审批工作流单号
                    model.F_ZL_CJ_IsRecord = model1[i].F_ZL_CJ_IsRecord;//质量管理科-抽检-未备案、已备案
                    model.F_VisitRemarks = model1[i].F_VisitRemarks;//回访备注
                    //model.SuperiorOpinion = AssCont(model1[i].F_ID);//上级处理意见
                    model.SuperiorOpinion = model1[i].F_SuperiorOpinion;//处理结果--外线
                    model.SuperiorOpinion2 = model1[i].F_SuperiorOpinion2;//处理结果--内线
                    model.F_Reasontimeout= model1[i].F_Reasontimeout;//超期原因
                    if (model1[i].F_SMSReply == 1)
                    {
                        model.F_SMSReply = "满意";//短信回访结果
                    }
                    else if (model1[i].F_SMSReply == 2)
                    {
                        model.F_SMSReply = "一般";//短信回访结果
                    }
                    else if (model1[i].F_SMSReply == 3)
                    {
                        model.F_SMSReply = "不满意";//短信回访结果
                    }
                    else
                    {
                        model.F_SMSReply = "";//短信回访结果
                    }
                    if (model1[i].F_IsVisit != 0)
                    {
                        model.F_IsVisit = "是";//是否回访
                    }
                    else
                    {
                        model.F_IsVisit = "否";//是否回访
                    }

                    model.F_IsAudit = model1[i].F_IsAudit;//是否审核
                    model.F_Highopinions = model1[i].F_Highopinions;//高层处理意见
                    model.F_CreateOn = model1[i].F_CreateOn; ;//添加时间
                                                              //  model.F_CreateBy = model1[i].F_CreateBy; ;//添加人
                    if (!string.IsNullOrEmpty(model1[i].F_CreateBy))

                    {
                        Model.T_Sys_UserAccount creatname = userAccountBLL.GetModel(model1[i].F_CreateBy);
                        if (creatname != null)
                        {
                            model.F_CreateBy = creatname.F_WorkNumber; ;//添加人
                            model.F_CreateName = creatname.F_UserName; ;//添加人
                            model.F_CreatePhone = creatname.F_Mobile;
                            model.CreateName = creatname.F_UserName + "(" + creatname.F_WorkNumber + ")";
                        }

                    }
                    model.F_UpdateBy = model1[i].F_UpdateBy;//修改人工号
                    model.F_UpdateOn = model1[i].F_UpdateOn; ;//修改人工号

                    if (model1[i].F_IsAudit != 0 && model1[i].F_IsAudit != null)
                    {
                        if (model1[i].F_AuditState == 0)
                        {
                            model.F_AuditState = "同意上报";
                        }
                        else if (model1[i].F_AuditState == 1)
                        {
                            model.F_AuditState = "驳回修订";
                        }
                        else
                        {
                            model.F_AuditState = "强制结案";
                        }
                    }
                    else
                    {
                        model.F_AuditState = "";
                    }
                   
                    model.F_AuditBy = model1[i].F_AuditBy;//审核人
                    model.F_AuditOn = model1[i].F_AuditOn;//审核时间
                    model.F_AuditCont = model1[i].F_AuditCont;//审核内容
                                                              // model.RemainingTime = float.Parse(string.Format("{0:f2}", TimeToOver(model1[i].F_ID, model1[i].F_limit)));

                    float c = TimeToOver(model1[i].F_ID, model1[i].F_limit);
                   float a = Math.Abs(c);
                    int days = (int)Math.Floor(Convert.ToDouble(a / 24));
                    int hours = days > 0
                                   ? (int)Math.Floor(Convert.ToDouble((a - days * 24)))
                                   : (int)Math.Floor(Convert.ToDouble(a));
                    float minutes = hours > 0
                                   ? a * 60 - days * 1440 - hours * 60
                                   : 0;
                    if (c > 0)
                    model.RemainingTime = string.Format("剩余{0:f0}天{1:f0}时{2:f0}分", days, hours, minutes);
                    else
                        model.RemainingTime = string.Format("超时{0:f0}天{1:f0}时{2:f0}分", days, hours, minutes);


                    #region 内线超时时间计算
                    float c2 = TimeToOver(model1[i].F_ID, model1[i].F_limit, 2);
                    float a2 = Math.Abs(c2);
                    int days2 = (int)Math.Floor(Convert.ToDouble(a2 / 24));
                    int hours2 = days2 > 0
                                   ? (int)Math.Floor(Convert.ToDouble((a2 - days2 * 24)))
                                   : (int)Math.Floor(Convert.ToDouble(a2));
                    float minutes2 = hours2 > 0
                                   ? a2 * 60 - days2 * 1440 - hours2 * 60
                                   : 0;
                    if (c2 > 0)
                        model.RemainingTime2 = string.Format("剩余{0:f0}天{1:f0}时{2:f0}分", days2, hours2, minutes2);
                    else
                        model.RemainingTime2 = string.Format("超时{0:f0}天{1:f0}时{2:f0}分", days2, hours2, minutes2);
                    #endregion

                    if (ua != null)
                    {
                        var itemlast = itembll.GetModelList("   F_WoID='" + model.F_ID + "' order by F_ID desc").FirstOrDefault();
                        if (itemlast != null)
                            model.F_UserCode = itemlast.F_CreateUser;
                        if (!string.IsNullOrEmpty(model.F_UserCode))
                        {
                            Model.T_Sys_UserAccount user = userAccountBLL.GetModel(model.F_UserCode);
                            if (user != null)
                            {
                                model.F_UserName = user?.F_UserName?? "";
                                Model.T_Sys_Department dept = departmentBLL.GetModel(user.F_DeptId);
                                if (dept != null)
                                {
                                    model.F_NextDeptName = dept.F_DeptName;
                                }
                            }
                        }

                    }
                    model.F_limit = model1[i].F_limit;
                    int day = (int)Math.Floor(Convert.ToDouble(model.F_limit / 24));
                    int hour = day > 0
                                   ? (int)Math.Floor(Convert.ToDouble((model.F_limit - day * 24)))
                                   : (int)Math.Floor(Convert.ToDouble(model.F_limit));

                    string time = "";
                    if (day > 0) time += day + "天";
                    if (hour > 0) time += hour + "小时";
                    model.F_limitTime = time;
                    //if (model1[i].F_Type !="3")
                    //{
                    //    #region 判断外线是否超时
                    //    if (TimeToOver(model1[i].F_ID, model1[i].F_limit) < 0)
                    //    {
                    //        model.F_IsOver = 1;
                    //    }
                    //    #endregion
                    //    #region 判断内线是否超时
                    //    else if (TimeToOver(model1[i].F_ID, model1[i].F_limit, 2) < 0)
                    //    {
                    //        model.F_IsOver = 2; //内线超时
                    //    }
                    //    #endregion
                    //    else
                    //    {
                    //        model.F_IsOver = model1[i].F_IsOver;
                    //    }
                    //}
                    model.F_IsOver = model1[i].F_IsOver;
                    model.F_VisitResultScore = model1[i].F_VisitResultScore;
                    model.F_EffectiveScore = model1[i].F_EffectiveScore;
                    model.F_ServiceAttitude = model1[i].F_ServiceAttitude;
                    model.F_ProductQuality = model1[i].F_ProductQuality;
                    model.F_NPS = model1[i].F_NPS;
                    model.F_EvaluationResult = model1[i].F_EvaluationResult;
                    model.F_MailingNumber = model1[i].F_MailingNumber;
                    model.F_ExpressName = model1[i].F_ExpressName;
                    model.F_WorkmanShip = model1[i].F_WorkmanShip;//质量管理科-工艺
                    model.F_Manufacturers = model1[i].F_Manufacturers;//质量管理科-原料及厂家
                    model.F_ProductionNum = model1[i].F_ProductionNum;//质量管理科-该批次生产数量
                    if (ua != null)
                    {
                        var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                        if (deptmodel != null)
                        {
                            model.F_Deptid = deptmodel.F_DeptId;
                            model.F_DeptName = deptmodel.F_DeptName;
                        }
                    }

                    #endregion
                    Input.Add(model);
                }
                return Input;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 是否超时
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private float TimeToOver(int id, int limit, int flag = 1)
        {
            string strsql = "";
            if (flag == 1)
            {
                strsql = " and F_Type in(1,3)";
            }
            else if (flag == 2)
            {
                strsql = " and F_Type in(2,3)";
            }
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + "" + strsql + " and  F_WoID=" + id);
            string time1 = "", time2 = ""; int x = 0, y = 0;
            if (itemlasts.Count > 0)
            {
                for (int z = 0; z < itemlasts.Count; z++)
                {
                    if (itemlasts[z].F_WoState >= 1)
                    {
                        if (itemlasts[z].F_WoState == 1)
                        {
                            x = z;
                            time1 = itemlasts[z].F_CreateTime.ToString();
                            break;
                        }
                    }
                }
                for (int i = 0; i < itemlasts.Count; i++)
                {
                    if (itemlasts[i].F_WoState >= 1)
                    {

                        if (itemlasts[i].F_WoState == 10 || itemlasts[i].F_WoState == 11)
                        {
                            y = i;
                            time2 = itemlasts[i].F_CreateTime.ToString();
                        }
                    }
                }
                if (time2 != "")
                {
                    if (time1 != "")
                    {
                        if (y > x)
                        {
                            System.TimeSpan a = DateTime.Parse(time2) - DateTime.Parse(time1);
                            float b = limit - (float)a.TotalHours;
                            return b;
                        }
                        else
                        {
                            System.TimeSpan a = DateTime.Now - DateTime.Parse(time1);
                            float b = limit - (float)a.TotalHours;
                            return b;
                        }
                    }
                    else
                    {
                        return 0;
                    }
                }
                else if (time1 != "")
                {
                    System.TimeSpan a = DateTime.Now - DateTime.Parse(time1);
                    float b = limit - (float)a.TotalHours;
                    return b;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                return 0;
            }

        }
        private string AssCont(int id)
        {
            string cont = "";
            var itemlist = itembll.GetModelList("F_WoID=" + id + "and F_IsUsed=0" + "order by F_ID desc");
            if (itemlist.Count > 0)
            {
                cont = itemlist[0].F_OptContent;
            }
            return cont;
        }
        /// <summary>
        /// 获取当前用户上一级的用户
        /// </summary>
        /// <param name="OpenId"></param>
        /// <returns></returns>
        public Model.T_Sys_UserAccount GetUser(string OpenId)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                //  int userId = CurrentUser.UserData.F_UserId;
                //   Model.T_Sys_UserAccount ua = userAccountBLL.GetModel(userId);
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();

                if (ua != null)
                {
                    Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                    var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                    //  var dept = departmentBLL.GetModel(deptmodel.F_ParentId);
                    #region 业务员

                    if (ro.F_RoleCode == "YWY")
                    {
                        if (deptmodel != null)
                        {
                            Model.T_Sys_UserAccount userModel = userAccountBLL.GetModelList(" F_DeptId=" + deptmodel.F_DeptId + " and F_RoleId=60 ").FirstOrDefault();
                            if (userModel != null)
                                return userModel;
                            else
                            {
                                Model.T_Sys_UserAccount userModel1 = userAccountBLL.GetModelList(" F_DeptId=" + deptmodel.F_DeptId + " and F_RoleId=62  ").FirstOrDefault();
                                return userModel1;
                            }
                            //if (deptmodel.F_Layer == 2)
                            //{
                            //    Model.T_Sys_UserAccount userModel = userAccountBLL.GetModelList(" F_DeptId=" + deptmodel.F_DeptId + " and F_RoleId=60 ").FirstOrDefault();
                            // if (userModel!=null )
                            //    return userModel;
                            // else
                            //    {
                            //        var dept = departmentBLL.GetModel(deptmodel.F_ParentId);
                            //        if (dept != null)
                            //        {
                            //            Model.T_Sys_UserAccount userModel1 = userAccountBLL.GetModelList(" F_DeptId=" + dept.F_DeptId + " and F_RoleId=62  ").FirstOrDefault();
                            //            return userModel1;
                            //        }
                            //    }

                            //}
                            //if (deptmodel.F_Layer == 1)
                            //{
                            //    Model.T_Sys_UserAccount userModel = userAccountBLL.GetModelList(" F_DeptId=" + deptmodel.F_DeptId + " and F_RoleId=62  ").FirstOrDefault();
                            //    return userModel;
                            //}
                        }
                        else
                        {
                            return null;
                        }
                    }
                    #endregion
                    #region 大区经理

                    else if (ro.F_RoleCode == "DQJL")
                    {
                        return null;
                    }
                    #endregion
                    #region 分公司经理

                    else if (ro.F_RoleCode == "FGSJL")
                    {
                        if (deptmodel != null)
                        {
                            var dept = departmentBLL.GetModel(deptmodel.F_ParentId);
                            if (dept != null)
                            {
                                Model.T_Sys_UserAccount userModel = userAccountBLL.GetModelList(" F_DeptId=" + dept.F_DeptId + " and F_RoleId=62  ").FirstOrDefault();
                                if (userModel!=null )
                                return userModel;
                               
                            }
                            else
                            {
                                return null;
                            }
                        }
                        else
                        {
                            return null;
                        }
                    }
                    #endregion
                }

                return null;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 获取上一级管理员
        /// </summary>
        /// <param name="OpenId"></param>
        /// <returns></returns>
        [WechatActionFilter]
        public ActionResult GetDpment(string OpenId)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                if (GetUser(OpenId) != null)
                {
                    return Success("获取成功！", GetUser(OpenId));

                }
                else
                {
                    return Success("获取失败！", null);
                }
            }
            else
            {
                return Error("OpenId不能为空！");
            }
        }

        /// <summary>
        ///  修改密码
        /// </summary>
        /// <returns></returns>
        [WechatActionFilter]
        public ActionResult UpdatePassWord()
        {
            string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
            //5--业主（客户档案会员） 
            int usertype = RequestString.GetInt("usertype", 0);
            //原密码
            string oldpwd = RequestString.GetFormString("oldpwd").Trim();
            string pwd = RequestString.GetFormString("pwd").Trim();
            string repeatpwd = RequestString.GetFormString("repeatpwd").Trim();
            if (usertype == 0)
                return Error("无权修改密码");
            if (string.IsNullOrWhiteSpace(oldpwd))
                return Error("请输入原密码");
            if (string.IsNullOrWhiteSpace(pwd))
                return Error("请输入新密码");
            if (string.IsNullOrWhiteSpace(repeatpwd))
                return Error("请再次输入新密码");
            if (!pwd.Equals(repeatpwd))
                return Error("两个新密码不同，请重新输入");
            var model = new Model.T_Sys_UserAccount();
            var modelCus = new Model.T_Cus_CustomerBaseNew();
            //坐席表
            if (usertype < 5)
            {
                model = userAccountBLL.GetModelByOpenid(stropenid);
                if (model != null)
                {
                    if (!model.F_Password.Equals(oldpwd)) return Error("原密码不正确");
                    model.F_Password = pwd;
                    if (userAccountBLL.Update(model))
                        return Success("重置密码成功");
                }
                return Error("重置密码失败");
            }
            //客户档案表
            modelCus = customerBaseBLL.GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();//customerBaseBLL.GetModelByOpenid(stropenid);
            if (modelCus != null)
            {
                if (!modelCus.F_WxPassword.Equals(oldpwd)) return Error("原密码不正确");
                modelCus.F_WxPassword = pwd;
                if (customerBaseBLL.Update(modelCus))
                    return Success("重置密码成功");
            }
            return Error("重置密码失败");
        }

        /// <summary>
        /// 验证生产批次号为15位
        /// </summary>
        private bool vaBatchNumber(string code)
        {
            var res = false;
            if (code.Length == 15)
            {
                char chr = code[12];
                if (chr > 'A' && chr < 'Z')
                {
                    string code1 = code.Substring(0, 12);
                    string code2 = code.Substring(15 - 2, 2);
                    if (Regex.IsMatch(code1, @"^\d{12}$") && Regex.IsMatch(code2, @"^\d{2}$"))
                        res = true;
                }
                else
                {
                    res = false;
                }
            }
            return res;
        }
        /// <summary>
        /// 验证物料编码为10位纯数字
        /// </summary>
        private bool valcode(string code, int number)
        {
            var res = false;
            //11位数字
            if (code.Length == number && Regex.IsMatch(code, @"^\d{" + number + "}$"))
                res = true;
            return res;
        }
        /// <summary>
        /// 验证物料编号是否唯一
        /// </summary>
        private bool gematerque(int id, string code)
        {
            var sql = " F_IsDelete=0 ";
            sql += "and (F_MaterialCode='" + code + "')";
            if (id > 0)
                sql += " and F_Id<>" + id;
            var count = mmBLL.GetModelList(sql).Count();

            return count > 0;
        }

        /// <summary>
        /// 验证客户编号是否唯一
        /// </summary>
        private bool getunique(int id, string code)
        {
            var sql = " F_IsDelete=0 ";
            sql += "and (F_CustomerCode='" + code + "')";
            if (id > 0)
                sql += " and F_CustomerId<>" + id;
            var count = customerBaseBLL.GetModelList(sql).Count();

            return count > 0;
        }
        /// <summary>
        /// 获取我参与的工单编号
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetParticipateID(string user)
        {
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_CreateUser in(" + user + ") and F_OptType in( 0,1,7 )";

            ;
            return str;
        }
        /// <summary>
        /// 获取我参与的工单编号
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetID(string user)
        {
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_CreateUser in(" + user + ") ";

            ;
            return str;
        }
        /// <summary>
        /// 获取我参与的工单编号
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetParticipate(string user)
        {
            string str = string.Empty;
            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_CreateUser in(" + user + ")  ";

            ;
            return str;
        }
        private bool IsCustomerBaseNew(WorkOrderNewInput input)
        {
            bool n = false;
            if (!string.IsNullOrEmpty(input.F_CustomerID) || !string.IsNullOrEmpty(input.F_CompanyName)
               || !string.IsNullOrEmpty(input.F_AreaName) || !string.IsNullOrEmpty(input.F_BranchName)
                || !string.IsNullOrEmpty(input.F_Salesman) || !string.IsNullOrEmpty(input.F_SalesPhone)
              || !string.IsNullOrEmpty(input.F_Brands) )
            {
                n = true;
            }
            return n;
        }
        /// <summary>
        /// 添加客户
        /// </summary>
        private Model.T_Cus_CustomerBaseNew inputtooCustomer(Model.T_Cus_CustomerBaseNew model, WorkOrderNewInput input)
        {
            var newmodel = model;
            if (!string.IsNullOrWhiteSpace(input.F_CustomerID.ToString()))
                model.F_CustomerCode = input.F_CustomerID.ToString();
            else
                model.F_CustomerCode = model.F_CustomerCode;
            if (!string.IsNullOrWhiteSpace(input.F_CompanyName))
                model.F_CompanyName = input.F_CompanyName;
            #region 基本字段
            if (!string.IsNullOrEmpty(input.F_AreaName))
            {
                Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                try
                {
                    pdModel = departmentBLL.GetModel(int.Parse(input.F_AreaName));
                }
                catch
                {
                    pdModel = departmentBLL.GetModel(input.F_AreaName);
                }
                model.F_AreaID = pdModel.F_DeptId.ToString();
            }

            if (!string.IsNullOrEmpty(input.F_BranchName))
            {
                Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                try
                {
                    pdModel = departmentBLL.GetModel(int.Parse(input.F_BranchName));
                }
                catch
                {
                    pdModel = departmentBLL.GetModel(input.F_BranchName);
                }
                model.F_BranchID = pdModel.F_DeptId.ToString();
            }
            model.F_Salesman = input.F_Salesman;//业务员
            model.F_SalesPhone = input.F_SalesPhone;//业务员电话
            model.F_Channel = input.F_Channel;// 渠道类型:总经销、二级商、种田大户、农户、化工客户、公司员工
            model.F_Legal = input.F_CusName;//法人 
            model.F_LegalPhone = input.F_CusPhone;//法人电话
            model.F_AddressProvince = input.F_AddressProvince;//省
            model.F_AddressCity = input.F_AddressCity;//市
            model.F_AddressCountry = input.F_AddressCountry;//县
            model.F_AddressTownship = input.F_AddressTownship;//乡
            model.F_AddressFull = input.F_AddressFull;//详细地址
            model.F_Brands = input.F_Brands;// 经营品牌:心连心、手拉手、沃利沃、双心、空
            model.F_IsRunXLX = input.F_IsRunXLX;// 是否经营心连心:是、否
            model.F_AnnualSales = input.F_AnnualSales;//年销量
            model.F_Formula = input.F_Formula;//配方
            model.F_RaiseCrops = input.F_RaiseCrops;//种植作物
            model.F_PlantingArea = input.F_PlantingArea;//种植面积
            model.F_FertilizerBrand = input.F_FertilizerBrand;//用肥品牌
            model.F_FileId = 0;
            #endregion
            return model;
        }
        private string GetCusCode(int i)
        {
            DateTime times = DateTime.Now.AddMinutes(i);
            string time = times.ToString("yyMMddhhmm");
            return time;
        }
        private string GetIntCode()
        {
            string time = DateTime.Now.ToString("hhmmss");
            Random ran = new Random();
            int RandKey = ran.Next(1000, 9999);
            string timecode = 3 + "" + RandKey + "" + time;
            return timecode;
        }
        private bool IsMaterial(WorkOrderNewInput input)
        {
            bool n = false;
            if (!string.IsNullOrEmpty(input.F_MaterialID) || !string.IsNullOrEmpty(input.F_MaterialName)
               || !string.IsNullOrEmpty(input.F_Model) || !string.IsNullOrEmpty(input.F_Specs)
                || !string.IsNullOrEmpty(input.F_Level1) || !string.IsNullOrEmpty(input.F_Level2)
              || !string.IsNullOrEmpty(input.F_Level3) || !string.IsNullOrEmpty(input.F_Brand)
              || !string.IsNullOrEmpty(input.F_MaterialEffect) || !string.IsNullOrEmpty(input.F_Craft)
              || !string.IsNullOrEmpty(input.F_Pipeline))
            {
                n = true;
            }
            return n;
        }
        private void AddMait(WorkOrderNewInput input, string usercode)
        {
            Model.T_Wo_MaterialManage dModel = new Model.T_Wo_MaterialManage();
            dModel.F_MaterialCode = input.F_MaterialID.ToString();//物料编号
            dModel.F_MaterialName = input.F_MaterialName;//物料名称
            dModel.F_Model = input.F_Model;//型号
            dModel.F_Specs = input.F_Specs;//规格
            dModel.F_Level1 = input.F_Level1;//一级分类
            dModel.F_Level2 = input.F_Level2;//二级分类
            dModel.F_Level3 = input.F_Level3;//三级分类
            dModel.F_Brand = input.F_Brand;//品牌
            dModel.F_MaterialEffect = input.F_MaterialEffect;//复合肥肥效
            dModel.F_Craft = input.F_Craft;//工艺
            dModel.F_Pipeline = input.F_Pipeline;//产品线
            dModel.F_IsDelete = 0;
            dModel.F_CreateOn = DateTime.Now;
            dModel.F_CreateBy = usercode;
            int f = mmBLL.Add(dModel);
        }
        /// <summary>
        /// 根据传入的对象和input的内容返回对象（添加修改使用）
        /// </summary>
        private Model.T_Wo_WorkOrder inputtoobj(Model.T_Sys_UserAccount ua, Model.T_Wo_WorkOrder model, WorkOrderNewInput input, int type)
        {
            string usercode = "";
            if (ua != null)
            {
                usercode = ua.F_UserCode;
            }
            var newmodel = model;
            if (input.F_ID != 0)
            {
                model.F_ID = input.F_ID;

            }
            else
            {
                model.F_ID = model.F_ID;//工单ID

            }
            if (type == 2)
            {
                model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");  //工单编号  
                model.F_Source = model.F_Source;
            }
            else
            {
                model.F_WorkOrderCode = model.F_WorkOrderCode;//工单编号
                model.F_Source = model.F_Source.ToString();//工单来源
            }

            if (input.F_Type == 2 || input.F_Type == 3)
            {
                if (string.IsNullOrEmpty(input.F_CustomerID))
                {
                    var sql = $" and  F_LegalPhone  = '" + input.F_CusPhone.Trim() + "'";
                    var Customer = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_IsDelete = 0 " + sql).FirstOrDefault(); ;
                    if (Customer != null)
                    {
                        model.F_CustomerID = Customer.F_CustomerCode;
                        if (!string.IsNullOrEmpty(input.F_Salesman))
                            Customer.F_Salesman = input.F_Salesman;
                        if (!string.IsNullOrEmpty(input.F_SalesPhone))
                            Customer.F_SalesPhone = input.F_SalesPhone;
                        if (!string.IsNullOrEmpty(input.F_Channel))
                            Customer.F_Channel = input.F_Channel;

                        if (!string.IsNullOrEmpty(input.F_Brands))
                            Customer.F_Brands = input.F_Brands;
                        if (!string.IsNullOrEmpty(input.F_AreaName))
                        {
                            Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                            try
                            {
                                pdModel = departmentBLL.GetModel(int.Parse(input.F_AreaName));
                            }
                            catch
                            {
                                pdModel = departmentBLL.GetModel(input.F_AreaName);
                            }
                            Customer.F_AreaID = pdModel.F_DeptId.ToString();
                        }
                        else
                        {
                            Customer.F_AreaID = "";
                        }

                        if (!string.IsNullOrEmpty(input.F_BranchName))
                        {
                            Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                            try
                            {
                                pdModel = departmentBLL.GetModel(int.Parse(input.F_BranchName));
                            }
                            catch
                            {
                                pdModel = departmentBLL.GetModel(input.F_BranchName);
                            }
                            Customer.F_BranchID = pdModel.F_DeptId.ToString();
                        }
                        else
                        {
                            Customer.F_BranchID = "";
                        }
                        if (!string.IsNullOrEmpty(input.F_CompanyName ))
                            Customer.F_CompanyName = input.F_CompanyName;
                        customerBaseBLL.Update(Customer);
                    }
                    else
                    {
                        if (IsCustomerBaseNew(input))
                        {
                            
                            if (string.IsNullOrEmpty(input.F_CustomerID))
                            {
                                    int i = 0;
                                    while (true)
                                    {
                                   
                                        if (!getunique(0, GetCusCode(i)))
                                        {
                                            input.F_CustomerID = GetCusCode(i);
                                            break;
                                        }
                                        else
                                        {
                                            i++;
                                        }
                                    }
                            }
                            var CustomerBaseNewmodel = new Model.T_Cus_CustomerBaseNew();
                            CustomerBaseNewmodel.F_CustomerCode = input.F_CustomerID;
                            CustomerBaseNewmodel.F_CreateBy = usercode;
                            CustomerBaseNewmodel.F_CreateOn = DateTime.Now;
                            CustomerBaseNewmodel.F_IsDelete = 0;
                            customerBaseBLL.Add(inputtooCustomer(CustomerBaseNewmodel, input));
                        }
                    }

                }
                else
                {
                    var Customer = customerBaseBLL.GetModel(input.F_CustomerID.Trim());
                    if (Customer != null)
                    {
                        if (!string.IsNullOrEmpty(input.F_Salesman))
                            Customer.F_Salesman = input.F_Salesman;
                        if (!string.IsNullOrEmpty(input.F_SalesPhone))
                            Customer.F_SalesPhone = input.F_SalesPhone;
                        if (!string.IsNullOrEmpty(input.F_Brands))
                            Customer.F_Brands = input.F_Brands;
                        if (!string.IsNullOrEmpty(input.F_CompanyName))
                            Customer.F_CompanyName = input.F_CompanyName.Trim();
                        if (!string.IsNullOrEmpty(input.F_Channel))
                            Customer.F_Channel = input.F_Channel;
                        if (!string.IsNullOrEmpty(input.F_AreaName))
                        {
                            Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                            try
                            {
                                pdModel = departmentBLL.GetModel(int.Parse(input.F_AreaName));
                            }
                            catch
                            {
                                pdModel = departmentBLL.GetModel(input.F_AreaName);
                            }
                            Customer.F_AreaID = pdModel.F_DeptId.ToString();
                        }
                        else
                        {
                            Customer.F_AreaID = "";
                        }

                        if (!string.IsNullOrEmpty(input.F_BranchName))
                        {
                            {
                                Model.T_Sys_Department pdModel = new Model.T_Sys_Department();
                                try
                                {
                                    pdModel = departmentBLL.GetModel(int.Parse(input.F_BranchName));
                                }
                                catch
                                {
                                    pdModel = departmentBLL.GetModel(input.F_BranchName);
                                }
                                Customer.F_BranchID = pdModel.F_DeptId.ToString();
                            }
                        }
                        else
                        {
                            Customer.F_BranchID = "";
                        }
                        if (!string.IsNullOrEmpty(input.F_CompanyName))
                            Customer.F_CompanyName = input.F_CompanyName;
                        customerBaseBLL  .Update(Customer);
                    }
                }

            }

            #region 基本字段
            if (!string.IsNullOrEmpty(input.F_MaterialID))
            {
                model.F_MaterialID = input.F_MaterialID.ToString();//物料编码为11为纯数字
            }
            model.F_Source = input.F_Source.ToString();//工单来源
          
            model.F_Type = input.F_Type.ToString();//工单类型:咨询及需求、投诉、抽检、其他(其它手动输入别的点选)
            model.F_Production = input.F_Production;//生产单位
            LogFactory.GetLogger("123").Debug(input.F_Production);
            model.F_CusName = input.F_CusName;//客户姓名
            model.F_CusPhone = input.F_CusPhone;//客户电话
            model.F_CompanyName = input.F_CompanyName;//公司名称
            model.F_IncidentProvince = input.F_IncidentProvince;//事发地-省
            model.F_IncidentCity = input.F_IncidentCity;//事发地-市
            model.F_IncidentCountry = input.F_IncidentCountry;//事发地-县
            model.F_IncidentTownship = input.F_IncidentTownship;//事发地-乡
            model.F_IncidentDetailed = input.F_IncidentDetailed;//事发地-详细
            model.F_SalesBase = input.F_SalesBase;//销售基地:新乡、新疆、九江、东北、其他(其它手动输入别的点选)
            model.F_Description = input.F_Description;//问题描述
            model.F_ZX_Area = input.F_ZX_Area;// 大区
            model.F_ZX_Branch = input.F_ZX_Branch;//分公司
            if (!string.IsNullOrEmpty(input.F_Files))
                model.F_Files = input.F_Files;//附件上传ids
            else
                model.F_Files = model.F_Files;//附件上传ids
            model.F_Brand = input.F_WorkerBrand;//
            model.F_DealType = model.F_DealType;//处理方式:当即办理、电话转接、网络转办（点选）
            model.F_Canal = input.F_Canal;//处理方式:当即办理、电话转接、网络转办（点选）
            #endregion
            model.F_QuestionType = input.F_QuestionType;//问题类别（投诉抽捡和咨询类别不一样）
            model.F_CustomerID = input.F_CustomerID;//客户编号为10为纯数字
            model.F_MaterialID = input.F_MaterialID;//物料编码为11为纯数字

            #region 投诉类
            model.F_BatchNumber = input.F_BatchNumber;//生产批次号
            model.F_TS_Formula = input.F_TS_Formula;// 投诉-配方
            model.F_TS_Category = input.F_TS_Category;//投诉-产品种类：化肥、化工、其他
            model.F_TS_Quantity = input.F_TS_Quantity;//投诉-问题数量（吨）
            model.F_TS_Level = input.F_TS_Level;//投诉-重要级别：轻微、一般、较大、重大
            #region 肥效类增加作物字段 20220307
            if (!string.IsNullOrEmpty(input.F_Crops))
            {
                model.F_Crops = input.F_Crops;
            }
            #endregion
            #endregion
            #region 咨询类
            //   model.F_ZX_ProName = input.F_ZX_ProName;//咨询-产品名称：三聚氰胺、甲醇、液氨、二甲醚、糠醇、其他
            model.F_ZX_Quantity = input.F_ZX_Quantity;// 咨询-问题数量（吨）

            #endregion
            #region 抽检类
            model.F_CJ_Time = input.F_CJ_Time;// 抽检-抽检时间
            model.F_CJ_Level = input.F_CJ_Level;// 抽检-抽检级别：乡镇级、县级、市级、省级及以上、个人送检
            model.F_CJ_Unit = input.F_CJ_Unit;// 抽检-抽检单位：市场监督、农业部、土肥站、工商、联合执法、其他
            model.F_CJ_TestUnit = input.F_CJ_TestUnit;//抽检-化验单位
            model.F_CJ_Tonnage = input.F_CJ_Tonnage;//抽检-抽检吨数
            model.F_CJ_BagNo = input.F_CJ_BagNo;//抽检-抽检袋数
            model.F_CJ_Outlay = input.F_CJ_Outlay;//抽检-公关费用金额：单位元】
            model.F_WxOpenId = input.F_WxOpenId;
           
            //     model.F_VisitRemarks = input.F_VisitRemarks;//回访备注
            //if (!string.IsNullOrEmpty(input.F_BatchNumber))
            //{
            //    if (type == 1)
            //    {
            //        model.F_SC_QualityMonth = new WorkOrderController().GetProTime(input.F_BatchNumber, DateTime.Parse(model.F_CreateOn.ToString())).ToString();
            //    }
            //    else
            //    {
            //        model.F_SC_QualityMonth = new WorkOrderController().GetProTime(input.F_BatchNumber, DateTime.Now).ToString();
            //    }
            //}

            if (type == 1)
            {
                model.F_State = model.F_State;//工单状态
                model.F_CreateOn = model.F_CreateOn;//添加时间
                model.F_CreateBy = model.F_CreateBy;//添加人
                model.F_UpdateBy = usercode;//修改人工号
                model.F_UpdateOn = DateTime.Now;//修改人工号
              
                if (input.F_UpdateCount != null)
                {
                    model.F_UpdateCount = model.F_UpdateCount + 1;//修改次数
                }
                else
                {
                    model.F_UpdateCount = 1;//修改次数
                }
                model.F_limit = model.F_limit;
            }
            else
            {
                model.F_limit = 0;
                model.F_State = (int)EnumWorkOrderState.neworder;
                model.F_State2= (int)EnumWorkOrderState.neworder;
                model.F_CreateBy = usercode;
                model.F_CreateOn = DateTime.Now;
            }
            model.F_IsVisit = 1;
            model.F_IsDelete = 0;
            model.F_IsOver = 0;
            #endregion
            return model;
        }
        /// <summary>
        /// 获取我参与的工单编号
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetCYWorkOrderID(string user)
        {
            string str = string.Empty;

            str = "select F_WoID from T_Wo_WorkOrderItem_New where F_CreateUser in(" + user + ") and F_OptType in( 1,3,13 )";

            return str;
        }
        /// <summary>
        /// 获取高层
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        public ActionResult GetHighlevel()
        {
            var user = userAccountBLL.GetModelList(" F_RoleId=61");
            if (user != null)
                return Success("获取高层信息成功", new
                {
                    user
                });
            return Error("获取高层信息失败");


        }
        /// <summary>
        /// 验证客户电话是否唯一
        /// </summary>
        private bool getunphone(int id, string phone)
        {
            var sql = " F_IsDelete=0 ";
            sql += "and (F_LegalPhone='" + phone + "')";
            if (id > 0)
                sql += " and F_CustomerId<>" + id;
            var count = customerBaseBLL.GetModelList(sql).Count();

            return count > 0;
        }
      
        /// <summary>
        /// 添加工单
        /// </summary>
        /// <returns></returns>
        public ActionResult CustomAdd(WorkOrderNewInput input, int overtime = 0, int sms = 0)
        {
                
                if (string.IsNullOrEmpty(input.F_CusName))
                    return Error("请输入客户姓名！");
                if (string.IsNullOrEmpty(input.F_CusPhone))
                    return Error("请输入客户电话！");
            
            if (input.F_Type == 3)
            {
                if (string.IsNullOrEmpty(input.F_Files))
                    return Error("请上传抽检单");
                if (string.IsNullOrEmpty(input.F_CJ_Time.ToString()))
                    return Error("请选择抽检时间");
            }
            if (!string.IsNullOrEmpty(input.F_SalesPhone))
            {
                if (!IsNumeric(input.F_SalesPhone))
                    return Error("请输入正确的业务员电话");
            }
            var model = new Model.T_Wo_WorkOrder();
                #region 保存客户基本信息
                model = inputtoobj(null , model, input, 2);
                model.F_State = (int)EnumWorkOrderState.customers;
                model.F_limit = overtime;
                #endregion
                long n = woBLL.Add(model);
                if (n > 0)
                {
                    #region 流转上一级领导审批
                    Model.T_Wo_WorkOrder modlelist = new BLL.T_Wo_WorkOrder().GetModel(n);
                    if (modlelist != null)
                    {
                    AddLog(modlelist.F_ID, 0, "客户" + "创建工单", (int)EnumItemType.deal, (int)EnumItemOpt.create, "", 0, null, overtime, sms);
                    return Success("添加成功");
                }
                    #endregion
                    return Success("添加成功！");
                }
                else
                    return Error("添加失败！");
        }
        /// <summary>
        /// 添加工单
        /// </summary>
        /// <returns></returns>
        public ActionResult Add(WorkOrderNewInput input, int overtime = 0, int sms = 0)
        {

            if (!string.IsNullOrEmpty(input.F_WxOpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + input.F_WxOpenId + "'").FirstOrDefault();
                //     string usercode = CurrentUser.UserData.F_UserCode;
                //   Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (ua == null && input.F_Source != 3)
                {
                    return Error("无操作权限！");
                   
                }
                if (input .F_Source !=3& input.F_Type  == 2 || input.F_Type == 5)
                {
                    if (string.IsNullOrEmpty(input.F_SalesBase))
                        return Error("请输入基地！");
                    if (string.IsNullOrEmpty(input.F_QuestionType))
                        return Error("请选择问题类别！");
                }


                //if (!string.IsNullOrEmpty(input.F_BatchNumber) && !vaBatchNumber(input.F_BatchNumber))
                //{
                //    return Error("请输入正确的生产批次号！");
                //}

                //else
                //{
                //    if (!string.IsNullOrEmpty(input.F_BatchNumber))
                //    {
                //        var prono = input.F_BatchNumber.Substring(0, 6);
                //        try
                //        {
                //            var pronos = DateTime.ParseExact(prono, "yyMMdd", null).ToString("yyyy-MM-dd");
                //            var protime = Convert.ToDateTime(pronos);
                //            if (DateTime.Parse(pronos) > DateTime.Now)
                //            {
                //                return Error("生产批次号错误，生产日期不能大于当前时间！");
                //            }

                //        }
                //        catch
                //        {
                //            return Error("生产批次号错误，日期格式错误！");
                //        }
                //    }
                //}

                if (!string.IsNullOrEmpty(input.F_CustomerID) && !valcode(input.F_CustomerID.ToString(), 10))
                    return Error("客户编号为10为纯数字！");
                if (!string.IsNullOrEmpty(input.F_MaterialID) && !valcode(input.F_MaterialID.ToString(), 11))
                    return Error("物料编码为11为纯数字！");
                if (string.IsNullOrEmpty(input.F_CusName))
                    return Error("请输入客户姓名！");
                if (string.IsNullOrEmpty(input.F_CusPhone))
                    return Error("请输入客户电话！");
              
                if (!string.IsNullOrEmpty(input.F_CustomerID))
                {
                    var Customer = customerBaseBLL.GetModel(input.F_CustomerID.Trim());
                    if (Customer == null)
                        return Error("无此客户编码！");
                }
                if (!string.IsNullOrWhiteSpace(input.F_MaterialID))
                {
                    var Customer = mmBLL.GetModel(input.F_MaterialID.Trim());
                    if (Customer == null)
                        return Error("无此物料编码！");
                }
                if (input.F_Type == 3)
                {
                    if (string.IsNullOrEmpty(input.F_Files))
                        return Error("请上传抽检单");
                    if (string.IsNullOrEmpty(input.F_CJ_Time.ToString()))
                        return Error("请选择抽检时间");
                    if (overtime==0)
                    {
                        overtime = 2160;
                    }
                }
                if (!string.IsNullOrEmpty(input.F_SalesPhone))
                {
                    if (!IsNumeric(input.F_SalesPhone))
                        return Error("请输入正确的业务员电话");
                }
                var model = new Model.T_Wo_WorkOrder();
                #region 保存客户基本信息
                model = inputtoobj(ua, model, input, 2);
                LogFactory.GetLogger("635").Debug("添加中。。。。");
                if (model.F_Source == "3")
                {
                    model.F_State = (int)EnumWorkOrderState.customers;
                }
                else
                {
                    model.F_State = (int)EnumWorkOrderState.audit;
                }
                model.F_limit = overtime;
               
                #endregion
                long n = woBLL.Add(model);
                if (n > 0)
                {
                    #region 流转上一级领导审批
                    Model.T_Wo_WorkOrder modlelist = new BLL.T_Wo_WorkOrder().GetModel(n);
                    if (modlelist != null)
                    {
                        if (ua != null && model.F_Source != "3")
                        {
                            if (GetUser(input.F_WxOpenId) != null)
                            {
                                var user = GetUser(input.F_WxOpenId);
                                string deptname = "", deptname1 = "";
                                var deptmodel = departmentBLL.GetModel(user.F_DeptId);
                                if (deptmodel != null)
                                {
                                    deptname = deptmodel.F_DeptName + "-";
                                }
                                var deptmodel1 = departmentBLL.GetModel(ua.F_DeptId);
                                if (deptmodel1 != null)
                                {
                                    deptname1 = deptmodel1.F_DeptName + "-";
                                }
                                AddLog(modlelist.F_ID, 0, deptname1 + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "创建工单", (int)EnumWorkOrderState.neworder, (int)EnumItemOpt.create, user.F_UserCode, user.F_DeptId, ua, overtime, sms );
                                AddLog(modlelist.F_ID, modlelist.F_State.Value, deptname + user.F_UserName + "(" + user.F_WorkNumber + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, user.F_UserCode, user.F_DeptId, ua, overtime, sms);
                                if (sms == 1 && !string.IsNullOrEmpty(user.F_Mobile))
                                {
                                    SendSms(model.F_Type, user.F_Mobile, ua.F_UserId);
                                }
                            }
                            else
                            {
                                string deptname1 = "";
                                int dapt = 0, nextda = 0;
                                string deptment = "";
                                var deptmodel1 = departmentBLL.GetModel(ua.F_DeptId);
                                if (deptmodel1 != null)
                                {
                                    deptname1 = deptmodel1.F_DeptName + "-";
                                    dapt = deptmodel1.F_ParentId;
                                    deptment = deptmodel1.F_DeptName;
                                }
                                AddLog(modlelist.F_ID, 0, deptname1 + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "创建工单", (int)EnumWorkOrderState.neworder, (int)EnumItemOpt.create, "", 0, ua, overtime, sms);
                                string opt = "";
                                //if (dapt != 0)
                                //{
                                if (CirculMarket(ua.F_DeptId, 11))
                                {
                                    nextda = 37;
                                    opt = "流转市场管理科";
                                }
                                else if (CirculMarket(ua.F_DeptId, 14))
                                {
                                    nextda = 57;
                                    opt = "流转营销管理处";
                                }
                                else if (CirculMarket(ua.F_DeptId, 15))
                                {
                                    nextda = 74;
                                    opt = "流转策划推广";
                                }
                                else if (CirculMarket(ua.F_DeptId, 16))
                                {
                                    nextda = 88;
                                    opt = "流转销售部";
                                }
                                else if (CirculMarket(ua.F_DeptId, 18))
                                {
                                    nextda = 268;
                                    opt = "流转车用尿素";

                                }

                                else if (CirculMarket(ua.F_DeptId, 20))
                                {
                                    nextda = 295;
                                    opt = "流转新乡黑科质检";
                                }
                                else if (CirculMarket(ua.F_DeptId, 332))
                                {
                                    nextda = 339;
                                    opt = "流转营销管理处";


                                } 
                                else if (ua.F_DeptId == 17 || ua.F_DeptId == 19 || ua.F_DeptId == 20 || ua.F_DeptId == 21)
                                    {
                                        nextda = ua.F_DeptId;
                                        opt = "流转" + deptment;
                                    }
                                //}
                                if (nextda != 0)
                                {
                                    var res = AssignWO(ua, modlelist, input, opt, "", nextda, 0, overtime, sms,0,0,0,"",1);
                                    if (res)
                                        return Success("添加成功");
                                    else
                                        return Error("流转失败！");
                                }
                                else
                                {
                                    return Error("流转失败！");
                                }

                        }
                    }
                        else
                        {
                            AddLog(modlelist.F_ID, 0, "客户" + "创建工单", (int)EnumItemType.deal, (int)EnumItemOpt.create, "", 0, null, overtime, sms);
                            LogFactory.GetLogger("456").Debug("添加成功");
                            return Success("添加成功");
                        }

                    }
                    #endregion
                    return Success("添加成功！");
                }
                else
                    return Error("添加失败！");



            }
            else
            {
                return Error("OpenId不能为空！");
            }
        }
        /// <summary>
        /// 更新市场管理科，质量管理科                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
        /// </summary>
        /// <param name="model"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        private Model.T_Wo_WorkOrder InToworkModel(Model.T_Wo_WorkOrder model, WorkOrderNewInput input)

        {
            if (!string.IsNullOrEmpty(input.F_SC_ProductBase))
                model.F_SC_ProductBase = input.F_SC_ProductBase;//市场管理科-生产基地（新乡、新疆、九江、东北、贴牌、无法确定）
            if (!string.IsNullOrEmpty(input.F_SC_PreliminaryOpinion))
                model.F_SC_PreliminaryOpinion = input.F_SC_PreliminaryOpinion;// 市场管理科-初审意见:退货、换货、补偿、自行处理
            if (!string.IsNullOrEmpty(input.F_SC_QualityMonth))
                model.F_SC_QualityMonth = input.F_SC_QualityMonth;//市场管理科-超出质保期限（算法：工单创建日期-生产日期，生产日期根据生产批次号获取，单位：月）
            if (!string.IsNullOrEmpty(input.F_SC_CJ_SpotResult))
                model.F_SC_CJ_SpotResult = input.F_SC_CJ_SpotResult;/// 市场管理科-抽检-抽检结果（视同合格、合格、不合格、复检后合格、未送检）
            if (!string.IsNullOrEmpty(input.F_SC_CJ_SelfResult))
                model.F_SC_CJ_SelfResult = input.F_SC_CJ_SelfResult;//市场管理科-抽检-自检结果
            if (!string.IsNullOrEmpty(input.F_SC_CJ_ApprovalNo))
                model.F_SC_CJ_ApprovalNo = input.F_SC_CJ_ApprovalNo;// 市场管理科-抽检-对应审批工作流单号
            if (!string.IsNullOrEmpty(input.F_SC_CJ_ReturnAccount))
                model.F_SC_CJ_ReturnAccount = input.F_SC_CJ_ReturnAccount;//市场管理科-抽检-确认返账金额（元）
            if (!string.IsNullOrEmpty(input.F_ZL_QualityEventLevel))
                model.F_ZL_QualityEventLevel = input.F_ZL_QualityEventLevel;// 质量管理科-质量事件等级（未遂、一般、较大、重大）
            if (!string.IsNullOrEmpty(input.F_ZL_ClaimAmount))
                model.F_ZL_ClaimAmount = input.F_ZL_ClaimAmount;//质量管理科-索赔金额（单位元，对应责任单位）
            if (!string.IsNullOrEmpty(input.F_ZL_ResponsibleUnit))
                model.F_ZL_ResponsibleUnit = string.IsNullOrEmpty(model.F_ZL_ResponsibleUnit) ? input.F_ZL_ResponsibleUnit : model.F_ZL_ResponsibleUnit + "；" + input.F_ZL_ResponsibleUnit;//质量管理科-责任单位（需列出，可选多个）
            if (!string.IsNullOrEmpty(input.F_ZL_ApprovalOpinions))
                model.F_ZL_ApprovalOpinions = input.F_ZL_ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
            if (!string.IsNullOrEmpty(input.F_ZL_ApprovalDisagree))
                model.F_ZL_ApprovalDisagree = input.F_ZL_ApprovalDisagree;// 质量管理科-审批不同意意见
            if (!string.IsNullOrEmpty(input.F_ZL_CompensationMethod))
                model.F_ZL_CompensationMethod = input.F_ZL_CompensationMethod;//质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
            if (!string.IsNullOrEmpty(input.F_ZL_CompensationMoney))
                model.F_ZL_CompensationMoney = input.F_ZL_CompensationMoney;// 质量管理科-补偿钱款
            if (!string.IsNullOrEmpty(input.F_ZL_CResponsibleUnits))
                model.F_ZL_CResponsibleUnits = input.F_ZL_CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
            if (!string.IsNullOrEmpty(input.F_ZL_Fquantity))
                model.F_ZL_Fquantity = input.F_ZL_Fquantity;// 质量管理科-确认实收数量（吨）
            if (!string.IsNullOrEmpty(input.F_ZL_ImprovementRequirements))
                model.F_ZL_ImprovementRequirements = string.IsNullOrEmpty(model.F_ZL_ImprovementRequirements) ? input.F_ZL_ImprovementRequirements : model.F_ZL_ImprovementRequirements + "；" + input.F_ZL_ImprovementRequirements;//质量管理科-改进要求
            if (!string.IsNullOrEmpty(input.F_ZL_CApprovalNo))
                model.F_ZL_CApprovalNo = input.F_ZL_CApprovalNo;//质量管理科-对应审批工作流单号
            if (!string.IsNullOrEmpty(input.F_ZL_CJ_IsRecord))
                model.F_ZL_CJ_IsRecord = input.F_ZL_CJ_IsRecord;//质量管理科-抽检-未备案、已备案
            if (input.F_IsVisit != null)
            {
                try
                {
                    model.F_IsVisit = int.Parse(input.F_IsVisit);
                }
                catch
                {
                    model.F_IsVisit = 1;
                }

            }

            if (!string.IsNullOrEmpty(input.F_CarNumber))//返厂车牌号
                model.F_CarNumber = input.F_CarNumber;
            if (input.F_LoadingFee > 0)//装车费
                model.F_LoadingFee = input.F_LoadingFee;
            if (input.F_UnLoadingFee > 0) //卸车费
                model.F_UnLoadingFee = input.F_UnLoadingFee;
            if (input.F_MaterialFee > 0) //返料费
                model.F_MaterialFee = input.F_MaterialFee;
            //if (!string.IsNullOrEmpty(input.F_EventReason))
            //    model.F_EventReason = input.F_EventReason;//质量管理科-事件原因
            if (!string.IsNullOrEmpty(input.F_DrivePhone))
                model.F_DrivePhone = input.F_DrivePhone;//电话号码
            if (!string.IsNullOrEmpty(input.F_WorkmanShip))
                model.F_WorkmanShip = input.F_WorkmanShip;//质量管理科-工艺
            if (!string.IsNullOrEmpty(input.F_Manufacturers))
                model.F_Manufacturers = input.F_Manufacturers;//质量管理科-原料及厂家
            if (input.F_ProductionNum > 0)
                model.F_ProductionNum = input.F_ProductionNum;//质量管理科-该批次生产数量

            return model;
        }
        /// <summary>
        /// 指派/转派工单
        ///  <param name="orderid">工单id</param>
        /// <param name="cont">指派说明</param>
        ///  <param name="clbm">指派部门</param>
        ///  <param name="clid">指派人</param>
        /// </summary>
        /// <returns></returns>
        [WechatActionFilter]
        public ActionResult AssignWorkOrder(string OpenId, long orderid, string cont, WorkOrdeDeptment deptment, string F_Files, int isvisit = 1,
            int overtime = 0, int sms = -1, int clbm = 0, int clid = 0, int isApprovalp = 0, int hclbm = 0, int hclid = 0, int clbm2 = 0, int clid2 = 0,string jsonstr="")
        {

            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
                if (model == null)
                {
                    return Error("工单不存在！");
                }
                if (model.F_State == 1 && model.F_CreateBy == ua.F_UserCode)
                {
                    return Error("工单已转派请勿重复操作！");
                }
                if (model .F_State !=0)
                {
                    var modellist = new BLL.T_Wo_WorkOrderItem_New().GetModelList("F_WoID=" + model.F_ID + "and F_IsUsed=0 order by   F_ID desc ").FirstOrDefault();
                    if (modellist != null)
                    {
                        if (modellist.F_NextUser != ua.F_UserCode)
                            return Error("非接单人不可操作工单");
                    }
                }
               if (sms ==-1)
                {
                    var itemlast = itembll.GetModelList("   F_WoID='" + model.F_ID + "' order by F_ID desc").FirstOrDefault();
                     sms = (int)itemlast.F_IsSMS;
                }
                WorkOrderNewInput input = new WorkOrderNewInput();

                if (ua != null)
                {
                    Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                    if (clid != 0)
                    {
                        Model.T_Sys_UserAccount clus = userAccountBLL .GetModel(clid);

                        if (clus != null)
                        {
                            if (clus.F_WorkNumber == "7000")
                                return Error("不能转派到市场管理员");
                            else if (clus.F_RoleId == 1 || clus.F_RoleId == 4)
                                return Error("不能转派到话务人员");
                            else if (clus.F_RoleId == 58)
                                return Error("不能转派到业务员");
                            else if (clus.F_RoleId == 60)
                                return Error("不能转派到分公司经理");
                            else if (clus.F_RoleId == 62)
                                return Error("不能转派到大区经理");
                        }

                    }
                    if (hclid == 0 && hclbm == 0 && isApprovalp != 0)
                    {
                        return Error("请选择接收部门");
                    }
                    if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                    {
                        if ((clbm == 0 && clid == 0) || (clbm2 == 0 && clid2 == 0))
                        {
                            return Error("请选择接收部门");
                        }
                    }
                    else
                    {
                        if (clbm == 0 && clid == 0)
                        {
                            return Error("请选择接收部门");
                        }
                        else
                        {
                            var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                            if (deptmodel != null)
                            {
                                if (model != null)
                                {
                                    if (deptmodel.F_DeptId == 12 || deptmodel.F_DeptId == 36)
                                    {
                                        input.F_WorkmanShip = deptment.WorkmanShip;//质量管理科-工艺
                                        input.F_Manufacturers = deptment.Manufacturers;//质量管理科-原料及厂家
                                        input.F_ProductionNum = deptment.ProductionNum;//质量管理科-该批次生产数量
                                    }
                                    if (model.F_Type == "2" || model.F_Type == "5")
                                    {
                                        if (deptmodel.F_DeptId == 37)
                                        {
                                            // input. F_SC_QualityMonth = QualityMonth;//市场管理科-超出质保期限
                                            input.F_SC_PreliminaryOpinion = deptment.PreliminaryOpinion;//市场管理科-初审意见:退货、换货、补偿、自行处理
                                        }
                                        else if (deptmodel.F_DeptId == 12 || deptmodel.F_DeptId == 36)
                                        {
                                            input.F_IsVisit = isvisit.ToString();
                                            input.F_ZL_QualityEventLevel = deptment.QualityEventLevel;//质量管理科-质量事件等级（未遂、一般、较大、重大）
                                            input.F_ZL_ClaimAmount = deptment.ClaimAmount;// 质量管理科-索赔金额（单位元，对应责任单位）
                                            input.F_ZL_ApprovalOpinions = deptment.ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
                                            input.F_ZL_ApprovalDisagree = deptment.ApprovalDisagree;// 质量管理科-审批不同意意见
                                            input.F_ZL_CompensationMethod = deptment.CompensationMethod;// 质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
                                            input.F_ZL_CompensationMoney = deptment.CompensationMoney;// 质量管理科-补偿钱款
                                            input.F_ZL_CResponsibleUnits = deptment.CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
                                            //input.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                                            //input.F_ZL_ImprovementRequirements = deptment.ImprovementRequirements;//  质量管理科-改进要求
                                            input.F_ZL_CApprovalNo = deptment.CApprovalNo;// 质量管理科-对应审批工作流单号
                                            //if (string.IsNullOrEmpty(deptment.EventReason))
                                            //    return Error("请填写事件原因！");
                                            //if (string.IsNullOrEmpty(deptment.ResponsibleUnit))
                                            //    return Error("请填写责任单位！");
                                            //input.F_EventReason = deptment.EventReason;// 质量管理科-事件原因
                                            input.F_ZL_ResponsibleUnit = deptment.ResponsibleUnit;// 质量管理科-责任单位（需列出，可选多个）

                                        }
                                        else if (deptmodel.F_DeptName == "成品库" && model.F_SC_PreliminaryOpinion == "退换货" ) //退换货成品库录入物料信息
                                        {
                                            if (!string.IsNullOrEmpty(jsonstr))
                                            {
                                                JavaScriptSerializer Serializer = new JavaScriptSerializer();   //实例化⼀个能够序列化数据的类
                                                List<Material> list = Serializer.Deserialize<List<Material>>(jsonstr);
                                                List<T_Wo_MaterialItems> itemlist = new List<T_Wo_MaterialItems>();

                                                if (list != null && list.Count > 0)
                                                {
                                                    foreach (var item in list)
                                                    {
                                                        T_Wo_MaterialItems itemodel = new T_Wo_MaterialItems();
                                                        itemodel.F_MaterialCode = item.materialcode;
                                                        itemodel.F_MaterialName = item.materialname;
                                                        itemodel.F_Formula = item.formula;
                                                        itemodel.F_ReturnQuantity = item.returnum??0;
                                                        itemodel.F_WoID = model.F_ID;//工单id
                                                        itemodel.F_CreateOn = DateTime.Now;
                                                        itemodel.F_Remark = item.specs;//规格
                                                        itemlist.Add(itemodel);
                                                    }
                                                    model.MaterialItems = itemlist;
                                                }
                                            }

                                        }
                                        else if (deptmodel.F_DeptId == 248 && model.F_SC_PreliminaryOpinion == "退换货")
                                        {
                                            input.F_CarNumber = deptment.CarNumber;//返厂车牌号
                                            input.F_LoadingFee = deptment.LoadingFee;//装车费
                                            input.F_UnLoadingFee = deptment.UnLoadingFee;//卸车费
                                            input.F_MaterialFee = deptment.MaterialFee;//返料费
                                            input.F_DrivePhone = deptment.DrivePhone;//电话号码
                                            if (!string.IsNullOrEmpty(jsonstr))
                                            {
                                                JavaScriptSerializer Serializer = new JavaScriptSerializer();   //实例化⼀个能够序列化数据的类
                                                List<Material> list = Serializer.Deserialize<List<Material>>(jsonstr);
                                                List<T_Wo_MaterialItems> itemlist = new List<T_Wo_MaterialItems>();

                                                if (list != null && list.Count > 0)
                                                {
                                                    foreach (var item in list)
                                                    {
                                                        T_Wo_MaterialItems itemodel = new T_Wo_MaterialItems();
                                                        if (!string.IsNullOrEmpty(item.fid))
                                                        {
                                                            itemodel.F_Id = Convert.ToInt32(item.fid);
                                                        }
                                                        itemodel.F_MaterialCode = item.materialcode;
                                                        itemodel.F_MaterialName = item.materialname;
                                                        itemodel.F_Formula = item.formula;
                                                        itemodel.F_ReturnQuantity = item.returnum ?? 0;
                                                        itemodel.F_WoID = model.F_ID;//工单id
                                                        itemodel.F_CreateOn = DateTime.Now;
                                                        itemodel.F_Remark = item.specs;//规格
                                                        itemlist.Add(itemodel);
                                                    }
                                                    model.MaterialItems = itemlist;
                                                }

                                            }
                                        }
                                        //else if (deptmodel.F_DeptName == "销售内勤" && (model.F_SC_PreliminaryOpinion == "退货" || model.F_SC_PreliminaryOpinion == "换货"))//部门id=193
                                        //{
                                        //    model.F_SC_CJ_ReturnAccount = deptment.ReturnAccount;//销售内勤-确认返账金额                               
                                        //}

                                    }
                                    else if (model.F_Type == "3")
                                    {
                                        if (deptmodel.F_DeptId == 37)
                                        {

                                            input.F_SC_CJ_SpotResult = deptment.SpotResult;//市场管理科-抽检-抽检结果（视同合格、合格、不合格、复检后合格、未送检）
                                            input.F_SC_CJ_SelfResult = deptment.SelfResult;//市场管理科-抽检-自检结果
                                            input.F_SC_CJ_ApprovalNo = deptment.ApprovalNo;//市场管理科-抽检-对应审批工作流单号
                                            input.F_SC_CJ_ReturnAccount = deptment.ReturnAccount;//市场管理科-抽检-确认返账金额
                                        }
                                        else if (deptmodel.F_DeptId == 12)
                                        {
                                            input.F_IsVisit = isvisit.ToString();
                                            input.F_ZL_CJ_IsRecord = deptment.IsRecord;//质量管理科-抽检-未备案、已备案
                                            input.F_ZL_ClaimAmount = deptment.ClaimAmount;// 质量管理科-索赔金额（单位元，对应责任单位）
                                        }
                                    }
                                    if (deptmodel.F_DeptName == "销售内勤")//部门id=193
                                    {
                                        input.F_SC_CJ_ReturnAccount = deptment.ReturnAccount2;//销售内勤-确认返账金额                               
                                    }
                                    if (deptmodel.F_DeptId == 260)//销售财务
                                    {
                                        input.F_SC_CJ_ReturnAccount = deptment.ReturnAccount3;//销售内勤-确认返账金额                               
                                    }
                                    if (deptmodel.F_DeptId == 36)
                                    {
                                        input.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                                    }
                                }
                                else
                                    return Error("工单不存在！");
                            }
                            else
                            {
                                return Error("请选择接收部门");
                            }
                        }
                    }

                    if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                    {
                        var res = AssignWO(ua, model, input, cont, F_Files, clbm, clid, overtime, sms, isApprovalp, hclbm, hclid);
                        var res1 = AssignWO(ua, model, input, cont, F_Files, clbm2, clid2, overtime, sms, isApprovalp, hclbm, hclid, "", 0, 2);
                        if (res && res1)
                        {
                            return Success("转派成功");
                        }
                        else
                            return Error("转派失败！");
                    }
                    else
                    {
                        var res = AssignWO(ua, model, input, cont, F_Files, clbm, clid, overtime, sms, isApprovalp, hclbm, hclid, "", 0, ua.F_Flag);
                        if (res)
                        {
                            return Success("转派成功");
                        }
                        else
                            return Error("转派失败！");
                    }

                }
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 转派工单
        /// </summary>
        public bool AssignWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, WorkOrderNewInput input, string cont, string F_Files, int clbm = 0, int clid = 0, int overtime = 0, int sms = 0, int isApprovalp = 0, int hclbm = 0, int hclid = 0, string creat = "",int  isbl=0, int flag = 1)
        {

            if (model.F_limit > 0)
                overtime = model.F_limit;
            string smscont = "";
            if (model.F_Type == "1")
            {
                smscont = "咨询";
            }
            else if (model.F_Type == "2")
            {
                smscont = "投诉";
            }
            else if (model.F_Type == "3")
            {
                smscont = "抽检";
            }
            else if (model.F_Type == "5")
            {
                smscont = "业务协办";
            }
            else
            {
                smscont = "建议";
            }
            string[] mag = { smscont };
            string smsmsg = "您好，您有一条新的" + smscont + "工单，请及时接单处理！";
            string touser = ""; string tousername = "";
            #region 获取接收人
            int deptid = 0;
            if (clid != 0)
            {
                Model.T_Sys_UserAccount clus = userAccountBLL.GetModel(clid);
                deptid = clus.F_DeptId;
                clbm = clus.F_DeptId;
                if (clus != null)
                {
                    touser = clus.F_UserCode;
                    tousername = clus.F_UserName + "(" + clus.F_WorkNumber + ")";
                }
                if (sms != 0)
                {
                    if (!string.IsNullOrEmpty(clus.F_Mobile))
                    {
                        SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, clus.F_Mobile);
                        bool n = new SMSController().AddSmS(clus.F_Mobile, smsmsg, nowUser.F_UserId);
                    }

                }
            }
            else
            {
                string users = string.Empty;
                deptid = clbm;
                string sql = "";
                if  (isbl>0)
                {
                    sql = " and F_RoleId in(select F_RoleId from T_Sys_RoleInfo where  F_RoleCode='BLRY')";
                }
                var list = userAccountBLL.GetModelList(" F_DeptId='" + clbm + "'and F_DeleteFlag=0" + sql);
                foreach (var l in list)
                {
                    if (string.IsNullOrEmpty(users))
                    {
                        users = l.F_UserCode;
                        tousername = l.F_UserName + "(" + l.F_WorkNumber + ")";
                    }
                    else
                    {
                        users = users + "," + l.F_UserCode;
                        tousername = tousername + "," + l.F_UserName + "(" + l.F_WorkNumber + ")";
                    }
                    if (sms != 0)
                    {
                        if (!string.IsNullOrEmpty(l.F_Mobile))
                        {
                            SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, l.F_Mobile);
                            bool n = new SMSController().AddSmS(l.F_Mobile, smsmsg, nowUser.F_UserId);
                        }

                    }
                }

                touser = users;
            }
            string htouser = "", htousername = "";
            if (isApprovalp != 0 && nowUser.F_DeptId == 37)
            {
                if (hclid != 0)
                {
                    Model.T_Sys_UserAccount clus = userAccountBLL.GetModel(hclid);
                    if (clus != null)
                    {
                        if (string.IsNullOrEmpty(htouser))
                        {
                            htouser = clus.F_UserCode;
                            htousername = clus.F_UserName + "(" + clus.F_WorkNumber + ")";
                        }
                    }
                }
                else
                {
                    var list = userAccountBLL.GetModelList(" F_DeptId='" + hclbm + "'");
                    foreach (var l in list)
                    {
                        if (string.IsNullOrEmpty(htouser))
                        {
                            htouser = l.F_UserCode;
                            htousername = l.F_UserName + "(" + l.F_UserCode + ")";
                        }
                        else
                        {
                            htouser = htouser + "," + l.F_UserCode;
                            htousername = htousername + "," + l.F_UserName + "(" + l.F_WorkNumber + ")";
                        }
                    }
                }
                AddLog(model.F_ID, (int)EnumWorkOrderState.assign, htousername + "高层待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, htouser, hclbm, nowUser, overtime, sms, creat, 2);
            }

            #region 财务审核后，填单人员可以收到到账提醒（短信到账提醒）20220217
            if (nowUser.F_DeptId == 260)
            {
                var noticlus = userAccountBLL.GetModel(model.F_CreateBy);
                if (!string.IsNullOrEmpty(noticlus.F_Mobile))
                {
                    //SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, noticlus.F_Mobile.Trim());
                    //bool n = new SMSController().AddSmS(noticlus.F_Mobile.Trim(), "返款已到账", nowUser.F_UserId);
                }
            }
            #endregion

            #endregion
            #region 工单处理
            var opt = "指派";
            int optbut = (int)EnumItemOpt.assign;
            int wostate = (int)EnumWorkOrderState.assign;//已指派待接单
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var optcont = "";
            if (!string.IsNullOrEmpty(cont))
                optcont = "，说明：" + cont;
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "工单给 " + tousername + optcont;
            var itemid = AddLog(model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, touser, clbm, nowUser, overtime, sms, creat,0,flag);
            if (itemid > 0)
            {
                #region 处理工单
                //工单完结要更新工单的状态
                //   model.F_DealBy = touser;
                if (flag == 1)
                {
                    model.F_State = wostate;
                }
                else if (flag == 2)
                {
                    model.F_State2 = wostate;
                }
                if (model.F_limit == 0)
                    model.F_limit = overtime;
                //处理内容
                if (!string.IsNullOrEmpty(cont))
                    if (flag == 2)
                    {
                        model.F_DealContent2 += cont + "；";
                    }
                    else
                    {
                        model.F_DealContent += cont + "；";
                    }
                InToworkModel(model, input);

                if (!string.IsNullOrEmpty(F_Files))
                {
                    if (!string.IsNullOrEmpty(model.F_Files))
                        model.F_Files = model.F_Files + "," + F_Files;
                    else
                        model.F_Files = F_Files;
                }
                woBLL.Update(model);
                #region 添加物料信息
                if (model.MaterialItems != null && model.MaterialItems.Count > 0)
                {
                    //var delmodels = new BLL.T_Wo_MaterialItems().GetModelList($" F_WoID ={ model.F_ID}");
                    //if (delmodels != null && delmodels.Count > 0)
                    //{
                    //    string delids = string.Join(",", delmodels.Select(p => p.F_Id).ToArray());
                    //    new BLL.T_Wo_MaterialItems().DeleteList(delids);
                    //}
                    foreach (var item in model.MaterialItems)
                    {
                        if (item.F_Id > 0)
                        {
                            new BLL.T_Wo_MaterialItems().Update(item);
                        }
                        else
                        {
                            new BLL.T_Wo_MaterialItems().Add(item);
                        }
                    }
                }
                #endregion
                #endregion
                #region 推送消息
                #region 推送消息给添加的坐席 -转派和处理
                if (nowUser.F_UserCode != model.F_CreateBy)
                {
                    sendsysmsg(model, nowUser, model.F_CreateBy, (int)model.F_ID, opt);//推送系统消息
                 //   var createmodel = userAccountBLL.GetModel(model.F_CreateBy);  //被指派人
                  //  if (createmodel != null)
                  //  {
                      //  if (!string.IsNullOrEmpty(createmodel.F_WxOpenId))
                      //  {
                          //  sendwxmsg(model, createmodel.F_WxOpenId, nowUser, opt);
                      //  }
                   // }
                }
                #endregion
                #region 向下一级操作人员推送消息
                if (!string.IsNullOrWhiteSpace(touser))
                {
                    sendsysmsg(model, nowUser, touser, (int)model.F_ID, opt);//推送系统消息
                 //   var modelUser2 = userAccountBLL.GetModel(touser);  //被指派人
                 //   if (modelUser2 != null)
                  //  {
                       // if (!string.IsNullOrEmpty(modelUser2.F_WxOpenId))
                      //  {
                          //  sendwxmsg(model, modelUser2.F_WxOpenId, nowUser, "指派");
                      //  }
                    //}
                }
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        /// <summary>
        /// 查询超时工单列表
        /// </summary>
        [WechatActionFilter]
        public ActionResult GetOvertime(string OpenId, string code, string keywords, string cusname, string cusphone, string companyname, string province, string city,
            string country, string township, string touser, int source = 0, int type = 0, int pageindex = 1, int pagesize = 10, int state = 0)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
               if (ua == null)
               {
                return Success("你的账号已在别处登录，你确定要再次登录吗？");
            }
                if (!Refresh() || !Refresh2())
                {
                    return Error("查询失败");
                }
                string sql = $" and F_IsDelete=0";
              //  sql += "and F_Type !=3";
                DataTable dt = new DataTable();
                #region 筛选条件
                if (type > 0 && type < 6)//工单类型
                    sql += $" and F_Type=" + type;
                if (source > 0)//工单来源
                {
                    if (source == 1)
                        sql += $" and F_Source in (1,'')";
                    else
                        sql += $" and F_Source='" + source + "'";
                }

                if (!string.IsNullOrWhiteSpace(touser))//参与人
                    sql += $" and F_DealBy like '%" + touser.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(code))//工单编号
                    sql += $" and F_WorkOrderCode like '%" + code.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(keywords))//关键字搜索
                    sql += $"  and (F_WorkOrderCode like '%" + keywords.Trim() + "%' or F_CusName like '%" + keywords.Trim() + "%'or F_CusPhone like '%" + keywords.Trim() + "%'  )";
                if (!string.IsNullOrWhiteSpace(cusname))//客户姓名
                    sql += $" and F_CusName like '%" + cusname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(cusphone))//客户电话
                    sql += $" and F_CusPhone like '%" + cusphone.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(companyname))//公司名称
                    sql += $" and F_CompanyName like '%" + companyname.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//省
                    sql += $" and F_IncidentProvince like '%" + province.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//市
                    sql += $" and F_IncidentCity like '%" + city.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//县
                    sql += $" and F_IncidentCountry like '%" + country.Trim() + "%'";
                if (!string.IsNullOrWhiteSpace(province))//乡
                    sql += $" and F_IncidentTownship like '%" + township.Trim() + "%'";
                //sql += $" and F_State in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," +
                //(int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + ")";
                sql += $" and F_IsOver=" + 1;
                Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                if (state > 0)
                {
                    sql += $" and F_State =" + state;
                }
                if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                {
                    sql += $" and((F_IsOver in(1,3) and F_State !=11) or ( F_IsOver in (2,3) and  F_State2!=11))";
                }
                else if (ua.F_Flag == 1)
                {
                    sql += $" and F_IsOver in (1,3)";
                    sql += $" and F_State !=" + 11;
                }
                else if (ua.F_Flag == 2)
                {
                    sql += $" and  F_IsOver in (2,3)";
                    sql += $" and F_State2 !=" + 11;
                }
                if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "YWY" || ro.F_RoleCode == "BLRY")
                {
                    sql += $" and F_DealBy like '%" + ua.F_UserCode.Trim() + "%'";
                }
                else if (ro.F_RoleCode == "DQJL" || ro.F_RoleCode == "FGSJL" || ro.F_RoleCode == "ZG")
                {
                    string detpid = "" + ua.F_DeptId;
                    var deparmentlist = new List<Model.T_Sys_Department>();
                    Model.T_Sys_Department dModel = departmentBLL.GetModel(ua.F_DeptId);
                    if (dModel != null)
                    {
                        if (dModel.F_Layer == 1)
                        {
                            deparmentlist = new BLL.T_Sys_Department().GetModelList(" F_State=1 and F_Layer=" + 2 + " and F_ParentId=" + dModel.F_DeptId);
                            if (deparmentlist.Count > 0)
                            {
                                foreach (var it in deparmentlist)
                                {
                                    if (detpid != "")
                                    {
                                        detpid += "," + it.F_DeptId;
                                    }
                                    else
                                    {
                                        detpid = "" + it.F_DeptId; ;
                                    }
                                }
                            }
                        }
                        else
                        {
                            detpid = ua.F_DeptId.ToString();
                        }
                        if (GetDeptWorkOrderID(detpid, "" + (int)EnumWorkOrderState.dealing + ", " + (int)EnumWorkOrderState.receive + "," +
                (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + "") != "")
                        {
                            sql += $"  and T_Wo_WorkOrder.F_ID in ( " + GetDeptWorkOrderID(detpid, "" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," +
                (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + "") + ") "; ;
                        }
                        else
                        {

                            return Success("暂无工单"); ;
                        }

                    }
                    else
                    {
                        return Error("加载失败");
                    }
                }
                else if (ro.F_RoleCode == "JDYBZZX")
                {
                    sql += $" and F_CreateBy like '%" + ua.F_UserCode.Trim() + "%'";
                }
                else if (ro.F_RoleCode == "QTJS")
                {
                    return Error("无操作权限！");
                }
                #endregion
                #region 退换货的工单按未超期处理 20220302
                sql += $" and  F_ID not in (select F_ID from T_Wo_WorkOrder where F_SC_PreliminaryOpinion='退换货')";
                #endregion
                int recordCount = 0;
                if (!string.IsNullOrWhiteSpace(sql))
                {

                    dt = BLL.PagerBLL.GetListPager(
                        "T_Wo_WorkOrder",
                        "F_ID",
                        "*",
                        sql,
                        "ORDER BY T_Wo_WorkOrder.F_ID desc",
                        pagesize,
                        pageindex,
                        true,
                        out recordCount);
                }
                List<long> woid = new List<long>();
                List<Model.T_Wo_WorkOrder> modlelist = new BLL.T_Wo_WorkOrder().DataTableToList(dt);
                List<WorkOrderNewInput> Input = modeltooip(modlelist, ua);
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = Input,
                    total = recordCount
                };
                return Content(obj.ToJson()); ;
            }
            else
            {
                return Error("无操作权限！");
            }
        }

        /// 是否超时
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool TimeforOver(int id, int flag = 1)
        {
            string strsql = "";
            if (flag == 1)
            {
                strsql = " and F_Type in(1,3)";
            }
            else if (flag == 2)
            {
                strsql = " and F_Type in(2,3)";
            }
            var itemlasts = itembll.GetModelList("  F_WoID=" + id + strsql + "");
            string time1 = "", time2 = ""; int x = 0, y = 0;
            float time = 0;
            if (itemlasts.Count > 0)
            {
                for (int z = 0; z < itemlasts.Count; z++)
                {
                    if (itemlasts[z].F_WoState >= 1)
                    {
                        if (itemlasts[z].F_WoState == 1)
                        {
                            x = z;
                            time1 = itemlasts[z].F_CreateTime.ToString();
                            time = float.Parse(itemlasts[z].F_LimitTime);
                            break; ;
                        }
                    }
                }
                for (int i = 0; i < itemlasts.Count; i++)
                {
                    if (itemlasts[i].F_WoState >= 1)
                    {
                      
                        if (itemlasts[i].F_WoState == 10)
                        {
                            y = i;
                            time2 = itemlasts[i].F_CreateTime.ToString();
                        }
                    }
                }
                if (time2 != "")
                {
                    if (time1 != "")
                    {
                        if (y > x )
                        {
                            System.TimeSpan a = DateTime.Parse(time2) - DateTime.Parse(time1);
                            if ((float)a.TotalHours > time)
                            {
                                return false;
                            }
                        }
                        else
                        {
                            System.TimeSpan a = DateTime.Now - DateTime.Parse(time1);
                            if ((float)a.TotalHours > time)
                            {
                                return false;
                            }
                        }
                    }
                    else
                    {
                        return true;
                    }
                }
                else if (time1 != "")
                {
                    System.TimeSpan a = DateTime.Now - DateTime.Parse(time1);
                    if ((float)a.TotalHours > time)
                    {
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return true;
            }
            return true;
        }

        /// <summary>
        /// 接单 - 确认工单
        /// </summary>
        /// <returns></returns>

        [WechatActionFilter]
        public ActionResult SureWorkOrder(long orderid, string OpenId)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                if (ua != null)
                {

                    Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
                    if (model != null)
                    {
                        string strsql = "";
                        if (ua.F_Flag == 1)
                        {
                            strsql = " and F_Type in(1,3)";
                        }
                        else if (ua.F_Flag == 2)
                        {
                            strsql = " and F_Type in(2,3)";
                        }

                        var modellist = new BLL.T_Wo_WorkOrderItem_New().GetModelList("F_WoID=" + model.F_ID + "and F_IsUsed=0 " + strsql + "  order by  F_ID desc ").FirstOrDefault();
                        if (modellist != null)
                        {
                            if (!string.IsNullOrEmpty(modellist.F_NextUser))
                            {
                                string[] sprt = modellist.F_NextUser.Split(',');
                                if (sprt.Length == 1)
                                {
                                    if (modellist.F_NextUser != ua.F_UserCode)
                                        return Error("非接单人不可操作工单");
                                }
                            }

                        }
                        if (ua.F_Flag == 1)
                        {
                            if (model.F_State == 2)
                                return Error("工单已接单无需重新接单");
                        }
                        else if (ua.F_Flag == 2)
                        {
                            if (model.F_State2 == 2)
                                return Error("工单已接单无需重新接单");
                        }
                        var res = SureWO(ua, model, ua.F_Flag);
                        if (res)
                            return Success("接单成功");
                        else
                            return Error("接单失败");
                    }
                    else
                        return Error("工单不存在");

                }
                return Error("OpenId不能为空");
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 高层审批
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        [WechatActionFilter]
        public ActionResult HigApprovalOrder(string OpenId, long orderid, string cont)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        var itemlast = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.audit + " and  F_OptType=" + (int)EnumItemOpt.audit + "and F_NextUser= '" + ua.F_UserCode + "'" + "and F_IsUsed=2  and  F_WoID = " + orderid);
                        int overtime = 0, sms = 0;
                        if (itemlast.Count > 0)
                        {
                            foreach (var it in itemlast)
                            {
                                if (!string .IsNullOrEmpty (it.F_LimitTime))
                                    overtime = int.Parse(it.F_LimitTime);
                                sms = int .Parse (it.F_IsSMS.ToString ());

                                it.F_IsUsed = 1;
                                itembll.Update(it);
                            }
                        }
                        model.F_Highopinions = cont;
                        string deptname = "";
                        var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                        if (deptmodel != null)
                        {
                            deptname = deptmodel.F_DeptName + "-";
                        }
                        AddLog(model.F_ID, model.F_State.Value, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "高层已审批", (int)EnumItemType.audit, (int)EnumItemOpt.reaudit, "", 0, ua, overtime, sms, "", 1);
                        bool n = woBLL.Update(model);
                        if (n)
                            return Success("审批成功");
                        else
                            return Error("审批失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 接单
        /// </summary>
        public bool SureWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, int flag = 3)
        {
            int overtime = 0, sms = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {
                        overtime = int.Parse(it.F_LimitTime);
                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                }
            }
            #region 工单处理
            var opt = "处理接单";
            int optbut = (int)EnumItemOpt.receive;
            int wostate = (int)EnumWorkOrderState.receive;

            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt;
            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, nowUser.F_UserCode, nowUser.F_DeptId, nowUser, overtime, sms,"",0,flag);
            if (itemid > 0)
            {
                #region 处理工单
                if (flag == 1)
                {
                    model.F_State = wostate;//已接单待处理
                }
                else if (flag == 2)
                {
                    model.F_State2 = wostate;//已接单待处理
                }
                model.F_DealBy = nowUser.F_UserCode;//已接单待处理
                woBLL.Update(model);
                #endregion
                #region 推送消息
                //读取上一级指派人员以及添加坐席并推送系统消息和微信消息
                #region 给添加坐席推送系统消息和微信消息
                sendsysmsg(model, nowUser, model.F_CreateBy, (int)itemid, "处理接单");
            //    var createUser = userAccountBLL.GetModel(model.F_CreateBy);
            //    if (createUser != null && !string.IsNullOrEmpty(createUser.F_WxOpenId))
               //     sendwxmsg(model, createUser.F_WxOpenId, nowUser, "接单");
                #endregion
                #region 读取上一级指派人员推送系统消息和微信消息
                var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
                if (itemlast != null)
                {
                    if (itemlast.F_CreateUser != model.F_CreateBy)
                    {
                        sendsysmsg(model, nowUser, itemlast.F_CreateUser, (int)itemid, "处理接单");
                     //   var lastUser = userAccountBLL.GetModel(itemlast.F_CreateUser);
                      //  if (lastUser != null && !string.IsNullOrEmpty(lastUser.F_WxOpenId))
                          //  sendwxmsg(model, lastUser.F_WxOpenId, nowUser, "接单");
                    }
                }
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        /// <summary>
        /// 工单处理
        /// </summary>
        /// <returns></returns>

        [WechatActionFilter]
        public ActionResult DealWorkOrder(string OpenId, long orderid, string F_Files, string cont, WorkOrdeDeptment deptment,
         string uncont = "",
        int isvisit = 1, int isover = 0)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                if (string.IsNullOrEmpty(cont))
                    return Error("请输入处理内容");
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                WorkOrderNewInput input = new WorkOrderNewInput();
                if (ua != null)
                {

                    if (isover == 1 && ua.F_DeptId != 36 && ua.F_DeptId != 37)
                        return Error("权限不足");
                    Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
                    var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                    if (deptmodel != null)
                    {
                        if (model != null)
                        {
                            string markdepts = "37,57,74,88,268,422,339";
                            string qualdepts = "12,36,295";
                            string strsql = "";
                            if (ua.F_Flag == 1)
                            {
                                strsql = " and F_Type in(1,3)";
                            }
                            else if (ua.F_Flag == 2)
                            {
                                strsql = " and F_Type in(2,3)";
                            }
                            var modellist = new BLL.T_Wo_WorkOrderItem_New().GetModelList("F_WoID=" + model.F_ID + "and F_IsUsed=0 " + strsql + "  order by  F_ID desc ").FirstOrDefault();
                            if (modellist != null)
                            {
                                if (modellist.F_NextUser != ua.F_UserCode)
                                    return Error("非接单人不可操作工单");
                            }
                            if (markdepts.Contains(ua.F_DeptId.ToString()) || qualdepts.Contains(ua.F_DeptId.ToString()))
                            {
                                input.F_ZL_ResponsibleUnit = deptment.ResponsibleUnit;// 责任单位
                                //input.F_EventReason = deptment.EventReason;// 事件原因
                                input.F_ZL_ImprovementRequirements = deptment.ImprovementRequirements;// 改进要求

                            }
                            #region nouser
                            //if (model.F_Type == "2" || model.F_Type == "5")
                            //{
                            //    if (deptmodel.F_DeptId == 37)
                            //    {
                            //        input.F_SC_ProductBase = deptment.ProductBase;//

                            //    }
                            //    else if (deptmodel.F_DeptId == 12)
                            //    {
                            //        input.F_IsVisit = isvisit.ToString();
                            //        input.F_ZL_QualityEventLevel = deptment.QualityEventLevel;//质量管理科-质量事件等级（未遂、一般、较大、重大）
                            //        input.F_ZL_ClaimAmount = deptment.ClaimAmount;// 质量管理科-索赔金额（单位元，对应责任单位）
                            //        input.F_ZL_ResponsibleUnit = deptment.ResponsibleUnit;// 质量管理科-责任单位（需列出，可选多个）
                            //        input.F_ZL_ApprovalOpinions = deptment.ApprovalOpinions;// 质量管理科-审批意见（同意、不同意，若选择不同意，增加输入框输入补充内容）
                            //        input.F_ZL_ApprovalDisagree = deptment.ApprovalDisagree;// 质量管理科-审批不同意意见
                            //        input.F_ZL_CompensationMethod = deptment.CompensationMethod;// 质量管理科-补偿方式（实物、钱款【单位元】，若选择钱款，增加输入框输入补充内容）
                            //        input.F_ZL_CompensationMoney = deptment.CompensationMoney;// 质量管理科-补偿钱款
                            //        input.F_ZL_CResponsibleUnits = deptment.CResponsibleUnits;//质量管理科-对应责任单位（生产、研发、农化、物流、质量管理科，销售内勤）
                            //        input.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                            //        input.F_ZL_ImprovementRequirements = deptment.ImprovementRequirements;//  质量管理科-改进要求
                            //        input.F_ZL_CApprovalNo = deptment.CApprovalNo;// 质量管理科-对应审批工作流单号
                            //    }

                            //}
                            //else if (model.F_Type == "3")
                            //{
                            //    if (deptmodel.F_DeptId == 37)
                            //    {
                            //        input.F_SC_ProductBase = deptment.ProductBase;//
                            //    }
                            //    else if (deptmodel.F_DeptId == 12)
                            //    {
                            //        input.F_IsVisit = isvisit.ToString();
                            //        input.F_ZL_CJ_IsRecord = deptment.IsRecord;//质量管理科-抽检-未备案、已备案
                            //    }
                            //}
                            //if (deptmodel.F_DeptId == 25)
                            //{

                            //    input.F_SC_CJ_ReturnAccount = deptment.ReturnAccount;//销售内勤-确认返账金额
                            //}
                            //else if (deptmodel.F_DeptId == 36)
                            //{
                            //    input.F_ZL_Fquantity = deptment.Fquantity;//质量管理科-确认实收数量（吨）
                            //}
                            #endregion
                        }
                        else
                            return Error("工单不存在！");
                    }
                    else
                    {
                        return Error("请选择接收部门");
                    }
                    if (model != null)
                    {
                        if (model.F_State == 10 && model.F_State2 == 10)
                            return Error("工单已处理请勿重复操作！");
                        else
                        {
                            var res = DealWO(ua, model, F_Files, input, cont, isover, uncont, ua.F_Flag, deptment.EventReason);
                            if (res)
                                return Success("处理成功");
                            else
                                return Error("处理失败！");
                        }
                       
                    }
                    else
                        return Error("工单不存在！");
                }
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 更新工单
        /// </summary>
        private bool Refresh()
        {
            int type = 0;
            var modlelist = woBLL.GetModelList(" F_IsDelete=0" + "and F_IsOver=0" + " and F_State in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," +
                (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.finish + ")");
            if (modlelist.Count > 0)
            {
                foreach (var it in modlelist)
                {

                    if (TimeforOver(it.F_ID))
                    {
                        type = 0;
                    }
                    else
                    {
                        type = 1;
                    }
                    if (type != it.F_IsOver)
                    {
                        it.F_IsOver = type;
                        bool n = woBLL.Update(it);
                        if (!n)
                        {
                            return false;
                        }
                    }
                }

            }
            return true;

        }

        /// <summary>
        /// 更新工单---判断内线超时工单
        /// </summary>
        private bool Refresh2()
        {
            int type = 0;
            var modlelist = woBLL.GetModelList("  F_IsDelete=0" + "and F_IsOver in(0,1)" + " and F_State2 in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," +
                (int)EnumWorkOrderState.assign + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + "," + (int)EnumWorkOrderState.finish + ")");
            if (modlelist.Count > 0)
            {
                foreach (var it in modlelist)
                {
                    if (TimeforOver(it.F_ID, 2))
                    {
                        type = 0;
                    }
                    else
                    {
                        type = 2;
                    }
                    if (type != it.F_IsOver)
                    {
                        if (it.F_IsOver == 1)
                        {
                            if (type == 2)
                            {
                                it.F_IsOver = 3;
                            }
                            else
                            {
                                it.F_IsOver = 1;
                            }
                        }
                        else
                        {
                            it.F_IsOver = type;
                        }
                        bool n = woBLL.Update(it);
                        if (!n)
                        {
                            return false;
                        }
                    }
                }

            }
            return true;
        }

        /// <summary>
        /// 退回工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        [WechatActionFilter]
        public ActionResult BackWorkOrder(string OpenId, long orderid, string cont, int type = 0)
        {//办理人员和监管可以退回工单
            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                //河南心连心化学工业集团股份有限公司-系统维护管理员(8000)指派工单给 李波(80324),张绍申(80325),杜爱国(80326)，说明：无

                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        string strsql = "";
                        if (ua.F_Flag == 1)
                        {
                            strsql = $" and F_Type in(1,3)";
                        }
                        else if (ua.F_Flag == 2)
                        {
                            strsql = $" and F_Type in(2,3)";
                        }
                        var modellist = new BLL.T_Wo_WorkOrderItem_New().GetModelList($"F_WoID={model.F_ID} and F_IsUsed=0 {strsql} order by   F_ID desc ").FirstOrDefault();
                        if (modellist != null)
                        {
                            if (modellist != null)
                            {
                                string[] sprt = modellist.F_NextUser.Split(',');
                                if (sprt.Length == 1)
                                {
                                    if (modellist.F_NextUser != ua.F_UserCode)
                                        return Error("非接单人不可操作工单");
                                }
                            }
                        }
                        var res = BackWO(ua, model, cont, type, ua.F_Flag);
                        if (res)
                            return Success("退回成功");
                        else
                            return Error("退回失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }


        /// <summary>
        /// 撤回工单
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="cont"></param>
        /// <returns></returns>
        [WechatActionFilter]
        public ActionResult RevokeWo(string OpenId,long orderid, string cont)
        {

            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                //增加撤回功能
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
                    //验证信息 
                    if (model != null)
                    {
                        int flag = 0;
                        Model.T_Sys_RoleInfo ro = rolebll.GetModel(ua.F_RoleId);
                        var modellist = new BLL.T_Wo_WorkOrderItem_New().GetModelList("F_WoID=" + model.F_ID + "and F_IsUsed=0 order by   F_ID desc ").FirstOrDefault();

                        if (modellist != null)
                        {
                            string createuser = modellist.F_CreateUser;
                            if (!string.IsNullOrEmpty(createuser))
                            {
                                if (createuser != ua.F_UserCode)
                                    return Error("无操作权限");
                            }
                            if (modellist.F_WoState == (int)EnumWorkOrderState.assign)
                            {
                                if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY")
                                {
                                    flag = 3;
                                }
                                else
                                {
                                    flag = ua.F_Flag;
                                }
                                var res = RevWO(ua, model, cont,flag);
                                if (res)
                                    return Success("撤回成功");
                                else return Error("撤回失败！");
                            }
                            else
                                return Error("撤回失败！");
                        }
                        return Error("操作失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");
        }

        /// <summary>
        ///申请延期
        /// </summary>
        /// <returns></returns>
        [WechatActionFilter]
        public ActionResult DelayWorkOrder(string OpenId, long orderid, string cont, float limit = 0)
        {
            if (!string.IsNullOrEmpty(OpenId))
            {
                var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + OpenId + "'").FirstOrDefault();
                if (ua != null)
                {
                    Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
                    //验证信息
                    if (model != null)
                    {
                        var res = DeWO(ua, model, cont, limit);
                        if (res)
                            return Success("延期成功");
                        else
                            return Error("延期失败！");
                    }
                    return Error("工单不存在");
                }
            }
            return Error("无操作权限");

        }
        /// <summary>
        /// 申请延期
        /// </summary>
        public bool DeWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont, float limit)
        {
            #region 工单处理
            int sms = 0; int wostate = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {
                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                    itembll.Update(it);
                    wostate = int.Parse(it.F_WoState.ToString());

                }
            }
            int optbut = (int)EnumItemOpt.Delay;
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + "延期工单，延期说明：" + cont;
            //获取上一级处理人员
            var touser = "";
            var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by  F_ID  desc").FirstOrDefault();
            if (itemlast != null)
                touser = itemlast.F_CreateUser;
            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.Delay, optbut, touser, 0, nowUser, limit + model.F_limit, sms, "", 1);

            #endregion

            return true;
        }
        /// <summary>
        /// 退回工单
        /// </summary>
        public bool BackWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont, int type, int flag = 1)
        {
            #region 工单处理
            int sms = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {
                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                }
            }
            var opt = "退回";
            int F_OptType = 1;
            int optbut = (int)EnumItemOpt.reback;
            int wostate = (int)EnumWorkOrderState.reback;
            if (type == 1)
            {
                opt = "异常退回";
                optbut = (int)EnumItemOpt.abreback;
                wostate = (int)EnumWorkOrderState.abreback;
                F_OptType = 2;
            }
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "工单，退回说明：" + cont;
            //获取上一级处理人员
            var touser = ""; var deptid = 0;
            string strsql = "";
            if (flag == 1)
            {
                strsql = $" and F_Type in(1,3)";
            }
            else if (flag == 2)
            {
                strsql = $" and F_Type in(2,3)";
            }
            var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and F_NextDept =" + nowUser.F_DeptId + " and F_WoState =" + F_OptType + " and  F_WoID='" + model.F_ID + "'" + strsql + " order by F_ID desc").FirstOrDefault();
            if (itemlast != null)
            {

                touser = itemlast.F_CreateUser;
                if (!string.IsNullOrEmpty(touser))
                {
                    var ua = userAccountBLL.GetModel(touser);
                    if (ua != null)
                    {
                        deptid = ua.F_DeptId;
                    }
                }
            }
            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, touser, deptid, nowUser, model.F_limit, sms, "", 0, flag);
            if (itemid > 0)
            {
                string smscont = "";
                if (model.F_Type == "1")
                {
                    smscont = "咨询";
                }
                else if (model.F_Type == "2")
                {
                    smscont = "投诉";
                }
                else if (model.F_Type == "3")
                {
                    smscont = "抽检";
                }
                else if (model.F_Type == "5")
                {
                    smscont = "业务协办";
                }
                else
                {
                    smscont = "建议";
                }
                string[] mag = { smscont };
                string smsmsg = "您好，您有一条新的" + smscont + "工单，请及时接单处理！";
                var tousermodel = new BLL.T_Sys_UserAccount().GetModel(touser);
                if (tousermodel != null)
                {
                    if (!string.IsNullOrEmpty(tousermodel.F_Mobile))
                    {
                        SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, tousermodel.F_Mobile.Trim());
                        bool n = new SMSController().AddSmS(tousermodel.F_Mobile.Trim(), smsmsg, nowUser.F_UserId);
                    }
                }
                #region 处理工单
                if (deptid == 2)
                {
                    if (flag == 1)
                    {
                        model.F_State = (int)EnumWorkOrderState.reassign;
                    }
                    else if (flag == 2)
                    {
                        model.F_State2 = (int)EnumWorkOrderState.reassign;
                    }
                }
                else
                {
                    if (flag == 1)
                    {
                        model.F_State = wostate;
                    }
                    else if (flag == 2)
                    {
                        model.F_State2 = wostate;
                    }

                }
                woBLL.Update(model);
                #endregion
                #region 推送消息
                #region 向上一级操作人员推送消息
                if (!string.IsNullOrWhiteSpace(touser) && touser != nowUser.F_UserCode)
                {//排除上一级指派人是自己
                    sendsysmsg(model, nowUser, touser, (int)itemid, opt);
                  //  var lastUser = userAccountBLL.GetModel(touser);
                  //  if (lastUser != null && !string.IsNullOrEmpty(lastUser.F_WxOpenId))
                    //    sendwxmsg(model, lastUser.F_WxOpenId, nowUser, opt);
                }
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }

        /// <summary>
        /// 撤回工单
        /// </summary>
        public bool RevWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string cont,int flag=1)
        {
            #region 工单处理
            int sms = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {
                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                }
            }
            var opt = "撤回";
            int F_OptType = 1;
            int optbut = (int)EnumItemOpt.revoke;
            int wostate = (int)EnumWorkOrderState.revoke;
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "工单，撤回说明：" + cont;
            //获取上一级处理人员

            var touser = ""; var deptid = 0;
            string strsql = "";
            if (flag == 1)
            {
                strsql = " and F_Type in(1,3)";
            }
            else if (flag == 2)
            {
                strsql = " and F_Type in(2,3)";
            }
            else
            {
                strsql = "";
            }

            var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_IsUsed=0 and F_WoState =" + F_OptType + " and  F_WoID='" + model.F_ID + "'" + strsql + " order by F_ID desc");
            if (itemlast != null && itemlast.Count > 0)
            {
                foreach (var item in itemlast)
                {
                    touser = item.F_NextUser;
                    if (!string.IsNullOrEmpty(touser))
                    {
                        var ua = userAccountBLL.GetModel(touser);
                        if (ua != null)
                        {
                            deptid = ua.F_DeptId;
                        }
                    }
                }
            }
            var itemid = AddLog((int)model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, nowUser.F_UserCode, nowUser.F_DeptId, nowUser, model.F_limit, sms,"",0,flag);
            if (itemid > 0)
            {
                #region 发短信
                //string smscont = "";
                //if (model.F_Type == "1")
                //{
                //    smscont = "咨询";
                //}
                //else if (model.F_Type == "2")
                //{
                //    smscont = "投诉";
                //}
                //else if (model.F_Type == "3")
                //{
                //    smscont = "抽检";
                //}
                //else
                //{
                //    smscont = "建议";
                //}
                //string[] mag = { smscont };
                //string smsmsg = "您好，您有一条待处理的工单已被撤回,请留意！";
                //var tousermodel = new BLL.T_Sys_UserAccount().GetModel(touser);
                //if (tousermodel != null)
                //{
                //    if (!string.IsNullOrEmpty(tousermodel.F_Mobile))
                //    {
                //        SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, tousermodel.F_Mobile.Trim());
                //        //SmsSingleSenderResult result = new SMSController().SMSSingleshot(445305, mag, "15225066843");
                //        bool n = new SMSController().AddSmS(tousermodel.F_Mobile.Trim(), smsmsg, nowUser.F_UserId);
                //    }
                //}
                #endregion
                #region 处理工单
                if (flag == 1)
                {
                    model.F_State = wostate;
                }
                else if (flag == 2)
                {
                    model.F_State2 = wostate;
                }
                else
                {
                    model.F_State = wostate;
                    model.F_State2 = wostate;
                }
                woBLL.Update(model);
                #endregion
                #region 推送消息
                #region 向上一级操作人员推送消息
                //if (!string.IsNullOrWhiteSpace(touser) && touser != nowUser.F_UserCode)
                //{//排除上一级指派人是自己
                //    sendsysmsg(model, nowUser, touser, (int)itemid, opt);                 
                //}
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }

        /// <summary>
        /// 处理工单
        /// </summary>
        public bool DealWO(Model.T_Sys_UserAccount nowUser, Model.T_Wo_WorkOrder model, string F_Files, WorkOrderNewInput input, string cont, int isover = 0, string uncont = "",int flag=1, string eventreason = "")
        {
            #region 工单处理
            int sms = 0;
            var itemlasts = itembll.GetModelList("  F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID=" + model.F_ID + " ");
            if (itemlasts.Count > 0)
            {
                foreach (var it in itemlasts)
                {
                    if (it.F_WoState == 1)
                    {
                        sms = int.Parse(it.F_IsSMS.ToString());
                    }
                }
            }
            var opt = "处理";
            int optbut = (int)EnumItemOpt.deal;
            int wostate = (int)EnumWorkOrderState.receive;
            string nextuser = "";
            int nextdept = 0;


            if (isover == 1)
            {

                model.F_DealResult = "已处理";//处理结果
                opt = "处理完结";
                optbut = (int)EnumItemOpt.end;
                wostate = (int)EnumWorkOrderState.finish;
                model.F_DealBy = nowUser.F_UserCode;
                model.F_DealTime = DateTime.Now;
            }
            else
            {
                model.F_DealResult = "未处理";//处理结果
                model.F_DealReasons = uncont;//未处理原因
                nextuser = nowUser.F_UserCode;
                nextdept = nowUser.F_DeptId;
            }
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = departmentBLL.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var optcont = "";
            if (!string.IsNullOrEmpty(cont))
                optcont = "，处理内容：" + cont;
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_WorkNumber + ")" + opt + "工单" + optcont;
            var itemid = AddLog(model.F_ID, wostate, content, (int)EnumItemType.deal, optbut, nextuser, nextdept, nowUser, model.F_limit, sms, "", 0, flag);
            if (itemid > 0)
            {
                #region 处理工单
                if (flag == 1)
                {
                    model.F_State = wostate;
                }
                else if (flag == 2)
                {
                    model.F_State2 = wostate;
                }
                //处理内容
                if (!string.IsNullOrEmpty(F_Files))
                {
                    if (!string.IsNullOrEmpty(model.F_Files))
                        model.F_Files = model.F_Files + "," + F_Files;
                    else
                        model.F_Files = F_Files;
                }

                if (!string.IsNullOrEmpty(cont))
                {
                    if (model.F_Source == "3")
                    {
                        if (flag == 2)
                        {
                            model.F_DealContent2 = cont;
                        }
                        else
                        {
                            model.F_DealContent = cont;
                        }
                    }
                    else
                    {
                        if (flag == 2)
                        {
                            model.F_DealContent2 += cont + "；";
                        }
                        else
                        {
                            model.F_DealContent += cont + "；";
                        }
                    }
                    if (flag == 1)
                    {
                        model.F_SuperiorOpinion = cont;
                    }
                    else if (flag == 2)
                    {
                        model.F_SuperiorOpinion2 = cont;
                    }
                    //model.F_SuperiorOpinion = string.IsNullOrEmpty(model.F_SuperiorOpinion) ? cont : model.F_SuperiorOpinion + "； " + cont;
                }
                if (!string.IsNullOrEmpty(eventreason))
                {
                    if (flag == 1)
                    {
                        model.F_EventReason = eventreason;
                    }
                    else if (flag == 2)
                    {
                        model.F_EventReason2 = eventreason;
                    }
                }

                model.F_DealTime = DateTime.Now;
                InToworkModel(model, input);
                woBLL.Update(model);
                #endregion

                #region 推送消息
                #region 推送消息给添加的坐席 -处理情况
                if (nowUser.F_UserCode != model.F_CreateBy)
                {
                    sendsysmsg(model, nowUser, model.F_CreateBy, (int)model.F_ID, opt);//推送系统消息
                  if (model.F_State == (int)EnumWorkOrderState.finish)
                    {
                        var createmodel = userAccountBLL.GetModel(model.F_CreateBy);  //被指派人
                        if (createmodel != null)
                        {
                            if (!string.IsNullOrEmpty(createmodel.F_WxOpenId))
                            {
                                sendwxmsg(model, createmodel.F_WxOpenId, nowUser, "工单完结");
                            }
                        }
                    }
                   
                }
                #endregion
                #region 向上一级操作人员推送消息
                var itemlast = itembll.GetModelList(" F_ItemType=" + (int)EnumItemType.deal + " and  F_WoID='" + model.F_ID + "' and F_NextUser='" + nowUser.F_UserCode + "' order by F_ID desc").FirstOrDefault();
                if (itemlast != null)
                {
                    if (itemlast.F_CreateUser != model.F_CreateBy)
                    {
                        sendsysmsg(model, nowUser, itemlast.F_CreateUser, (int)itemid, opt);
                      //  var lastUser = userAccountBLL.GetModel(itemlast.F_CreateUser);
                       // if (lastUser != null && !string.IsNullOrEmpty(lastUser.F_WxOpenId))
                          //  sendwxmsg(model, lastUser.F_WxOpenId, nowUser, opt);
                    }
                }
                #endregion
                #region 办理完结向客户发送消息
                //if (model.F_State == (int)EnumWorkOrderState.finish)
                //{
                //    if (!string.IsNullOrEmpty(model.F_CustomerID))
                //    {
                //        var cusmodel = customerBaseBLL.GetModel(model.F_CustomerID.Trim());
                //        if (cusmodel != null && !string.IsNullOrEmpty(cusmodel.F_WxOpenId))
                //        {
                //            sendwxmsg(model, cusmodel.F_WxOpenId, nowUser, opt);
                //        }
                //    }
                //}
                if (isover == 1)
                {
                   // if (!string.IsNullOrEmpty(model.F_WxOpenId))
//sendwxmsg(model, model.F_WxOpenId, nowUser, model.F_DealContent);
                }
                  
                #endregion
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        //推送系统提醒
        public void sendsysmsg(Model.T_Wo_WorkOrder womodel, Model.T_Sys_UserAccount nowUser, string touser, int toid, string opt)
        {
            #region 消息提醒
            string strmsg = string.Empty;
            strmsg = nowUser.F_UserName + "(" + nowUser.F_UserCode + ")" + "操作" + opt + "工单";
            Model.T_Msg_List msg = new Model.T_Msg_List();
            msg.Type = (int)Model.MSGType.workorder;//处理
            msg.ToUser = touser;
            msg.ToID = toid;
            msg.Detail = strmsg;
            msg.State = 0;
            msg.IsDel = 0;
            msg.CreateUser = nowUser.F_UserCode;
            msg.CreateDate = DateTime.Now;

            new BLL.T_Msg_List().Add(msg);
            #endregion
        }
        //推送微信消息
        public void sendwxmsg(Model.T_Wo_WorkOrder womodel, string openid, Model.T_Sys_UserAccount nowUser, string opt)
        {
            #region 推送微信
            try
            {
                if (!string.IsNullOrEmpty(openid))
                {
                    var dicv = dicvalueBll.GetModel(int.Parse(womodel.F_Type));
                    string content = string.Empty;
                    var wotype = "";
                    if (dicv != null)
                    {
                        wotype = dicv.F_Name;
                    }
                    content = opt;
                    var msg = WxHelper.SendWechatMsg1(DateTime .Now .ToString ("yyyy-MM-dd HH:mm:ss"),  "你的工单已处理", wotype, womodel.F_State.ToString(), content, womodel.F_ID.ToString(), openid, "");
                    Error("推送微信::::::" + msg.ToString());
                }
            }
            catch { }
            #endregion
        }
        public static bool IsNumeric(string value)
        {
            return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");

        }
        /// <summary>
        /// 修改工单
        /// </summary>
        /// <returns></returns>
        [WechatActionFilter]
        public ActionResult Update(WorkOrderNewInput input )
        {
            var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + input.F_WxOpenId + "'").FirstOrDefault();
          
            if (ua != null)
            {
                #region 添加验证判断
                if (input.F_ID <= 0)
                    return Error("参数错误！");
                if (!(input.F_Type > 0 && input.F_Type < 6))
                    return Error("工单类型错误！");
                if (string.IsNullOrEmpty(input.F_CusName))
                    return Error("请输入客户姓名！");
                if (string.IsNullOrEmpty(input.F_CusPhone))
                    return Error("请输入客户电话！");
                if(input.F_Type == 2 || input.F_Type == 5)
                {
                    if (string.IsNullOrEmpty(input.F_SalesBase))
                        return Error("请输入基地！");
                    if (string.IsNullOrEmpty(input.F_QuestionType))
                        return Error("请选择问题类别！");
                }
               
                //if (!string.IsNullOrEmpty(input.F_BatchNumber) && !vaBatchNumber(input.F_BatchNumber))
                //{
                //    return Error("请输入正确的生产批次号！");
                //}
                if (!string.IsNullOrEmpty(input.F_CustomerID))
                {
                    var Customer = customerBaseBLL.GetModel(input.F_CustomerID.Trim());
                    if (Customer == null)
                        return Error("无此客户编码！");
                }
                if (!string.IsNullOrWhiteSpace(input.F_MaterialID))
                {
                    var Customer = mmBLL.GetModel(input.F_MaterialID.Trim());
                    if (Customer == null)
                        return Error("无此物料编码！");
                }
                //if (!string.IsNullOrEmpty(input.F_BatchNumber))
                //{
                //    var prono = input.F_BatchNumber.Substring(0, 6);
                //    try
                //    {
                //        var pronos = DateTime.ParseExact(prono, "yyMMdd", null).ToString("yyyy-MM-dd");
                //        var protime = Convert.ToDateTime(pronos);
                //        if (DateTime.Parse(pronos) > DateTime.Now)
                //        {
                //            return Error("生产批次号错误，生产日期不能大于当前时间！");
                //        }

                //    }
                //    catch
                //    {
                //        return Error("生产批次号错误，日期格式错误！");
                //    }
                //}
                if (!string.IsNullOrEmpty(input.F_CustomerID) && !valcode(input.F_CustomerID.ToString(), 10))
                    return Error("客户编号为10为纯数字！");
                if (!string.IsNullOrEmpty(input.F_MaterialID) && !valcode(input.F_MaterialID.ToString(), 11))
                    return Error("物料编码为11为纯数字！");
                #endregion
                var model = woBLL.GetModel(input.F_ID);
                if (model == null)
                    return Error("查询不到此工单！");

                if (model.F_State == 2)
                {
                    return Error("此工单已接单不能修改！");
                }
                else if (model.F_State == 11 || model.F_State == 10)
                {
                    return Error("此工单已处理不能修改！");
                }
                if (!string.IsNullOrEmpty(input.F_SalesPhone))
                {
                    if (!IsNumeric(input.F_SalesPhone))
                        return Error("请输入正确的业务员电话");
                }
                var itemlasts = itembll.GetModelList("    F_WoID=" + model.F_ID + "order by F_ID desc ").FirstOrDefault ();
                int overtime = 0, sms = 0;
                if (itemlasts!=null )
                {
                    if (itemlasts.F_LimitTime != "")
                        overtime = int.Parse(itemlasts.F_LimitTime);
                    sms = int.Parse(itemlasts.F_IsSMS.ToString());
                }
                #region 保存客户基本信息
                model = inputtoobj(ua, model, input, 1);
                #endregion
                bool n = woBLL.Update(model);
                if (n)
                {
                    WriteWorkOrderLog(model.F_WorkOrderCode, ua.F_UserCode, 0, "", 1, "修改工单");
                    #region 读取当前登录人的部门
                    string deptname = "";
                    var deptmodel = departmentBLL.GetModel(ua.F_DeptId);
                    if (deptmodel != null)
                    {
                        deptname = deptmodel.F_DeptName + "-";
                    }
                    #endregion

                    AddLog(input.F_ID, model.F_State.Value, deptname + ua.F_UserName + "(" + ua.F_WorkNumber + ")" + "修改工单", (int)EnumItemType.update, (int)EnumItemOpt.update, "", 0, ua, overtime, sms, "", 1);
                    if (GetUser(input.F_WxOpenId) != null)
                    {
                        var user = GetUser(input.F_WxOpenId);
                        string deptname1 = "";
                        var deptmode = departmentBLL.GetModel(user.F_DeptId);
                        if (deptmode != null)
                        {
                            deptname1 = deptmode.F_DeptName + "-";
                        }
                        var deptmodel1 = departmentBLL.GetModel(ua.F_DeptId);

                        AddLog(input.F_ID, model.F_State.Value, deptname1 + user.F_UserName + "(" + user.F_WorkNumber + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, user.F_UserCode, user.F_DeptId, ua, overtime, sms);
                        if (sms == 1 && !string.IsNullOrEmpty(user.F_Mobile))
                        {
                            SendSms(model.F_Type, user.F_Mobile, ua.F_UserId);
                        }
                    }
                    else
                    {

                        string deptname1 = "";
                        int dapt = 0, nextda = 0; string opt = "";
                        var deptmodel1 = departmentBLL.GetModel(ua.F_DeptId);
                        if (deptmodel1 != null)
                        {
                            deptname1 = deptmodel1.F_DeptName ;
                            dapt = deptmodel1.F_ParentId;
                        }
                        //if (dapt != 0)
                        //{
                            if (CirculMarket(ua.F_DeptId, 11))
                            {
                                nextda = 37;
                                opt = "流转市场管理科";
                            }
                            else if (CirculMarket(ua.F_DeptId, 14))
                            {
                                nextda = 57;
                                opt = "流转营销管理处";
                            }
                            else if (CirculMarket(ua.F_DeptId, 15))
                            {
                                nextda = 74;
                                opt = "流转策划推广";
                            }
                            else if (CirculMarket(ua.F_DeptId, 16))
                            {
                                nextda = 88;
                                opt = "流转销售部";
                            }
                            else if (CirculMarket(ua.F_DeptId, 18))
                            {
                                nextda = 268;
                                opt = "流转车用尿素";

                            }

                            else if (CirculMarket(ua.F_DeptId, 20))
                            {
                                nextda = 295;
                                opt = "流转新乡黑科质检";
                            }
                            else if (CirculMarket(ua.F_DeptId, 332))
                            {
                                nextda = 339;
                                opt = "流转营销管理处";

                            }
                            else if (ua.F_DeptId == 17 || ua.F_DeptId == 19 || ua.F_DeptId == 20 || ua.F_DeptId == 21)
                            {
                                nextda = ua.F_DeptId;
                                opt = "流转" + deptname1;
                            }
                        //}
                        if (nextda != 0)
                        {
                            var res = AssignWO(ua, model, input, opt, "", nextda, 0, model.F_limit, sms,0,0,0,"",1 );
                            if (res)
                                return Success("保存成功");
                            else
                                return Error("流转失败！");
                        }
                        else
                        {
                            return Error("流转失败！");
                        }

                    }
                    return Success("保存成功！");
                }
                else
                    return Error("保存失败！");
            }
            else
            {
                return Error("OpenId不能为空！！");
            }
        }


        public void WriteWorkOrderLog(string WorkOrderID, string UserCode, int IsDelete, string DelUserCode, int TypeId, string Remark)
        {
            var model = new Model.T_Wo_WorkOrder_Logs();
            model.WorkOrderID = WorkOrderID;        //工单编号
            model.UserCode = UserCode;              //修改人code
            model.AddTime = DateTime.Now;           //添加时间
            model.IsDelete = IsDelete;              //是否删除（0正常1删除）
            model.DelUserCode = DelUserCode;        //删除人code
            model.TypeId = TypeId;                  //类型（0添加，1修改）
            model.Remark = Remark;                  //备注
            blllogs.Add(model);
        }
        /// <summary>
        /// 添加工单记录
        /// </summary>
        public long AddLog(long woid, int wostate, string content, int itemtype, int opttype, string nextuser, int nextdept, Model.T_Sys_UserAccount nowUser, float overtime, int sms, string create = "", int F_IsUsed = 0, int flag = 3)
        {
            Model.T_Wo_WorkOrderItem_New itemModel = new Model.T_Wo_WorkOrderItem_New();
            #region 
            string strsql = "";
            Model.T_Sys_RoleInfo ro = rolebll.GetModel(nowUser.F_RoleId);
            if (ro.F_RoleCode == "JDYPTZX" || ro.F_RoleCode == "JDYBZZX" || ro.F_RoleCode == "XTGLY" && flag != 3)
            {
                strsql = $" F_OptType !=1 and isnull(F_IsUsed,'0')='0' and F_ItemType={itemtype} and  F_WoID={woid} and  F_CreateUser={nowUser.F_UserCode} and F_Type in({flag},3) ";
            }
            else
            {
                strsql = $" isnull(F_IsUsed,'0')='0' and F_ItemType={itemtype} and  F_WoID={woid} and  (F_CreateUser={nowUser.F_UserCode} or F_NextUser like '%{nowUser.F_UserCode}%')"
                       + $" and F_Type in({flag},3)";
            }
            //处理当前工单的记录之前的记录过期
            //var itemlast = itembll.GetModelList(" isnull(F_IsUsed,'0')='0' and F_ItemType=" + itemtype + " and  F_WoID=" + woid + " ");
            var itemlast = itembll.GetModelList(strsql);
            if (F_IsUsed == 0)
            {
                if (itemlast != null && itemlast.Count > 0)
                {
                    foreach (var it in itemlast)
                    {
                        it.F_IsUsed = 1;
                        it.F_LimitTime = overtime.ToString();

                        itembll.Update(it);
                    }
                    itemModel.F_LastTime = itemlast.LastOrDefault().F_CreateTime;
                }
            }

            #endregion
            itemModel.F_WoID = woid;
            itemModel.F_IsSMS = sms;
            itemModel.F_WoState = wostate;
            itemModel.F_ItemType = itemtype;
            itemModel.F_OptType = opttype;
            itemModel.F_OptContent = content;
            itemModel.F_NextUser = nextuser;
            itemModel.F_NextDept = nextdept;
            itemModel.F_IsUsed = F_IsUsed;
            itemModel.F_LimitTime = overtime.ToString();
            itemModel.F_Type = flag;//区分内外线和公共部门
            if (nowUser != null)
            {
                itemModel.F_CreateUser = nowUser.F_UserCode;
            }
            else
            {
                itemModel.F_CreateUser = "";
            }

            if (create != "")
            {
                itemModel.F_CreateTime = DateTime.Parse(create);
            }
            else
            {
                itemModel.F_CreateTime = DateTime.Now;
            }
            var res = itembll.Add(itemModel);
            return res;
        }
        #region
        //workorder.WoBillController blcon = new WoBillController();
        ///// <summary>
        ///// 获取所有业务
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult GetBusList()
        //{   
        //    var list = blcon.GetBusAllList();
        //    return Success("获取信息列表成功", list);
        //}
        ///// <summary>
        ///// 获取业务内容
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult GetBusInfo()
        //{
        //    string strbusid = HttpUtility.UrlDecode(RequestString.GetQueryString("busid"));
        //    if (string.IsNullOrEmpty(strbusid))
        //        return Error("参数错误");
        //    var model = blcon.GetBusInfo(strbusid);
        //    if (model != null)
        //        return Success("获取信息成功", model);
        //    else
        //        return Error("获取信息失败");
        //}
        ///// <summary>
        ///// 获取开票列表
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult GetBillList()
        //{
        //    DataTable dt = new DataTable();
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
        //    string strbtime = HttpUtility.UrlDecode(RequestString.GetQueryString("btime"));
        //    string stretime = HttpUtility.UrlDecode(RequestString.GetQueryString("etime"));
        //    string strpageindex = RequestString.GetQueryString("pageindex");
        //    int pageindex = 1;
        //    string strpagesize = RequestString.GetQueryString("pagesize");
        //    int pagesize = 10;
        //    if (strpageindex.Trim() != "")
        //    {
        //        pageindex = Convert.ToInt32(strpageindex);
        //    }
        //    if (strpagesize.Trim() != "")
        //    {
        //        pagesize = Convert.ToInt32(strpagesize);
        //    }
        //    var obj=blcon.GetLists(stropenid, strbtime, stretime, pageindex, pagesize);
        //    return Content(obj.ToJson());
        //}
        ///// <summary>
        ///// 获取开票详情
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult GetBillInfo()
        //{
        //    string strbillid = HttpUtility.UrlDecode(RequestString.GetQueryString("billid"));
        //    if (string.IsNullOrEmpty(strbillid))
        //        return Error("参数错误");
        //    var model = blcon.GetBillInfo(strbillid);
        //    if (model != null)
        //        return Success("获取信息成功", model);
        //    else
        //        return Error("获取信息失败");
        //}
        ///// <summary>
        ///// 开票
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult AddBill()
        //{
        //    string billtype = RequestString.GetFormString("billtype");//发票类型
        //    string cusname = RequestString.GetFormString("cusname");//客户名称
        //    string taxidnum = RequestString.GetFormString("taxidnum");//纳税人识别号
        //    string address = RequestString.GetFormString("address");//地址
        //    string phone = RequestString.GetFormString("phone");//电话
        //    string bank = RequestString.GetFormString("bank");//开户行
        //    string bankaccount = RequestString.GetFormString("bankaccount");//开户行账号
        //    string proname = RequestString.GetFormString("proname");//项目名称
        //    string models = RequestString.GetFormString("models");//型号
        //    string unit = RequestString.GetFormString("unit");//单位
        //    string amount = RequestString.GetFormString("amount");//数量
        //    string unitprice = RequestString.GetFormString("unitprice");//单价
        //    string sumprice = RequestString.GetFormString("sumprice");//金额
        //    string taxrate = RequestString.GetFormString("taxrate");//税率
        //    string taxamount = RequestString.GetFormString("taxamount");//税额
        //    string billingMethod = RequestString.GetFormString("billingmethod");//开票方式：快递/自取
        //    string billingTime = RequestString.GetFormString("billingtime");//开票时间
        //    string remark = RequestString.GetFormString("remark");//备注
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    Model.T_Wo_Bill dModel = new Model.T_Wo_Bill();
        //    #region 保存基本信息
        //    dModel.F_BillType = billtype;
        //    dModel.F_CusName = cusname;
        //    dModel.F_TaxIDNum = taxidnum;
        //    dModel.F_Address = address;
        //    dModel.F_Phone = phone;
        //    dModel.F_Bank = bank;
        //    dModel.F_BankAccount = bankaccount;
        //    dModel.F_ProName = proname;
        //    dModel.F_Models = models;
        //    dModel.F_Unit = unit;
        //    dModel.F_Amount = amount;
        //    dModel.F_UnitPrice = unitprice;
        //    dModel.F_SumPrice = sumprice;
        //    dModel.F_TaxRate = taxrate;
        //    dModel.F_TaxAmount = taxamount;
        //    dModel.F_BillingMethod = billingMethod;
        //    dModel.F_BillingTime = billingTime;
        //    dModel.F_Remark = remark;
        //    dModel.F_Openid = stropenid;
        //    dModel.F_CreateOn = DateTime.Now;
        //    dModel.F_State = 0;
        //    #endregion
        //    var res=blcon.addbills(dModel);
        //    if (res)
        //        return Success("保存成功");
        //    else
        //        return Error("保存失败");
        //}
        #endregion
        #region 获取公司详情
        ////获取公司信息
        //[WechatActionFilter]
        //public ActionResult GetInfo()
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
        //    if (string.IsNullOrEmpty(stropenid))
        //        return Error("参数错误!");
        //    var model=customerBaseBLL.GetModelByOpenid(stropenid);
        //    if (model != null)
        //    {
        //        var sqlwo = " IsDel=0 and State <>2 "; var sqlno = " F_isDel=0 ";
        //        var nowUser = userAccountBLL.GetModelByOpenid(stropenid);
        //        var nowCus = customerBaseBLL.GetModelByOpenid(stropenid);
        //        if (nowUser != null)
        //        {
        //            workorder.WorkOrderController wo = new workorder.WorkOrderController();
        //            sqlwo += " and State =1 and WorkOrderID in ( '" + wo.GetDWCWorkOrderID(nowUser.F_UserCode) + "') ";
        //            sqlno += " and (ISNULL(F_UserId,'') = '' or ISNULL(F_UserId,'') like '%," + nowUser.F_UserId + ",%')";
        //        }
        //        else if (nowCus != null)
        //        {
        //            sqlwo += " and ( CustomerID=" + model.F_CustomerId + " or County like '%" + model.F_CompanyName + "%' )";
        //            sqlno += " and F_isCus=1 and F_NoticeId not in (select toid from T_Msg_List where Type=6 and ToUser='"+nowCus.F_CustomerCode+ "' and state=1 and IsDel=0)";
        //        }
        //        var ordercount = woBLL.GetRecordCount(sqlwo);
        //        var noticecount = new BLL.T_Msg_NoticeInfo().GetRecordCount(sqlno);

        //        var obj = new
        //        {
        //            model.F_CompanyName,//公司名称
        //            model.F_CompanyLogo,//logo
        //            model.F_CustomerCode,//编号
        //            model.F_CycleStart,//服务周期-开始时间
        //            model.F_CycleEnd,//服务周期-结束时间
        //            model.F_ChargeType,//收费类型：1月度，2季度，3年度
        //            model.F_Charges,//收费
        //            model.F_TaxNumber,//公司税号
        //            model.F_CompanyAddress,//公司地址
        //            ordercount,//待处理工单数量
        //            noticecount,//未读公告数量
        //        };
        //        return Success("获取成功", obj);
        //    }
        //    return Error("获取失败");
        //}
        ////获取财税信息
        ////[WechatActionFilter]
        //public ActionResult GetFinc()
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
        //    var model = customerBaseBLL.GetModelByOpenid(stropenid);
        //    if (model != null)
        //    {
        //        var finmodel = finbll.GetModelList(" F_CustomerId=" + model.F_CustomerId).FirstOrDefault();
        //        if (finmodel != null)
        //        {
        //            var obj = new
        //            {
        //                model.F_CompanyName,//公司名称
        //                model.F_CompanyLogo,//logo
        //                model.F_CustomerCode,//编号
        //                finmodel.F_CusFinId,
        //                finmodel.F_CustomerId,
        //                finmodel.F_MonthState,
        //                finmodel.F_AnnualIncome,
        //                finmodel.F_AnnualProfit,
        //                finmodel.F_AnnualCost,
        //                finmodel.F_AnnualPersonCount,
        //                finmodel.F_AnnualWages,
        //                finmodel.F_QuarterlyCost,
        //                finmodel.F_QuarterlyPersonCount,
        //                finmodel.F_QuarterlyWages,
        //                finmodel.F_QuarterlyIncome,
        //                finmodel.F_QPVAT,
        //                finmodel.F_QPSurtax,
        //                finmodel.F_QPTaxes,
        //                finmodel.F_QPConTax,
        //                finmodel.F_QPPerinTax,
        //                finmodel.F_QPStampTax,
        //                finmodel.F_QPOtherTax
        //            };
        //            return Success("获取成功", obj);
        //        }
        //    }
        //    return Error("获取失败");
        //}
        #endregion
        #region 工单
        /// <summary>
        /// 工单列表
        /// </summary>
        [WechatActionFilter]
        public ActionResult GetWoList()
        {
            workorder.WorkOrderController wo = new workorder.WorkOrderController();
            var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='TimeLimitDays' ").FirstOrDefault();
            int days = config != null ? Convert.ToInt32(config.F_ParamValue) : 60;  //默认60天
            DataTable dt = new DataTable();
            int recordCount = 0;

            string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
            //客户姓名,电话,工单号
            string keyword = HttpUtility.UrlDecode(RequestString.GetQueryString("keyword"));
            //工单状态
            int states = RequestString.GetInt("states", -1);
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            //#region sql 语句相关处理
            string sql = " ";
            //获取坐席表信息
            var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();
            //获取客户档案（业主）表信息
            var modelCustomer = customerBaseBLL.GetModelList(" F_WxOpenId='" + stropenid.Trim() + "'").FirstOrDefault();

            if (!string.IsNullOrEmpty(sql))
            {
                //sql += " and IsDel=0 ";
                ////客户姓名,电话,房间号,工单号，接待描述
                //if (!string.IsNullOrEmpty(keyword))
                //{
                //    sql += " and (CustomerTel like '%" + keyword + "%' or Customer like '%" + keyword + "%' or WorkOrderID like '%" + keyword + "%' or Detail like '%" + keyword + "%' or County like '%" + keyword + "%' ) ";
                //}

                //if (states >= 0)
                //{
                //    #region 权限限制  
                //    if (ua != null)
                //    {
                //        string uwhere = " ";
                //        switch (states)
                //        {
                //            case 0://待指派的
                //                   //sql += " and State ='0' and CreateUser= '" + ua.F_UserCode + "' ";
                //                   //3区域客服可以看到区域待指派工单
                //                if (ua.F_RoleId != 17)
                //                {
                //                    uwhere += " and CreateUser='" + ua.F_UserCode + "' ";
                //                }
                //                sql += " and State =0 " + uwhere;
                //                break;
                //            case 1://待接单的
                //                sql += " and State =" + (int)EnumWorkOrderState.assign + " and T_Wo_WorkOrder.ID in ( " + wo.GetDJDWorkOrderID(ua.F_UserCode) + ") ";
                //                break;
                //            case 2://待完成的(待处理)
                //                sql += " and State in(" + (int)EnumWorkOrderState.dealing + "," + (int)EnumWorkOrderState.receive + "," + (int)EnumWorkOrderState.reback + "," + (int)EnumWorkOrderState.abreback + ") and T_Wo_WorkOrder.ID in ( " + wo.GetDWCWorkOrderID(ua.F_UserCode) + ") ";
                //                break;
                //            case 3://已完成的
                //                sql += " and State =" + (int)EnumWorkOrderState.finish + " and LastDealUser = '" + ua.F_UserCode + "' ";
                //                break;
                //            case 4://我参与的
                //                sql += " and (CreateUser= '" + ua.F_UserCode + "' or T_Wo_WorkOrder.ID in ( " + wo.GetCYWorkOrderID(ua.F_UserCode) + ")) ";
                //                break;
                //            case 5://超期工单 - 设置两个月的处理时效，两个月内未解决的工单都直接汇总到这里
                //                sql += $" and DATEADD(DAY,{days},CreateTime) < GETDATE() AND State < " + (int)EnumWorkOrderState.finish + " ";
                //                break;
                //        }
                //    }
                //    else if (modelCustomer != null)
                //    {
                //        sql += " and ( CustomerID=" + modelCustomer.F_CustomerId + " or County like '%"+modelCustomer.F_CompanyName+"%' )";
                //    }
                //    else
                //    {
                //        sql = "";
                //    }
                //    #endregion
                //}

                //if (strstarttime.Trim() != "" && strstarttime != "undefined")
                //{
                //    sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
                //}
                //if (strendtime.Trim() != "" && strendtime != "undefined")
                //{
                //    sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
                //}
                //#endregion
                //if (strpageindex.Trim() != "")
                //{
                //    pageindex = Convert.ToInt32(strpageindex);
                //}
                //if (strpagesize.Trim() != "")
                //{
                //    pagesize = Convert.ToInt32(strpagesize);
                //}
                //string cols = "*,dbo.GetDictionaryName(Source) as GDLYName,dbo.GetDictionaryName(Type) as GDLXName,dbo.GetDictionaryName(TypeClass) as TypeClassName,dbo.GetUserName(CreateUser) as CreateUserNameRel,dbo.GetUserName(LastDealUser) as LastDealUserNameRel,dbo.GetUserName(AuditUser) as AuditUserNameRel,dbo.GetDeptName(ResponDept) as ResponDeptName";
                //dt = BLL.PagerBLL.GetListPager(
                //    "T_Wo_WorkOrder (NOLOCK)",
                //    "WorkOrderID",
                //    cols,
                //    sql,
                //    "ORDER BY CreateTime DESC,State asc",
                //    pagesize,
                //    pageindex,
                //    true,
                //    out recordCount);
            }
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 工单详情
        /// </summary>
        [WechatActionFilter]
        public ActionResult GetWoInfo()
        {
            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
            string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
            if (string.IsNullOrEmpty(strworkorderid))
                return Error("参数错误");
            if (string.IsNullOrEmpty(stropenid))
                return Error("参数错误!");
            //string sql = "select *,dbo.GetDictionaryName(Type) as GDLXName,dbo.GetDictionaryName(TypeClass) as YWLXName,dbo.GetDictionaryName(Source) as GDLYName,dbo.GetUserName(CreateUser) as CreateUserName,dbo.GetUserName(LastDealUser) as LastDealUserNameRel,dbo.GetUserName(AuditUser) as AuditUserNameRel,dbo.GetUserName(ResponUser) as ResponUserName,dbo.GetDeptName(ResponDept) AS ComplaintDepartment "
            //           + " from T_Wo_WorkOrder where T_Wo_WorkOrder.ID ='" + strworkorderid + "' ";
            //var dt = DbHelperSQL.Query(sql).Tables[0];
            //if (dt.Rows.Count > 0)
            //{
            //    var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            //    var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

            //    if (configfj != null)
            //    {
            //        dt = BindFileData(dt, configfj.F_ParamValue);
            //    }

            //    string gcsql = "select *,dbo.GetUserName(F_NextUser) as F_NextUserName, dbo.GetDeptName(F_NextDept) as F_NextDeptName,dbo.GetUserName(F_CreateUser) as F_CreateUserName  "
            //                        + "from T_Wo_WorkOrderItem_New where F_WoID ='" + strworkorderid + "'";
            //    var gcdt = DbHelperSQL.Query(gcsql).Tables[0];

            //    dt.Columns.Add("FilePath", typeof(string));
            //    if (configfj != null || config != null)
            //    {
            //        foreach (DataRow bldr in dt.Rows)
            //        {
            //            if (bldr["CallID"] != null && config != null)
            //            {
            //                bldr["FilePath"] = GetCallPath(bldr["CallID"].ToString(), config.F_ParamValue);
            //            }
            //        }
            //    }
            //    var obj = new
            //    {
            //        data = dt,
            //        item = gcdt
            //    };
            //    return Success("查询成功", obj);
            //}
            return Error("查询失败");
        }
        #region 在用工单操作
        ///// <summary>
        /////  处理工单
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult DealWorkOrder(long orderid, string cont, int isover = 0)
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        Model.T_Sys_UserAccount ua = userAccountBLL.GetModelByOpenid(stropenid);
        //        if (ua != null)
        //        {
        //            Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
        //            if (model != null)
        //            {
        //                bool res = new workorder.WorkOrderController().DealWO(ua, model, cont, isover);
        //                if (res)
        //                    return Success("处理成功");
        //                else
        //                    return Error("操作失败");
        //            }
        //            else
        //                return Error("工单不存在");
        //        }
        //        else
        //            return Error("无操作权限");
        //    }
        //    else
        //        return Error("参数错误");
        //}

        ///// <summary>
        ///// 接单 - 确认工单
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult SureWorkOrder(long orderid)
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        var ua = userAccountBLL.GetModelByOpenid(stropenid);
        //        if (ua != null)
        //        {
        //            Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
        //            if (model != null)
        //            {
        //                bool res = new workorder.WorkOrderController().SureWO(ua, model);
        //                if (res)
        //                    return Success("接单成功");
        //                else
        //                    return Error("操作失败");
        //            }
        //            else
        //                return Error("工单不存在");
        //        }
        //        else
        //            return Error("无操作权限");
        //    }
        //    else
        //        return Error("参数错误");
        //}

        ///// <summary>
        ///// 指派/转派工单
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult AssignWorkOrder(long orderid, string cont, int clbm = 0, int clid = 0)
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        var ua = userAccountBLL.GetModelByOpenid(stropenid);
        //        if (ua != null)
        //        {
        //            if (clbm != 0 && clid == 0)
        //                return Error("请选择接收人");
        //            Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
        //            if (model != null)
        //            {
        //                var res = new workorder.WorkOrderController().AssignWO(ua, model, cont, clbm, clid);
        //                if (res)
        //                    return Success("转派成功");
        //                else
        //                    return Error("转派失败！");
        //            }
        //            else
        //                return Error("工单不存在！");
        //        }
        //    }
        //    return Error("无操作权限！");
        //}

        ///// <summary>
        ///// 退回工单
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult BackWorkOrder(long orderid, string cont,int type=0)
        //{//办理人员和监管可以退回工单
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        var ua = userAccountBLL.GetModelByOpenid(stropenid);
        //        if (ua != null)
        //        {
        //            Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
        //            //验证信息
        //            if (model != null)
        //            {
        //                var res = new workorder.WorkOrderController().BackWO(ua, model, cont, type);
        //                if (res)
        //                    return Success("处理成功");
        //                else
        //                    return Error("处理失败！");
        //            }
        //            return Error("工单不存在");
        //        }
        //    }
        //    return Error("无操作权限");
        //}

        ///// <summary>
        ///// 催办工单
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult AddWorkOrderRemind(long orderid, string cont)
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        var ua = userAccountBLL.GetModelByOpenid(stropenid);
        //        if (ua != null)
        //        {
        //            Model.T_Wo_WorkOrder model = woBLL.GetModel(orderid);
        //            if (model != null)
        //            {
        //                var res = new workorder.WorkOrderController().RemindWO(ua, model, cont);
        //                if (res)
        //                    Success("催办成功！");
        //                else
        //                    Success("操作失败！");
        //            }
        //            return Error("工单不存在！");
        //        }
        //    }
        //    return Error("无操作权限！");
        //}
        #endregion
        #endregion

        #region 公告通知
        /// <summary>
        /// 获取公告列表
        /// </summary>
        /// <returns></returns>
        //[WechatActionFilter]
        public ActionResult GetNoticeList()
        {
            DataTable dt = new DataTable(); int recordCount = 0;
            string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            #region sql 语句相关处理
            string sql = " and F_isDel=0 ";
            //获取坐席表信息
            var ua = userAccountBLL.GetModelByOpenid(stropenid);
            //获取客户档案（业主）表信息
            var modelCustomer = customerBaseBLL.GetModelByOpenid(stropenid);
            if (ua != null)
            {
                sql += " and (ISNULL(F_UserId,'') = '' or ISNULL(F_UserId,'') like '%," + ua.F_UserId + ",%')";
            }
            else if (modelCustomer != null) {
                sql += " and F_isCus=1";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateOn,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateOn,'" + strendtime + "')>=0   ";
            }
            #endregion
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            dt = BLL.PagerBLL.GetListPager(
            "T_Msg_NoticeInfo",
            "F_NoticeId",
            "*",
            sql,
            "ORDER BY F_NoticeId desc",
            pagesize,
            pageindex,
            true,
            out recordCount);
            List<Model.T_Msg_NoticeInfo> msgList = new BLL.T_Msg_NoticeInfo().DataTableToList(dt);
            List<Model.T_Sys_UserAccount> userList = new BLL.T_Sys_UserAccount().GetModelList("");
            var obj = new
            {
                rows = msgList.Select(m =>
                {
                    Model.T_Sys_UserAccount usermodel = userList.Where(u => u.F_UserId == m.F_CreateBy.Value).FirstOrDefault();
                    var uname = "";
                    if (usermodel != null)
                        uname = usermodel.F_UserName;
                    return new
                    {
                        F_NoticeId = m.F_NoticeId,
                        F_Title = m.F_Title,
                        F_Content = m.F_Content,
                        F_isCus = m.F_isCus,
                        F_CreateOn = m.F_CreateOn,
                        F_CreateBy = m.F_CreateBy,
                        F_CreateByName = uname
                    };
                }),
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 获取公告详情
        /// </summary>
        /// <returns></returns>
        //[WechatActionFilter]
        public ActionResult GetNoticeInfo()
        {
            string strnoticeid = HttpUtility.UrlDecode(RequestString.GetQueryString("noticeid"));
            string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
            if (string.IsNullOrEmpty(strnoticeid))
                return Error("参数错误");
            if (string.IsNullOrEmpty(stropenid))
                return Error("参数错误!");
            var dModel = new BLL.T_Msg_NoticeInfo().GetModel(int.Parse(strnoticeid.Trim()));
            Model.T_Sys_UserAccount userModel = new Model.T_Sys_UserAccount();

            if (dModel != null)
            {
                if (dModel.F_CreateBy != null)
                    userModel = userAccountBLL.GetModel(dModel.F_CreateBy.Value);
                var uname = "";
                if (userModel != null)
                    uname = userModel.F_UserName;
                #region 标记为已读
                var nowUser = userAccountBLL.GetModelByOpenid(stropenid);
                var nowCus = customerBaseBLL.GetModelByOpenid(stropenid);
                var usercode = "";
                if (nowUser != null)
                {
                    usercode = nowUser.F_UserCode;
                    var msglist = new BLL.T_Msg_List().GetModelList(" State=0 and ToUser='" + usercode + "' and Type=5 and ToID=" + dModel.F_NoticeId);
                    foreach (var item in msglist)
                    {
                        item.State = 1;
                        item.ReadDate = DateTime.Now;
                        new BLL.T_Msg_List().Update(item);
                    }

                }
                else if (nowCus != null)
                {
                    usercode = nowCus.F_CustomerCode;
                    Model.T_Msg_List msg = new Model.T_Msg_List();
                    msg.Type = (int)Model.MSGType.cusnotice;
                    msg.ToUser = usercode;
                    msg.ToID = dModel.F_NoticeId;
                    msg.Detail = "客户" + usercode + "查看了公告《" + dModel.F_Title + "》";
                    msg.State = 1;
                    msg.IsDel = 0;
                    msg.CreateDate = DateTime.Now;
                    msg.ReadDate = DateTime.Now;
                    new BLL.T_Msg_List().Add(msg);
                }
                #endregion
                var obj = new
                {
                    F_NoticeId = dModel.F_NoticeId,
                    F_Title = dModel.F_Title,
                    F_Content = dModel.F_Content,
                    F_isCus = dModel.F_isCus,
                    F_CreateOn = dModel.F_CreateOn,
                    F_CreateBy = dModel.F_CreateBy,
                    F_CreateByName = uname,
                    F_UserId = dModel.F_UserId,
                    F_RoleId = dModel.F_RoleId,
                };
                return Success("获取公告详情成功", dModel);
            }
            else
                return Error("获取公告详情失败");
        }
        #endregion

        #region 微信工单

        ///// <summary>
        ///// 获取工单列表
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult GetList()
        //{
        //    workorder.WorkOrderController wo = new workorder.WorkOrderController();
        //    var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='TimeLimitDays' ").FirstOrDefault();
        //    int days = config != null ? Convert.ToInt32(config.F_ParamValue) : 60;  //默认60天
        //    DataTable dt = new DataTable();
        //    int recordCount = 0;

        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
        //    //客户姓名,电话,房间号,工单号
        //    string keyword = HttpUtility.UrlDecode(RequestString.GetQueryString("keyword"));
        //    //工单状态(ltype:)
        //    string strltype = HttpUtility.UrlDecode(RequestString.GetQueryString("ltype"));
        //    //工单状态
        //    int states = RequestString.GetInt("states", -1);
        //    //工单来源
        //    int strtype = RequestString.GetInt("type", 0);
        //    //工单类型
        //    int strtypeclass = RequestString.GetInt("typeclass", 0);
        //    //工单起止时间
        //    string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
        //    string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
        //    //来电单位
        //    string lddep = HttpUtility.UrlDecode(RequestString.GetQueryString("lddep"));
        //    //20180329 来电弹屏工单记录根据反馈单位获取列表 可以看到同一坐席组的所有人的工单记录
        //    string fkdep = HttpUtility.UrlDecode(RequestString.GetQueryString("fkdep"));
        //    int isldtp = RequestString.GetQueryInt("isldtp", 0);
        //    //微信列表（0未审核微信列表，1已审核微信列表）
        //    int isaudit = RequestString.GetInt("isaudit", -1);
        //    string strpageindex = RequestString.GetQueryString("page");
        //    int pageindex = 1;
        //    string strpagesize = RequestString.GetQueryString("pagesize");
        //    int pagesize = 10;

        //    #region sql 语句相关处理
        //    string sql = " ";
        //    //获取坐席表信息
        //    var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();
        //    //获取客户档案（业主）表信息
        //    var modelCustomer = customerBaseBLL.GetModelList(" F_WxOpenId='" + stropenid.Trim() + "'").FirstOrDefault();
        //    #region 权限限制      
        //    string mobile = "", roomno = "";
        //    int customerid = 0, areaid = 0, proid = 0, buildingid = 0;

        //    if (ua != null)
        //    {
        //        int deptid = ua.F_DeptId;         //部门id
        //        string deptCode = ua.F_DeptCode;  //部门code
        //        int userRegionId = ua.RegionId;  //项目id
        //        //部门信息
        //        var modelDep = new BLL.T_Sys_Department().GetModel(deptid);
        //        int depType = 0, depRegion = 0;
        //        if (modelDep != null)
        //        {
        //            depType = modelDep.F_Type ?? 0;  //部门操作权限：1接待部，2办理人员，3区域客服，4监管
        //            depRegion = modelDep.F_Header ?? 0; //部门权限范围：9全部，1区域，2项目，3期
        //        }
        //        if (ua.F_RoleId != 17)
        //        {
        //            if (depType == 2)
        //            {
        //                if (depRegion == 1)
        //                {
        //                    // 查看该区域工单
        //                    //sql += $" and IsUserSend = (SELECT TOP 1 F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId}) ";
        //                    sql += $" and IsUserSend = {userRegionId} ";
        //                }
        //                else if (depRegion == 2)
        //                {
        //                    // 查看该项目工单
        //                    sql += $" and IsAdminSend = {userRegionId} ";
        //                }
        //            }
        //            else if (depType == 3)
        //            {
        //                if (depRegion == 1)
        //                {
        //                    // 查看该区域工单
        //                    //sql += $" and IsUserSend = (SELECT TOP 1 F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId}) ";
        //                    sql += $" and IsUserSend = {userRegionId} ";
        //                }
        //            }
        //            else if (depType == 4)
        //            {
        //                if (depRegion == 2)
        //                {
        //                    // 查看该项目工单
        //                    sql += $" and IsAdminSend = {userRegionId} ";
        //                }
        //                else if (depRegion == 9)
        //                {
        //                    // 查看该部门工单（包括一级，二级）
        //                    string deptCodeNew = String.Empty;
        //                    int deptCodeIndex = 0;                                  //变量声明
        //                    string deptCodeN = deptCode.TrimEnd('|');      //去掉最后一个|
        //                    deptCodeIndex = deptCodeN.LastIndexOf("|");             //获得|的索引
        //                    deptCodeNew = deptCodeN.Substring(0, deptCodeIndex + 1);    //获得目标字符串（//去掉最后一个|后面的字符串）
        //                                                                                //============== 部门权限条件 - 部门 ================
        //                    string arrUser = " select F_UserCode from T_Sys_UserAccount where F_DeptCode LIKE '" + deptCodeNew + "%' ";
        //                    sql += $" and WorkOrderID in (SELECT DISTINCT WorkOrderID FROM dbo.T_Wo_WorkOrderItem WHERE ToUser IN ({arrUser})) ";
        //                }
        //            }
        //        }
        //        string uwhere = " ";
        //        switch (strltype)
        //        {
        //            case "0"://待指派的
        //                     //sql += " and State ='0' and CreateUser= '" + ua.F_UserCode + "' ";
        //                if (ua.F_RoleId != 17 && depType != 1 && depType != 3)
        //                {
        //                    uwhere += " and CreateUser='" + ua.F_UserCode + "' ";
        //                }
        //                sql += " and State ='0' " + uwhere;
        //                break;
        //            case "1"://待接单的
        //                sql += " and State ='1' and WorkOrderID in ( '" + wo.GetDJDWorkOrderID(ua.F_UserCode) + "') ";
        //                break;
        //            case "2"://待完成的
        //                sql += " and State ='1' and WorkOrderID in ( '" + wo.GetDWCWorkOrderID(ua.F_UserCode) + "') ";
        //                break;
        //            case "3"://已完成的
        //                sql += " and State ='2' and LastDealUser = '" + ua.F_UserCode + "' ";
        //                break;
        //            case "4"://我参与的
        //                sql += " and (CreateUser= '" + ua.F_UserCode + "' or WorkOrderID in ( '" + wo.GetCYWorkOrderID(ua.F_UserCode) + "')) ";
        //                break;
        //            case "5"://超期工单 - 设置两个月的处理时效，两个月内未解决的工单都直接汇总到这里
        //                sql += $" and DATEADD(DAY,{days},CreateTime) < GETDATE() AND State < 2 ";
        //                break;
        //        }
        //    }
        //    else if (modelCustomer != null)
        //    {
        //        #region 根据openid获取所有工单号
        //        //var wxuser = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + stropenid.Trim() + "' and F_Type=1 ").FirstOrDefault();
        //        //if (wxuser != null)
        //        //{
        //        //    sql += " and id in (select distinct F_WorkOrderID from T_WO_UserWorkOrder where F_UserId='" + wxuser.F_Id + "') ";
        //        //}
        //        #endregion
        //        // ============== 项目权限 - 项目 ============== 不通过项目查询，因为客户可能有多个项目的房产
        //        // ============== 电话，区域，项目，楼号，房间号权限条件 - 电话 ================
        //        //通过相关电话，区域，项目，楼号，房间号（CustomerTel,IsUserSend,IsAdminSend,IsTimeOut,Address）查询该用户查看的工单
        //        //mobile = modelCustomer.F_LegalTel;
        //        customerid = modelCustomer.F_CustomerId;
        //        //int CustomerClassID = modelCustomer.F_CustomerClassID ?? 0;
        //        ////F_Layer区域id F_CategoryId所购项目id F_CustomerType楼号 F_BusinessLicenseID房间号
        //        //areaid = modelCustomer.F_Layer ?? 0;
        //        //proid = modelCustomer.F_CategoryId ?? 0;
        //        //buildingid = modelCustomer.F_CustomerType ?? 0;
        //        //roomno = modelCustomer.F_BusinessLicenseID;

        //        ////查询业主和相关的亲属租户名下工单
        //        //sql += $" and CustomerTel IN (SELECT DISTINCT F_Mobile FROM dbo.T_Cus_CustomerBase WHERE F_CustomerClassID = {customerid} OR F_CustomerId = {customerid})  ";
        //        //if (CustomerClassID == 0)
        //        //{
        //        //    //业主查看房屋所有工单
        //        //    sql += $" and CustomerID IN (SELECT DISTINCT F_CustomerId FROM dbo.T_Cus_CustomerBase WHERE F_CustomerClassID = {customerid} OR F_CustomerId = {customerid})  ";
        //        //}
        //        //else
        //        //{
        //        //    //租户只可查看自己工单
        //        //    sql += $" and CustomerID = {customerid} ";
        //        //}

        //        ////查询相关房间号下工单
        //        //if (areaid > 0 && proid > 0 && buildingid > 0 && !string.IsNullOrEmpty(roomno))
        //        //{
        //        //    sql += $" and F_Layer = {areaid} and  F_CategoryId = {proid} and  F_CustomerType = {buildingid} and  F_BusinessLicenseID = '{roomno}'  ";
        //        //}
        //    }
        //    else
        //    {
        //        sql = "";
        //    }
        //    #endregion

        //    if (!string.IsNullOrEmpty(sql))
        //    {
        //        sql += " and IsDel=0 ";
        //        //客户姓名,电话,房间号,工单号，接待描述
        //        if (!string.IsNullOrEmpty(keyword))
        //        {
        //            sql += " and (CustomerTel like '%" + keyword + "%' or Customer like '%" + keyword + "%' or Address like '%" + keyword + "%' or WorkOrderID like '%" + keyword + "%' or Detail like '%" + keyword + "%' ) ";
        //        }
        //        if (isaudit >= 0)
        //        {
        //            sql += " and IsAudit = " + isaudit + " ";   // ANd Type = (SELECT F_DictionaryValueId FROM dbo.T_Sys_DictionaryValue (NOLOCK) WHERE F_DictionaryFlag = 'GDLY' AND F_Name = '微信')
        //        }
        //        if (states >= 0)
        //            sql += " and State = " + states + " ";
        //        if (strtype > 0)
        //        {
        //            sql += " and Type = " + strtype + " ";
        //        }
        //        if (strtypeclass > 0)
        //        {
        //            sql += " and TypeClass = " + strtypeclass + " ";
        //        }
        //        if (lddep.Trim() != "" && lddep != "undefined")
        //        {
        //            sql += " and Address = '" + lddep.Trim() + "' ";
        //        }
        //        if (fkdep.Trim() != "" && fkdep != "undefined")
        //        {
        //            sql += " and Source = '" + fkdep.Trim() + "' ";
        //        }
        //        if (strstarttime.Trim() != "" && strstarttime != "undefined")
        //        {
        //            sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
        //        }
        //        if (strendtime.Trim() != "" && strendtime != "undefined")
        //        {
        //            sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
        //        }
        //        #endregion
        //        if (strpageindex.Trim() != "")
        //        {
        //            pageindex = Convert.ToInt32(strpageindex);
        //        }
        //        if (strpagesize.Trim() != "")
        //        {
        //            pagesize = Convert.ToInt32(strpagesize);
        //        }
        //        string cols = "*,dbo.GetDictionaryName(Source) as GDLYName,dbo.GetDictionaryName(Type) as GDLXName,dbo.GetDictionaryName(TypeClass) as TypeClassName,dbo.GetUserName(CreateUser) as CreateUserNameRel,dbo.GetUserName(LastDealUser) as LastDealUserNameRel,dbo.GetUserName(AuditUser) as AuditUserNameRel,dbo.GetDeptName(ResponDept) as ResponDeptName";
        //        dt = BLL.PagerBLL.GetListPager(
        //            "T_Wo_WorkOrder (NOLOCK)",
        //            "WorkOrderID",
        //            cols,
        //            sql,
        //            "ORDER BY CreateTime DESC",
        //            pagesize,
        //            pageindex,
        //            true,
        //            out recordCount);
        //    }
        //    var obj = new
        //    {
        //        state = "success",
        //        message = "成功",
        //        rows = dt,
        //        total = recordCount
        //    };
        //    return Content(obj.ToJson());

        //}

        ///// <summary>
        ///// 获取可催办工单列表
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult GetNotDoneWorkList()
        //{
        //    workorder.WorkOrderController wo = new workorder.WorkOrderController();
        //    DataTable dt = new DataTable();
        //    int recordCount = 0;
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
        //    //客户姓名,电话,房间号,工单号
        //    string keyword = HttpUtility.UrlDecode(RequestString.GetQueryString("keyword"));
        //    //工单状态
        //    string strltype = HttpUtility.UrlDecode(RequestString.GetQueryString("ltype"));
        //    //工单状态
        //    int states = RequestString.GetInt("states", -1);
        //    //工单来源
        //    int strtype = RequestString.GetInt("type", 0);
        //    //工单类型
        //    int strtypeclass = RequestString.GetInt("typeclass", 0);
        //    //工单起止时间
        //    string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
        //    string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
        //    //区域id
        //    int areaid = RequestString.GetInt("areaid", 0);
        //    //项目id
        //    int regionid = RequestString.GetInt("regionid", 0);
        //    //期id
        //    int buldingid = RequestString.GetInt("buldingid", 0);
        //    string uid = HttpUtility.UrlDecode(RequestString.GetQueryString("userid") == "" ? "0" : HttpUtility.UrlDecode(RequestString.GetQueryString("userid")));
        //    string strpageindex = RequestString.GetQueryString("page");
        //    int pageindex = 1;
        //    string strpagesize = RequestString.GetQueryString("pagesize");
        //    int pagesize = 10;

        //    string sql = " and isdel=0 and State != 2 ";
        //    //获取坐席表信息
        //    var ua = userAccountBLL.GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();
        //    //获取客户档案（业主）表信息
        //    var modelCustomer = customerBaseBLL.GetModelList(" F_WxOpenId='" + stropenid.Trim() + "'").FirstOrDefault();
        //    if (ua != null)
        //    {
        //        #region 权限限制

        //        int deptid = ua.F_DeptId;         //部门id
        //        string deptCode = ua.F_DeptCode;  //部门code
        //        int userRegionId = ua.RegionId;  //项目id
        //        //部门信息
        //        var modelDep = new BLL.T_Sys_Department().GetModel(deptid);
        //        int depType = 0, depRegion = 0;
        //        if (modelDep != null)
        //        {
        //            depType = modelDep.F_Type ?? 0;  //部门操作权限：1接待部，2办理人员，3区域客服，4监管
        //            depRegion = modelDep.F_Header ?? 0; //部门权限范围：9全部，1区域，2项目，3期
        //        }
        //        if (ua.F_RoleId != 17)
        //        {
        //            if (depType == 2)
        //            {
        //                if (depRegion == 1)
        //                {
        //                    // 查看该区域工单
        //                    //sql += $" and IsUserSend = (SELECT TOP 1 F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId}) ";
        //                    sql += $" and IsUserSend = {userRegionId} ";
        //                }
        //                else if (depRegion == 2)
        //                {
        //                    // 查看该项目工单
        //                    sql += $" and IsAdminSend = {userRegionId} ";
        //                }
        //            }
        //            else if (depType == 3)
        //            {
        //                if (depRegion == 1)
        //                {
        //                    // 查看该区域工单
        //                    //sql += $" and IsUserSend = (SELECT TOP 1 F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId}) ";
        //                    sql += $" and IsUserSend = {userRegionId} ";
        //                }
        //            }
        //            else if (depType == 4)
        //            {
        //                if (depRegion == 2)
        //                {
        //                    // 查看该项目工单
        //                    sql += $" and IsAdminSend = {userRegionId} ";
        //                }
        //                else if (depRegion == 9)
        //                {
        //                    // 查看该部门工单（包括一级，二级）
        //                    string deptCodeNew = String.Empty;
        //                    int deptCodeIndex = 0;                                  //变量声明
        //                    string deptCodeN = deptCode.TrimEnd('|');      //去掉最后一个|
        //                    deptCodeIndex = deptCodeN.LastIndexOf("|");             //获得|的索引
        //                    deptCodeNew = deptCodeN.Substring(0, deptCodeIndex + 1);    //获得目标字符串（//去掉最后一个|后面的字符串）
        //                                                                                //============== 部门权限条件 - 部门 ================
        //                    string arrUser = " select F_UserCode from T_Sys_UserAccount where F_DeptCode LIKE '" + deptCodeNew + "%' ";
        //                    sql += $" and WorkOrderID in (SELECT DISTINCT WorkOrderID FROM dbo.T_Wo_WorkOrderItem WHERE ToUser IN ({arrUser})) ";
        //                }
        //            }
        //        }
        //        #endregion

        //        //客户姓名,电话,房间号,工单号
        //        if (!string.IsNullOrEmpty(keyword))
        //        {
        //            sql += " and (CustomerTel like '%" + keyword + "%' or Customer like '%" + keyword + "%' or Address like '%" + keyword + "%' or WorkOrderID like '%" + keyword + "%' ) ";
        //        }
        //        if (states >= 0)
        //            sql += " and State = " + states + " ";
        //        if (areaid > 0)
        //            sql += " and IsUserSend = " + areaid + " ";
        //        if (regionid > 0)
        //            sql += " and IsAdminSend = " + regionid + " ";
        //        if (buldingid > 0)
        //            sql += " and IsTimeOut = " + buldingid + " ";
        //        //坐席工号
        //        if (uid.Trim() != "" && uid != "0")
        //        {
        //            sql += " and CreateUser = '" + uid + "' ";
        //        }
        //        if (strtype > 0)
        //        {
        //            sql += " and Type = " + strtype + " ";
        //        }
        //        if (strtypeclass > 0)
        //        {
        //            sql += " and TypeClass = " + strtype + " ";
        //        }
        //        if (strstarttime.Trim() != "" && strstarttime != "undefined")
        //        {
        //            sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
        //        }
        //        if (strendtime.Trim() != "" && strendtime != "undefined")
        //        {
        //            sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
        //        }
        //        if (strpageindex.Trim() != "")
        //        {
        //            pageindex = Convert.ToInt32(strpageindex);
        //        }
        //        if (strpagesize.Trim() != "")
        //        {
        //            pagesize = Convert.ToInt32(strpagesize);
        //        }
        //        dt = BLL.PagerBLL.GetListPager(
        //            "T_Wo_WorkOrder",
        //            "T_Wo_WorkOrder.ID",
        //            "*,(SELECT F_RegionName FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = dbo.T_Wo_WorkOrder.IsUserSend) AS areaname,(SELECT F_RegionName FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = dbo.T_Wo_WorkOrder.IsAdminSend) AS proname,(SELECT F_RegionName FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = dbo.T_Wo_WorkOrder.IsTimeOut) AS buildingname,dbo.GetDictionaryName(Type) as GDLYName,dbo.GetDictionaryName(Ownerrelationsid) as OwnerrelationsName,dbo.GetDictionaryName(TypeClass) as TypeClassName,dbo.GetUserName(CreateUser) as CreateUserNameRel,dbo.GetUserName(LastDealUser) as LastDealUserNameRel,dbo.GetUserName(AuditUser) as AuditUserNameRel,(SELECT TOP 1 F_DeptName FROM dbo.T_Sys_Department WHERE F_DeptId = Source) AS complaintTypeName",
        //            sql,
        //            "ORDER BY T_Wo_WorkOrder.ID desc",
        //            pagesize,
        //            pageindex,
        //            true,
        //            out recordCount);
        //        dt.Columns.Add("CBCount", typeof(int));
        //        foreach (DataRow dr in dt.Rows)
        //        {
        //            var list = new BLL.T_Wo_WorkOrderItem().GetList(" WorkOrderID='" + dr["WorkOrderID"].ToString() + "' and IsDel=0 and Type=2 and ','+ToUser+',' like ',%" + ua.F_UserCode + "%,' ").Tables[0];
        //            dr["CBCount"] = list.Rows.Count;
        //        }
        //    }
        //    var obj = new
        //    {
        //        state = "success",
        //        message = "成功",
        //        rows = dt,
        //        total = recordCount
        //    };
        //    return Content(obj.ToJson());
        //}

        ///// <summary>
        /////  新增工单
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult AddWorkOrder()
        //{
        //    DataTable dt = new DataTable();
        //    //工单来源
        //    int gdly = RequestString.GetFormInt("gdly", 0);
        //    //工单类型
        //    int gdlx = RequestString.GetFormInt("gdlx", 0);
        //    //客户id
        //    int customerid = RequestString.GetFormInt("customerid", 0);
        //    //客户姓名
        //    string callCustomer = RequestString.GetFormString("callCustomer");
        //    //联系电话
        //    string tel = RequestString.GetFormString("tel");

        //    //处理部门
        //    string fkdep = RequestString.GetFormString("fkdep");
        //    //客服类类型
        //    string kfdepid = RequestString.GetFormString("kfdepid");

        //    //受理人 - 审核人工号
        //    string auditusercode = RequestString.GetFormString("auditusercode");
        //    //工单状态
        //    int gdzt = RequestString.GetFormInt("gdzt", 0);
        //    //接待描述 - 反馈内容
        //    string fkcont = RequestString.GetFormString("fkcont");
        //    string callid = HttpUtility.UrlDecode(RequestString.GetFormString("callid"));
        //    string files = RequestString.GetFormString("files");

        //    //咨询类工单指派部门
        //    int clbm = RequestString.GetFormInt("clbm", 0);
        //    //备注
        //    string note = RequestString.GetFormString("note");
        //    #region 添加验证判断
        //    if (string.IsNullOrEmpty(callCustomer))
        //        return Error("姓名不能为空！");
        //    if (string.IsNullOrEmpty(tel))
        //        return Error("电话不能为空！");
        //    #endregion

        //    string workOrder = DateTime.Now.ToString("yyyyMMddHHmmssfff");  //工单编号     
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    var wxuser = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + stropenid.Trim() + "'  and F_Type=1 ").FirstOrDefault();
        //    var model = userAccountBLL.GetModelByOpenid(stropenid);
        //    var modelCustomer = customerBaseBLL.GetModelList(" F_WxOpenId='" + stropenid.Trim() + "'").FirstOrDefault(); //customerBaseBLL.GetModelByOpenid(stropenid);
        //    string usercode = "";
        //    if (model != null)
        //    {
        //        usercode = model.F_UserCode;
        //    }
        //    else if (modelCustomer != null)
        //    {
        //        usercode = modelCustomer.F_CustomerCode;
        //        customerid = modelCustomer.F_CustomerId;
        //    }
        //    workorder.WorkOrderController wo = new workorder.WorkOrderController();
        //    string workorderid = wo.AddWXWorkOrder(workOrder, gdly, gdlx, customerid, callCustomer, tel, fkdep, kfdepid, auditusercode, fkcont, files, gdzt, note, usercode,-1);
        //    if (string.IsNullOrEmpty(workorderid))
        //    {
        //        return Error("新增失败");
        //    }
        //    else
        //    {
        //        #region 咨询类工单指派至部门
        //        //工单类型(107咨询,108投诉)
        //        if (gdlx == 107)
        //        {
        //            //需要审核后，再处理
        //            //bool b = wo.DealWXWorkOrder(workOrder, 0, 0, clbm, 0, "", fkcont, stropenid);
        //        }
        //        #endregion
        //        //暂时排除客户档案用户（F_UserId无法区分是住户添加 还是管理员添加） - 后期完善
        //        if (wxuser != null)
        //        {
        //            Model.T_WO_UserWorkOrder tbu = new Model.T_WO_UserWorkOrder();
        //            tbu.F_UserId = wxuser.F_Id;
        //            tbu.F_WorkOrderId = workorderid;
        //            new BLL.T_WO_UserWorkOrder().Add(tbu);
        //        }
        //        return Success("新增成功", workorderid);
        //    }
        //}

        ///// <summary>
        /////  修改工单
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult UpdateWorkOrder()
        //{
        //    DataTable dt = new DataTable();
        //    //工单id
        //    string workorderid = RequestString.GetFormString("orderid");
        //    //工单来源
        //    int gdly = RequestString.GetFormInt("gdly", 0);
        //    //工单类型
        //    int gdlx = RequestString.GetFormInt("gdlx", 0);
        //    //客户id
        //    int customerid = RequestString.GetFormInt("customerid", 0);
        //    //客户姓名
        //    string callCustomer = RequestString.GetFormString("callCustomer");
        //    //联系电话
        //    string tel = RequestString.GetFormString("tel");

        //    //处理部门
        //    string fkdep = RequestString.GetFormString("fkdep");
        //    //客服类类型
        //    string kfdepid = RequestString.GetFormString("kfdepid");

        //    //受理人 - 审核人工号
        //    string auditusercode = RequestString.GetFormString("auditusercode");
        //    //接待描述 - 反馈内容
        //    string fkcont = RequestString.GetFormString("fkcont");
        //    string files = RequestString.GetFormString("files");

        //    //备注
        //    string note = RequestString.GetFormString("note");

        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    //var wxuser = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + stropenid.Trim() + "'  and F_Type=1 ").FirstOrDefault();
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        var ua = new BLL.T_Sys_UserAccount().GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();
        //        if (ua != null)
        //        {
        //            WorkOrderController wo = new WorkOrderController();
        //            if (!string.IsNullOrEmpty(workorderid))
        //            {
        //                var models = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + workorderid + "'");
        //                if (models.Count > 0)
        //                {
        //                    var model = models.FirstOrDefault();
        //                    string detail = model.Detail;
        //                    model.Type = gdly;              //工单来源                    
        //                    model.TypeClass = gdlx;         //投诉类型 -工单类型
        //                    model.Customer = callCustomer;  //客户姓名
        //                    model.CustomerTel = tel;        //联系电话  
        //                    //model.CustomerID = customerid;  //用户档案Id

        //                    model.Source = fkdep;  //处理部门 反馈单位  
        //                    model.CreateUserID = kfdepid;  //客服类类型           
        //                    model.AuditUser = auditusercode;  //受理人 - 审核人工号
        //                    //model.CreateUser = ua.F_UserCode;      //接待人(工号)
        //                                                           //model.State = 0;                //工单状态
        //                                                           //反馈内容
        //                    var detailutf8 = System.Web.HttpUtility.UrlDecode(fkcont, System.Text.Encoding.UTF8);
        //                    model.Detail = detailutf8;

        //                    if (new BLL.T_Wo_WorkOrder().Update(model))
        //                    {
        //                        //添加工单修改操作日志
        //                        wo.WriteWorkOrderLog(workorderid, detail, detailutf8, ua.F_UserCode, 0, "", 1, "修改工单(微信端)");
        //                        return Success("修改成功！");
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    return Error("修改失败！");
        //}

        ///// <summary>
        /////  处理工单
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult DealWorkOrder()
        //{
        //    DataTable dt = new DataTable();
        //    string orderid = RequestString.GetFormString("orderid");
        //    int isend = RequestString.GetInt("isend", 0);   //0转派
        //    int ltype = RequestString.GetInt("ltype", 0);   //处理方式 1结束  0转派
        //    int clbm = RequestString.GetInt("clbm", 0);     //部门id
        //    int clid = RequestString.GetInt("clid", 0);     //用户接收人id                         
        //    string cont = RequestString.GetFormString("cont");  //处理内容
        //    string detail = RequestString.GetFormString("detail");

        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));

        //    workorder.WorkOrderController wo = new workorder.WorkOrderController();
        //    bool res = wo.DealWXWorkOrder(orderid, isend, ltype, clbm, clid, cont, detail, stropenid);

        //    if (res)
        //    {
        //        return Success("操作成功");
        //    }
        //    else
        //    {
        //        return Error("操作失败");
        //    }
        //}

        ///// <summary>
        ///// 接单 - 确认工单
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult SureWorkOrder()
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    string orderid = RequestString.GetFormString("orderid");
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        var ua = new BLL.T_Sys_UserAccount().GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();
        //        if (ua != null)
        //        {
        //            Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
        //            if (model != null)
        //            {
        //                Model.T_Wo_WorkOrderItem item = new BLL.T_Wo_WorkOrderItem().GetModelList(" WorkOrderID='" + orderid + "' and isdel=0 and Type=1 ").OrderByDescending(p => p.CreateTime).FirstOrDefault();
        //                if (item != null && item.State == 0 && ("," + item.ToUser + ",").Contains("," + ua.F_UserCode + ","))
        //                {
        //                    item.SureUser = ua.F_UserCode;
        //                    item.State = 1;
        //                    item.SureTime = DateTime.Now;
        //                    if (new BLL.T_Wo_WorkOrderItem().Update(item))
        //                    {
        //                        return Success("接单成功！");
        //                    }
        //                }
        //                return Error("操作失败，工单还没有派单！");
        //            }
        //        }
        //        return Error("操作失败");
        //    }
        //    return Error("参数错误");
        //}

        ///// <summary>
        ///// 催办工单（管理员，业主）
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult RemindWorkOrder()
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        var ua = new BLL.T_Sys_UserAccount().GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();
        //        string usercode = string.Empty;
        //        string username = string.Empty;
        //        if (ua != null)
        //        {
        //            usercode = ua.F_UserCode;
        //            username = ua.F_UserName;
        //        }
        //        else
        //        {
        //            //获取客户档案（业主）表信息
        //            var modelCustomer = customerBaseBLL.GetModelList(" F_WxOpenId='" + stropenid.Trim() + "'").FirstOrDefault();
        //            if (modelCustomer != null)
        //            {
        //                usercode = modelCustomer.F_CustomerCode;
        //                username = modelCustomer.F_CompanyName;
        //            }
        //        }
        //        if (string.IsNullOrEmpty(usercode))
        //            return Error("参数错误!");

        //        string orderid = RequestString.GetFormString("orderid");
        //        string cont = RequestString.GetFormString("cont");
        //        string callid = RequestString.GetFormString("callid");
        //        Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
        //        if (model != null)
        //        {
        //            Model.T_Wo_WorkOrderItem itemlast = new BLL.T_Wo_WorkOrderItem().GetModelList(" WorkOrderID='" + orderid + "' and IsDel=0 and Type=1 and (State=0 or State=1) ").FirstOrDefault();

        //            Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();

        //            if (itemlast != null)
        //            {
        //                item.ToDept = itemlast.ToDept;
        //                item.ToUser = itemlast.ToUser;
        //            }
        //            else
        //            {
        //                var cu = new BLL.T_Sys_UserAccount().GetModel(model.CreateUser);
        //                if (cu != null)
        //                {
        //                    item.ToDept = cu.F_DeptId;
        //                    item.ToUser = cu.F_UserCode;
        //                }
        //                else {
        //                    var modelCus = customerBaseBLL.GetModelList(" F_CustomerCode='" + model.CreateUser + "'").FirstOrDefault(); //customerBaseBLL.GetModel(model.CreateUser);
        //                    if (modelCus != null)
        //                    {
        //                        item.ToDept = 0;
        //                        item.ToUser = modelCus.F_LegalTel;
        //                    }
        //                }
        //            }

        //            item.WorkOrderID = orderid;
        //            item.Type = 2;
        //            item.Detail = cont;
        //            item.CallID = callid;

        //            item.State = 0;
        //            item.IsDel = 0;
        //            item.IsLast = 0;
        //            item.IsStart = 0;
        //            item.IsTimeOut = 0;
        //            item.CreateUser = usercode; // ua.F_UserCode;
        //            item.CreateTime = DateTime.Now;

        //            long itemid = new BLL.T_Wo_WorkOrderItem().Add(item);
        //            if (itemid > 0 && !string.IsNullOrEmpty(item.ToUser))
        //            {
        //                foreach (string ur in item.ToUser.Split(','))
        //                {
        //                    Model.T_Msg_List msg = new Model.T_Msg_List();
        //                    msg.Type = 1;
        //                    msg.ToUser = ur;
        //                    msg.ToID = Int32.Parse(itemid.ToString());
        //                    msg.Detail = username + "向你催办了工单，单号：" + model.WorkOrderID;
        //                    msg.State = 0;
        //                    msg.IsDel = 0;
        //                    msg.CreateUser = usercode;
        //                    msg.CreateDate = DateTime.Now;

        //                    new BLL.T_Msg_List().Add(msg);
        //                }
        //                return Success("催办成功！");
        //            }
        //        }
        //    }
        //    return Error("参数错误");
        //}

        ///// <summary>
        ///// 退回工单
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult BackWorkOrder()
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        var ua = new BLL.T_Sys_UserAccount().GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();
        //        if (ua != null)
        //        {
        //            string orderid = RequestString.GetFormString("orderid");
        //            var model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
        //            //验证信息
        //            if (model == null)
        //            {
        //                return Error("工单不存在");
        //            }

        //            model.State = 0;
        //            if (new BLL.T_Wo_WorkOrder().Update(model))
        //            {
        //                var modelItem = new BLL.T_Wo_WorkOrderItem().GetModelList(" IsDel=0 and Type=1 and (state='0' and ','+ToUser+',' like '%," + ua.F_UserCode + ",%') and WorkOrderID = '" + orderid + "' ").FirstOrDefault();
        //                if (modelItem != null)
        //                {
        //                    modelItem.State = 6;
        //                    new BLL.T_Wo_WorkOrderItem().Update(modelItem);
        //                }
        //                return Success("操作成功");
        //            }
        //            return Error("操作失败");
        //        }
        //    }
        //    return Error("操作失败");
        //}

        ///// <summary>
        ///// 评论工单(管理人员，业主)
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult CommentWorkOrder()
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        var ua = new BLL.T_Sys_UserAccount().GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();
        //        string usercode = string.Empty;
        //        string username = string.Empty;
        //        if (ua != null)
        //        {
        //            usercode = ua.F_UserCode;
        //            username = ua.F_UserName;
        //        }
        //        else
        //        {
        //            //获取客户档案（业主）表信息
        //            var modelCustomer = customerBaseBLL.GetModelList(" F_WxOpenId='" + stropenid.Trim() + "'").FirstOrDefault();
        //            if (modelCustomer != null)
        //            {
        //                usercode = modelCustomer.F_CustomerCode;
        //                username = modelCustomer.F_CompanyName;
        //            }
        //        }
        //        if (string.IsNullOrEmpty(usercode))
        //            return Error("参数错误!");

        //        string orderid = RequestString.GetFormString("orderid");
        //        string cont = RequestString.GetFormString("cont");
        //        string file = RequestString.GetFormString("file");

        //        Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
        //        if (model != null)
        //        {
        //            Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
        //            item.WorkOrderID = orderid;
        //            item.Type = 3;  //评论
        //            item.Detail = cont;
        //            item.Files = file;
        //            item.State = 0;
        //            item.IsDel = 0;
        //            item.IsStart = 0;
        //            item.IsTimeOut = 0;
        //            item.IsLast = 0;
        //            item.CreateUser = usercode;
        //            item.CreateTime = DateTime.Now;

        //            if (new BLL.T_Wo_WorkOrderItem().Add(item) > 0)
        //            {
        //                return Success("评论成功！");
        //            }
        //        }
        //    }
        //    return Error("操作失败");
        //}

        ///// <summary>
        ///// 刪除工单
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult DelWorkOrder(string[] ids)
        //{
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
        //    if (!string.IsNullOrEmpty(stropenid))
        //    {
        //        var ua = new BLL.T_Sys_UserAccount().GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();
        //        if (ua != null)
        //        {
        //            if (ids != null && ids.Length > 0)
        //            {
        //                string idd = " ";
        //                foreach (string str in ids)
        //                {
        //                    idd += str + ",";
        //                }
        //                string sql = "update T_Wo_WorkOrder set IsDel=1,DelUser='" + ua.F_UserCode + "',DelTime=getdate() where ID in (" + idd.TrimEnd(',') + ")";
        //                if (!string.IsNullOrEmpty(idd.Trim()))
        //                {
        //                    if (DbHelperSQL.ExecuteSql(sql) > 0)
        //                    {
        //                        return Success("删除成功");
        //                    }
        //                }
        //                else
        //                {
        //                    return Error("请选择记录");
        //                }
        //            }
        //            else
        //            {
        //                return Error("获取参数失败");
        //            }
        //        }
        //    }
        //    return Error("操作失败");
        //}

        ///// <summary>
        /////  获取工单详情
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult GetWorkOrder()
        //{
        //    string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
        //    if (string.IsNullOrEmpty(strworkorderid))
        //        return Error("参数错误");
        //    if (string.IsNullOrEmpty(stropenid))
        //        return Error("参数错误!");
        //    #region pc端工单也可以查看，所以注释（注释功能只能查看自己创建的工单）
        //    //var wxuser = new BLL.T_Sys_Users().GetModelList(" F_OpenId='" + stropenid.Trim() + "' and F_Type=1 ").FirstOrDefault();
        //    //if (wxuser != null)
        //    //{
        //    //    var tbu = new BLL.T_WO_UserWorkOrder().GetList(" F_UserId='" + wxuser.F_Id + "' and F_WorkOrderId=" + strworkorderid + " ").Tables[0];

        //    //    if (tbu.Rows.Count > 0)
        //    //    {

        //    //    }
        //    //}
        //    #endregion

        //    string sql = "select *,dbo.GetDictionaryName(Type) as GDLXName,dbo.GetDictionaryName(TypeClass) as YWLXName,dbo.GetDictionaryName(Source) as GDLYName,dbo.GetUserName(CreateUser) as CreateUserName,dbo.GetUserName(LastDealUser) as LastDealUserNameRel,dbo.GetUserName(AuditUser) as AuditUserNameRel,dbo.GetUserName(ResponUser) as ResponUserName,dbo.GetDeptName(ResponDept) AS ComplaintDepartment "
        //                + " from T_Wo_WorkOrder where WorkOrderID ='" + strworkorderid + "' ";
        //    var dt = DbHelperSQL.Query(sql).Tables[0];
        //    if (dt.Rows.Count > 0)
        //    {
        //        var config = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
        //        var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

        //        if (configfj != null)
        //        {
        //            dt = BindFileData(dt, configfj.F_ParamValue);
        //        }

        //        string gcsql = "select *,dbo.GetUserName(CreateUser) as UserName "
        //                            + "from T_Wo_WorkOrderItem where IsDel=0 and WorkOrderID ='" + dt.Rows[0]["WorkOrderId"] + "'";
        //        var gcdt = DbHelperSQL.Query(gcsql).Tables[0];

        //        dt.Columns.Add("FilePath", typeof(string));
        //        if (configfj != null || config != null)
        //        {
        //            foreach (DataRow bldr in dt.Rows)
        //            {
        //                if (bldr["CallID"] != null && config != null)
        //                {
        //                    bldr["FilePath"] = GetCallPath(bldr["CallID"].ToString(), config.F_ParamValue);
        //                }
        //            }
        //        }
        //        var obj = new
        //        {
        //            data = dt,
        //            item = gcdt
        //        };
        //        return Success("查询成功", obj);
        //    }
        //    return Error("查询失败");
        //}

        ///// <summary>
        /////  获取工单明细列表
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult GetItemList()
        //{
        //    string sql = " and IsDel=0 ";
        //    DataTable dt = new DataTable();

        //    string strid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
        //    string strtype = HttpUtility.UrlDecode(RequestString.GetQueryString("type"));
        //    string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
        //    string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

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

        //    if (strid.Trim() != "" && strid != "undefined")
        //    {
        //        sql += " and WorkOrderID = '" + strid.Trim() + "' ";
        //    }
        //    if (strtype.Trim() != "" && strtype != "undefined")
        //    {
        //        sql += " and Type = '" + strtype.Trim() + "' ";
        //    }
        //    if (strstarttime.Trim() != "" && strstarttime != "undefined")
        //    {
        //        sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
        //    }
        //    if (strendtime.Trim() != "" && strendtime != "undefined")
        //    {
        //        sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
        //    }

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

        //    if (strpagesize.Trim() != "")
        //    {
        //        pagesize = Convert.ToInt32(strpagesize);
        //    }
        //    int recordCount = 0;
        //    dt = BLL.PagerBLL.GetListPager(
        //        "T_Wo_WorkOrderItem",
        //        "T_Wo_WorkOrderItem.ID",
        //        "*,dbo.GetUserName(ToUser) as ToUserName, dbo.GetDeptName(ToDept) as ToDeptName,dbo.GetUserName(SureUser) as SureUserName,dbo.GetUserName(DealUser) as DealUserName,dbo.GetUserName(CreateUser) as CreateUserName,case Type when 1 then convert(decimal(18,2),DATEDIFF(minute, CreateTime, ISNULL(DealTime, GETDATE()))/60.00) else 0 end as totalhour",
        //        sql,
        //        "ORDER BY T_Wo_WorkOrderItem.ID desc",
        //        pagesize,
        //        pageindex,
        //        true,
        //        out recordCount);

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

        ///// <summary>
        /////  获取工作动态列表 - 工单明细动态列表 - 管理员功能
        ///// </summary>
        ///// <returns></returns>
        //[WechatActionFilter]
        //public ActionResult GetWorkOrderItemList()
        //{
        //    DataTable dt = new DataTable();
        //    string stropenid = HttpUtility.UrlDecode(RequestString.GetQueryString("openid"));
        //    //string stropenid = "oXF5e1mWpX5DajW5_yjNLPKb8ThE";
        //    //获取客户档案（业主）表信息
        //    var model = userAccountBLL.GetModelList(" F_WxOpenId='" + stropenid + "'").FirstOrDefault();
        //    string sql = " and IsDel=0 ";

        //    string daytype = HttpUtility.UrlDecode(RequestString.GetQueryString("daytype"));
        //    string strpageindex = RequestString.GetQueryString("page");
        //    int pageindex = 1;
        //    string strpagesize = RequestString.GetQueryString("pagesize");
        //    int pagesize = 10;
        //    #region 权限限制
        //    //if (model != null) {
        //    //    var sqlUser = "";

        //    //    //部门信息
        //    //    var modelDep = new BLL.T_Sys_Department().GetModel(model.F_DeptId);
        //    //    int depType = 0, depRegion = 0;
        //    //    if (modelDep != null)
        //    //    {
        //    //        depType = modelDep.F_Type ?? 0;  //部门操作权限：1接待部，2办理人员，3区域客服，4监管
        //    //        depRegion = modelDep.F_Header ?? 0; //部门权限范围：9全部，1区域，2项目，3期
        //    //    }
        //    //    //根据部门查询工单（可查看当前部门工单）
        //    //    string deptCode = model.F_DeptCode;  //部门code
        //    //    int userRegionId = model.RegionId;  //项目id

        //    //    ////接待部（坐席）可以看到所有的工单                
        //    //    //if (model.F_RoleId != 17 && depType != 1)
        //    //    //{
        //    //    //    //if (depType == 2 || depType == 3)
        //    //    //    //{
        //    //    //    //    // ============== 项目权限 - 项目 ============== 
        //    //    //    //    sqlUser += $" and IsAdminSend = {userRegionId} ";
        //    //    //    //}
        //    //    //    //else if (depType == 4)
        //    //    //    //{
        //    //    //    //    // 查看该部门工单（包括一级，二级）
        //    //    //    //    string deptCodeNew = String.Empty;
        //    //    //    //    int deptCodeIndex = 0;                                  //变量声明
        //    //    //    //    string deptCodeN = deptCode.TrimEnd('|');      //去掉最后一个|
        //    //    //    //    deptCodeIndex = deptCodeN.LastIndexOf("|");             //获得|的索引
        //    //    //    //    deptCodeNew = deptCodeN.Substring(0, deptCodeIndex + 1);    //获得目标字符串（//去掉最后一个|后面的字符串）
        //    //    //    //    // ============== 部门权限条件 - 部门 ================
        //    //    //    //    string arrUser = " select F_UserCode from T_Sys_UserAccount where F_DeptCode LIKE '" + deptCodeNew + "%' ";
        //    //    //    //    sql += $" and ToUser IN ({arrUser}) and WorkOrderID IN (SELECT WorkOrderID FROM dbo.T_Wo_WorkOrder WHERE 1=1 {sqlUser} ) ";
        //    //    //    //}
        //    //    //}
        //    //}
        //    #endregion
        //    switch (daytype)
        //    {
        //        case "today":
        //            sql += " and DateDiff(dd,CreateTime,getdate())=0 ";
        //            break;
        //        case "yesterday":
        //            sql += " and DateDiff(dd,CreateTime,getdate())=1 ";
        //            break;
        //        case "month":
        //            sql += " and DateDiff(mm,CreateTime,getdate())=0 ";
        //            break;
        //        default:
        //            break;
        //    }
        //    if (strpageindex.Trim() != "")
        //    {
        //        pageindex = Convert.ToInt32(strpageindex);
        //    }
        //    if (strpagesize.Trim() != "")
        //    {
        //        pagesize = Convert.ToInt32(strpagesize);
        //    }
        //    int recordCount = 0;
        //    dt = BLL.PagerBLL.GetListPager(
        //        "T_Wo_WorkOrderItem",
        //        "T_Wo_WorkOrderItem.ID",
        //        "*,dbo.GetUserName(ToUser) as ToUserName, dbo.GetDeptName(ToDept) as ToDeptName,dbo.GetUserName(SureUser) as SureUserName,dbo.GetUserName(DealUser) as DealUserName,dbo.GetUserName(CreateUser) as CreateUserName,case Type when 1 then convert(decimal(18,2),DATEDIFF(minute, CreateTime, ISNULL(DealTime, GETDATE()))/60.00) else 0 end as totalhour",
        //        sql,
        //        "ORDER BY T_Wo_WorkOrderItem.ID desc",
        //        pagesize,
        //        pageindex,
        //        true,
        //        out recordCount);

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

        #region 附件和语音文件
        /// <summary>
        /// 获取留言路径
        /// </summary>
        /// <param name="lid">留言id</param>
        /// <param name="prefix">前缀</param>
        /// <returns></returns>
        public string GetLeavePath(string lid, string prefix)
        {
            string path = string.Empty;
            var liuyan = new BLL.T_Call_LeaveRecord().GetModelList(" F_Id='" + lid + "' ").FirstOrDefault();
            if (liuyan != null)
            {
                if (!string.IsNullOrEmpty(liuyan.F_RecFileUrl))
                {
                    path = prefix + liuyan.F_RecFileUrl;
                }
            }
            return path;
        }

        /// <summary>
        /// 获取通话录音路径
        /// </summary>
        /// <param name="cid">通话id</param>
        /// <param name="prefix">前缀</param>
        /// <returns></returns>
        public string GetCallPath(string cid, string prefix)
        {
            string path = string.Empty;
            var luyin = new BLL.T_Call_CallRecords().GetModelList(" callid='" + cid + "'  ").FirstOrDefault();
            if (luyin != null)
            {
                if (!string.IsNullOrEmpty(luyin.FilePath))
                {
                    var ym = prefix;
                    ym = ym.Substring(0, ym.Length - 1);
                    path = ym + luyin.FilePath.Substring(luyin.FilePath.IndexOf(':') + 1).Replace('\\', '/');
                }
            }
            return path;
        }

        /// <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["Files"] != null && dr["Files"].ToString() != "")
                {
                    dr["File"] = GetFileData(dr["Files"].ToString(), prefix);
                }
            }
            return dt;
        }
        #endregion

        #region 上传附件
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            try
            {
                string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
                string filePathName = string.Empty;
                string path = "/Upload/Files/" + DateTime.Now.ToString("yyyy/MM/dd") + "/";
                string localPath = Server.MapPath(Path.Combine(HttpRuntime.AppDomainAppPath, path));
                if (Request.Files.Count == 0)
                {
                    return Error("保存失败");
                }
                string ex = Path.GetExtension(file.FileName);
                filePathName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString("N") + ex;
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                file.SaveAs(Path.Combine(localPath, filePathName));
                #region 添加日志
                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 = filePathName;//附件名称
                model_T_Sys_Accessories.F_FileType = type;//附件类型
                model_T_Sys_Accessories.F_FileUrl = path + filePathName;//附件地址
                model_T_Sys_Accessories.F_Size = size;
                model_T_Sys_Accessories.F_UserCode = stropenid;//上传人  
                int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);

                #endregion
                if (fid > 0)
                {//返回附件的ID
                    model_T_Sys_Accessories.F_FileId = fid;//修改为返回对象以便查看图片
                    return Success("文件日志都成功", model_T_Sys_Accessories);
                }
                else
                    return Success("文件成功");

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


    }
    #endregion
}
