using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Common;
using CallCenterApi.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.workorder
{

    public class WorkOrderController : BaseController
    {
        // GET: WorkOrder

        //工单状态：0新工单 1待交办 2待查收 3退回审核中 4办理中 5延时审核中 6已办理 7已回访 8重办中 9已结案
        //操作按钮：1查询 2编辑 3删除 4提交 5交办 6领导批示 7市长指示 8督办 9监察 10收回 11查收 12退回申请 
        //          13办理 14延时申请 15退回审核 16回访 17延时审核 18重办 19结案 20导出 21回退 22强制结案

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

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

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

        public ActionResult test()
        {
            return Success("", workorderBLL.GetNewWorkOrderID("8000"));
        }
        #region 获取工单

        public ActionResult GetAnnexList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            int deptid = RequestString.GetInt("deptid", 0);//承办单位
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string keys = HttpUtility.UrlDecode(RequestString.GetQueryString("keys"));//内容简介
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("strstarttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("strendtime"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            if (deptid != 0)
            {
                sql += " and isnull(F_MainDeptId,null)='" + deptid + "'";
            }

            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (!string.IsNullOrEmpty(keys))
            {
                sql += " and  F_ComContent like '%" + keys + "%'  ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            string sort = "ORDER BY F_CreateTime DESC";
            int recordCount = 0;
            if (isdc==0)
            {
                dt = BLL.PagerBLL.GetListPager(
                                "T_Bus_WorkOrder WITH(NOLOCK)",
                                "F_WorkOrderId",
                                //"案件编号", "题目", "创建日期", "交办单位", "是否超期","是否回复" };
                                " F_WorkOrderId,F_ComTitle,F_CreateTime, F_MainDeptId,  F_DealTime, F_IsResult,F_WorkState,  (case  when F_DealTime is null then '未回复' else '已回复' end) isreply,F_LimitTime",
                                sql,
                               sort,
                                pagesize,
                                pageindex,
                                true,
                                out recordCount);
            }
            else
            {
                dt = DbHelperSQL.Query("select F_WorkOrderId,F_ComTitle,F_CreateTime, F_MainDeptId,   F_IsResult,F_WorkState, F_DealTime, (case  when F_DealTime is null then '未回复' else '已回复' end) isreply,F_LimitTime from T_Bus_WorkOrder WITH(NOLOCK) where 1=1" + sql).Tables[0];
            }
            
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            if (isdc==0)
            {
                dt.Columns.Add("bldata", typeof(object));

            }
            dt.Columns.Add("OverState", typeof(string));//超时状态
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            foreach (DataRow dr in dt.Rows)
            {
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    //获取最新交办信息
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {


                        dr["DeptName"] = DbHelperSQL.GetSingle("  select (case when F_IsResult =1 then dbo.[GetDeptNameByUserCode](F_CreateUser) else (select  dbo.GetDeptNames('" + dr["F_MainDeptId"].ToString() + "'))   end)  from t_bus_workorder where F_workorderid='" + dr["F_WorkOrderId"].ToString() + "'");

                        #region 超时时限
                        var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                       // dr["LimitTime"] = lt;

                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {

                                    dr["OverState"] = "否";


                                }
                                else
                                {

                                    dr["OverState"] = "超时" + gshsj;
                                }
                            }

                        }

                        if (state == (int)EnumWorkState.finish || state == (int)EnumWorkState.closed)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            if (!string.IsNullOrEmpty(closetime))
                            {
                                var dttime = DateTime.Parse(closetime);

                                if (!string.IsNullOrEmpty(lt))
                                {
                                    var ltime = DateTime.Parse(lt);
                                    TimeSpan ts = ltime.Subtract(dttime);
                                    int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                    if (tss < 0) { tss = -tss; }
                                    string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                    if (ltime < dttime)
                                    {

                                        dr["OverState"] = "超时" + gshsj;
                                    }
                                    else
                                    {
                                        dr["OverState"] = "否";
                                    }
                                }

                            }

                        }
                        #endregion
                    }

                    else
                    {
                        if (dr["F_IsResult"].ToString() == "1")
                        {
                            dr["DeptName"] = DbHelperSQL.GetSingle("  select   dbo.[GetDeptNameByUserCode](F_CreateUser)   from t_bus_workorder where F_workorderid='" + dr["F_WorkOrderId"].ToString() + "'");
                        }
                    }

                 
                }



                if (isdc == 0)
                { 

                var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                string blsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_CreateDeptId) as DeptName " + "from T_Bus_Feedback WITH(NOLOCK) where  F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId ='" + dr["F_WorkOrderId"].ToString() + "' order by F_CreateTime";
                var bldt = DbHelperSQL.Query(blsql).Tables[0];
                if (configfj != null)
                {
                    bldt = BindFileData(bldt, configfj.F_ParamValue);
                }
                dr["blData"] = bldt;
            }
            }

            if (isdc==1)
            {
                //删除一些列      
               
                      dt.Columns.Remove("F_DealTime");
                dt.Columns.Remove("F_MainDeptId");
                dt.Columns.Remove("F_IsResult");
                dt.Columns.Remove("F_WorkState");
                dt.Columns.Remove("F_LimitTime");
                
                dt.Columns["isreply"].SetOrdinal(5);
                var cols = new string[] { "案件编号", "题目", "创建日期", "交办单位", "是否超期","是否回复" };
                var msg = new NPOIHelper().ExportToExcel("附件管理", dt,cols);
                if (msg == "")
                {
                   
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }


        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns></returns>
      //  [Authority]
        #region MyRegion
        public ActionResult GetList(int isdc = 0)
        {

            int userId =   Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string keys = HttpUtility.UrlDecode(RequestString.GetQueryString("keys"));//内容简介
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("strstarttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("strendtime"));

            int sourcearea = RequestString.GetInt("sourcearea", 0);//精准地域
            int type = RequestString.GetInt("type", 0);//舆情类型 
            string source = HttpUtility.UrlDecode(RequestString.GetQueryString("source"));//舆情来源
            //RequestString.GetInt("source", 0);
            int deptid = RequestString.GetInt("deptid", 0);//承办单位
            int infoproperty = RequestString.GetInt("infoproperty", 0);//信息属性
            int level = RequestString.GetInt("level", 0);//舆情等级
            int isresult = RequestString.GetInt("isresult", -1);//处理类型
            string strtab = HttpUtility.UrlDecode(RequestString.GetQueryString("tab"));
            string strisaudit = HttpUtility.UrlDecode(RequestString.GetQueryString("isaudit")); //"0" 是待审核退回  1：同意  2：拒绝
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            int timesort = RequestString.GetInt("timesort", -1);//0 是limittime排序； 默认是1 是createtime

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

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

            #region 暂时不用的筛选项
            //
            //string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            //string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            //string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));

            //string wjstrstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("wjstarttime"));
            //string wjstrendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("wjendtime"));

            //string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            //string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            ////回传时间筛选
            //string hcstrstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("hcstrstarttime"));
            //string hcstrendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("hcstrendtime"));


            //int keyid = RequestString.GetInt("keyid", 0);


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

            //int files = RequestString.GetInt("files", 0);

            //int dealtype = RequestString.GetInt("dealtype", -1);
            //int issend = RequestString.GetInt("issend", -1);
            //int deptlevel = RequestString.GetInt("deptlevel", 0);
            //int satisfaction = RequestString.GetInt("satisfaction", -1);
            //
            //int BigType = RequestString.GetInt("BigType", -1);
            #endregion


            #region sql 语句相关处理

            if (!string.IsNullOrEmpty( keys))
            {
                sql += " and ( F_ComContent like '%" + keys + "%' or  F_ComTitle   like '%" + keys + "%' ) ";
            }

            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }

            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }
            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (mode != -1)
            {
                sql += " and F_Mode = '" + mode + "' ";
            }
            if (workordertype != -1)
            {
                sql += " and F_WorkOrderType = '" + workordertype + "' ";
            }
            if ( !string.IsNullOrEmpty(source))
            {
              //  sql += " and F_Event = '" + source + "' ";
                sql += " and  F_Event like '%" + source + "%'  ";
            }
            if (deptid != 0  )
            {               
                 sql += " and isnull(F_MainDeptId,null)='"+ deptid + "'";
            }
            if (infoproperty > 0)
            {
                sql += " and F_InfoConBigType = '" + infoproperty + "' ";
            }          
            if (level > 0)
            {
                sql += " and F_Level = '" + level + "' ";
            }
            if (isresult > -1)
            {
                sql += " and F_IsResult = '" + isresult + "' ";
            }
            
           
        

        
            if (strstate.Trim() != "" && strstate != "undefined" && strstate != "3")
            {
                if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString())
                    sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
               else if (strstate.Trim() == ((int)EnumWorkState.finish).ToString())
                    sql += " and F_WorkState in (" + (int)EnumWorkState.finish + "," + (int)EnumWorkState.closed + ") ";
                else
                    sql += " and F_WorkState  in( " + strstate.Trim() + ") ";

            }
            if (strtab == "2")
            {
                sql += "  and F_WorkOrderID in (select F_WorkOrderID from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";// and F_IsAudit>0
                if (!string.IsNullOrEmpty(strisaudit))
                {
                    if (strisaudit == "0")
                    {
                        sql += " and F_WorkState =3 ";

                    }
                    sql += " and F_IsAudit='" + strisaudit + "'";
                }
                if (deptid > 0)
                {
                    sql += " and F_CreateDeptId='"+ deptid + "'";

                }

                if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                {
                    sql += " and F_AuditUser='" + userModel.F_UserCode + "')";
                }
                else
                {
                    sql += ")";
                }
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            #endregion
         
            #region 暂时不用的sql筛选的拼接
            //if (files > 1)
            //{
            //    sql += " and F_Files  is not null and F_Files!='' ";
            //}


            //if (strname.Trim() != "" && strname != "undefined")
            //{
            //    sql += " and F_CusName like '%" + strname + "%' ";
            //}
            //if (strtel.Trim() != "" && strtel != "undefined")
            //{
            //    sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            //}
            //if (strkey.Trim() != "" && strkey != "undefined")
            //{
            //    sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";

            //}


            //if (strusercode.Trim() != "" && strusercode != "undefined")
            //{//坐席
            //    var usercode = strusercode.Trim().Split(',');
            //    var newusercode = "";
            //    foreach (var item in usercode)
            //    {
            //        if (!string.IsNullOrWhiteSpace(item.Trim()))
            //            newusercode += "'" + item + "',";
            //    }
            //    newusercode = newusercode.Trim(',');
            //    if (newusercode.Trim() != "" && newusercode != "undefined")
            //    {
            //        sql += " and F_CreateUser in (" + newusercode + ") ";
            //        //sql += " and F_CreateUser ='" + strusercode + "' ";
            //    }
            //}
            //if (strddusercode.Trim() != "" && strddusercode != "undefined")
            //{//调度员
            //    var ddusercode = strddusercode.Trim().Split(',');
            //    var newusercode = "";
            //    foreach (var item in ddusercode)
            //    {
            //        if (!string.IsNullOrWhiteSpace(item.Trim()))
            //            newusercode += "'" + item + "',";
            //    }
            //    newusercode = newusercode.Trim(',');
            //    if (newusercode.Trim() != "" && newusercode != "undefined")
            //    {
            //        sql += " and F_AssignUser in(" + newusercode + ") ";
            //        //sql += " and F_AssignUser = '" + strddusercode + "' ";
            //    }
            //}

            //if (satisfaction > -1)
            //{
            //    sql += " and F_Satisfaction = '" + satisfaction + "' ";
            //}
            //if (keyid != 0)
            //{
            //    sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            //}
            //else if (userModel.F_RoleCode == "DFZF")
            //{
            //    sql += " and F_CreateUser ='" + userModel.F_UserCode + "' ";
            //}

            ////if (bigtype != 0)
            ////{
            ////    sql += " and F_InfoConBigType = '" + bigtype + "' ";
            ////}
            //if (smalltype != 0)
            //{
            //    sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            //}



            ////if (deptid != 0 && string.IsNullOrEmpty(strisaudit))
            ////{
            ////    //sql += " and ',' + F_MainDeptID + ',' like '%," + deptid.ToString() + ",%'";
            ////    //sql += " and isnull(F_MainDeptId,null)='"+ deptid + "'";
            ////    sql += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
            ////    #region 20190924 zhengbingbing 主办单位查询以最后办理单位为准
            ////    //if (deptlevel == 0)
            ////    //{
            ////    //    string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
            ////    //    sql += " and F_WorkOrderID in(" + sqlwhere + ")";
            ////    //}
            ////    //else
            ////    //{
            ////    //    string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo_Next where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
            ////    //    sql += " and F_WorkOrderID in(" + sqlwhere + ")";
            ////    //}
            ////    #endregion
            ////}
            //if (dealtype != -1)
            //{
            //    sql += " and isnull(F_IsResult,0) = '" + dealtype + "' ";
            //}
            //if (issend != -1)
            //{
            //    sql += " and isnull(F_IsRelease,0) = '" + issend + "' ";
            //}


            //#region 结案时间
            //if (wjstrstarttime.Trim() != "" && wjstrstarttime != "undefined")
            //{
            //    sql += " and datediff(day,F_CloseTime,'" + wjstrstarttime + "')<=0 ";
            //}
            //if (wjstrendtime.Trim() != "" && wjstrendtime != "undefined")
            //{
            //    sql += " and datediff(day,F_CloseTime,'" + wjstrendtime + "')>=0   ";
            //}

            //#endregion
            ////根据回传时间判断
            //if (hcstrstarttime.Trim() != "" && hcstrstarttime != "undefined")
            //{
            //    sql += " and F_Hcdatetime >= '"+ hcstrstarttime + "  00:00:00'";
            //    //sql += " and datediff(day,F_Hcdatetime,'" + hcstrstarttime + "')<=0 ";
            //}
            //if (hcstrendtime.Trim() != "" && hcstrendtime != "undefined")
            //{
            //     sql += "  and F_Hcdatetime<='"+ hcstrendtime + " 23:59:59'   ";
            //    //sql += " and datediff(day,F_Hcdatetime,'" + hcstrendtime + "')>=0   ";
            //}
            #endregion


            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetOverState(F_WorkOrderId) as OverState,"
            //    + "dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetWorkOrderAssign(F_WorkOrderId) as DeptName ,dbo.GetLimitTime(F_WorkOrderId) as LimitTime";
            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";
            string sort = "ORDER BY F_CreateTime DESC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string cols = "F_OldWorkOrderId,F_Level,F_WorkOrderType,F_CusName,F_CusAddress,F_ComTitle,F_SourceAddress,F_Result,F_Key,F_Hcdatetime,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as InfoSourceName,dbo.GetDictionaryName(F_InfoConBigType) as InfoConBigTypeName,dbo.GetAreaName(F_SourceArea) as SourceAreaName,F_Scanning , F_WorkOrderId,  F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,  IsExport,F_Files,F_WorkRemarks,requirementFinishDay,F_Event,F_LimitTime,(case F_WorkOrderType when 0 then '舆情工单' when 1 then '频发工单' else '' end) F_WorkOrderTypeName,F_MainWorkOrderId";
            #region 导出
            if (isdc > 0)
            {
                var top = " "; var orderby = " order by F_CreateTime";
                if (sql == " and F_IsDelete=0 ")
                {
                    top = " top 1000 "; orderby += " desc ";
                }


                //20190715调整导出字段 zhengbingbing
                //日期，工单号，诉求标题，诉求内容，承办单位，办理结果，是否满意，备注
                //var dtdc = DbHelperSQL.Query(" select " + top + " F_CreateTime 日期, F_OldWorkOrderId 工单号,F_ComTitle 诉求标题,F_CusName 反映人,F_CusPhone 电话号码,F_ComContent 诉求内容,dbo.GetDictionaryName(F_Key) 主题词, "
                //   + " dbo.GetDeptNames(F_MainDeptId) 承办单位, "
                //   + " (select top 1 F_Situation from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId =wo.F_WorkOrderId order by F_CreateTime) 办理结果,"
                //   + " (select top 1 (case F_IsSatisfie when 1 then'满意' when 0 then '不满意'when 2 then '基本满意' else '未评价' end) F_Satisfie from T_Bus_VisitResult WITH(NOLOCK) where F_State = 1 and F_IsDelete = 0 and F_WorkOrderId = wo.F_WorkOrderId order by F_Id desc) 承办单位回访结果" +
                //          " from T_Bus_WorkOrder wo WITH(NOLOCK) where 1=1 " + sql + sort).Tables[0];
                var dtdc = DbHelperSQL.Query("select F_workorderid 案件编号, (case F_IsResult when 0 then '网络转办' when 1 then '当即办理' else '' end) 处理类型,F_ComTitle 题目, F_Event 舆情来源, dbo.GetDeptNames(F_MainDeptId) 承办单位,  F_LimitTime   办理时限 from T_Bus_WorkOrder wo WITH(NOLOCK) where 1=1 " + sql + sort).Tables[0];

                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    //if ( strstate.Trim() == ((int)EnumWorkState.finish).ToString())
                    // {
                    // var dtex= DbHelperSQL.Query("update T_Bus_WorkOrder set IsExport=1 where 1=1 " + sql ).Tables[0];
                    //  }
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            #endregion
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
               sort,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件和交办超时
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("OverState", typeof(string));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("PDState", typeof(string));//派单状态
            dt.Columns.Add("FilePath", typeof(string));//语音文件路径
            dt.Columns.Add("Buttons", typeof(object));//操作按钮
            dt.Columns.Add("FilePaths", typeof(object));//操作按钮
            dt.Columns.Add("IsFiles", typeof(object));//操作按钮
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            var reminds = remindBLL.GetModelList(" F_State=0 and F_IsDelete=0 and F_Type =1").ToList();
            foreach (DataRow dr in dt.Rows)
            {
                string iszbdw = "0";
                string ispd = "";

                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    //获取最新交办信息
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        //if (dtjb.Rows[0]["F_MainDeptId"].ToString().Split(',').Contains(userModel.F_DeptId.ToString())) { iszbdw = "1"; }
                        if (dr["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle("  select (case when F_IsResult =1 then dbo.[GetDeptNameByUserCode](F_CreateUser) else (select  dbo.GetDeptNames('" + dr["F_MainDeptId"].ToString() + "'))   end)  from t_bus_workorder where F_workorderid='" + dr["F_WorkOrderId"].ToString() + "'");                             
                        if (dr["F_OtherDeptIds"] != null && dr["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dr["F_OtherDeptIds"].ToString() + "')");
                        }
                        #region 20191016
                        //if (dtjb.Rows[0]["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        //dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        //if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        //{
                        //    dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        //}
                        #endregion
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                        #region
                        //int did = Int32.Parse(dtjb.Rows[0]["F_MainDeptId"].ToString());
                        //var deptinfo = new BLL.T_Sys_Department().GetModel(did);
                        //if (deptinfo != null)
                        //{
                        //    if (did == userModel.F_DeptId) { iszbdw = "1"; }
                        //    dr["DeptName"] = deptinfo.F_DeptName;//交办单位
                        //}
                        //if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        //{
                        //    string[] strids = dtjb.Rows[0]["F_OtherDeptIds"].ToString().Split(',');
                        //    string dns = string.Empty;
                        //    foreach (string strid in strids)
                        //    {
                        //        var dinfo = new BLL.T_Sys_Department().GetModel(Int32.Parse(strid));
                        //        if (dinfo != null)
                        //        {
                        //            if (string.IsNullOrEmpty(dns))
                        //            {
                        //                dns = dinfo.F_DeptName;//交办单位
                        //            }
                        //            else
                        //            {
                        //                dns += "," + dinfo.F_DeptName;//交办单位
                        //            }
                        //        }
                        //    }
                        //    dr["OtherDeptName"] = dns;
                        //}
                        #endregion
                        var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                        dr["LimitTime"] = lt;
                        #region 超时时限
                        //if (state < 6 || state == 8)
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                            ispd = dtjb.Rows[0]["F_IsNext"] != null ? dtjb.Rows[0]["F_IsNext"].ToString() : "";
                            dr["PDState"] = ispd;
                        }

                        if (state == (int)EnumWorkState.finish || state == (int)EnumWorkState.closed)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            if (!string.IsNullOrEmpty(closetime))
                            {
                                var dttime = DateTime.Parse(closetime);

                                if (!string.IsNullOrEmpty(lt))
                                {
                                    var ltime = DateTime.Parse(lt);
                                    TimeSpan ts = ltime.Subtract(dttime);
                                    int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                    if (tss < 0) { tss = -tss; }
                                    string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                    if (ltime < dttime)
                                    {
                                        dr["OverState"] = 3;
                                        dr["GapTime"] = "超时" + gshsj;
                                    }
                                }

                            }

                        }
                        #endregion
                    }

                    else
                    {
                        if (dr["F_IsResult"].ToString() =="1")
                        {
                            dr["DeptName"] = DbHelperSQL.GetSingle("  select   dbo.[GetDeptNameByUserCode](F_CreateUser)   from t_bus_workorder where F_workorderid='" + dr["F_WorkOrderId"].ToString() + "'");
                        }
                    }
                }

                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }

                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    if (!string.IsNullOrEmpty(dr["F_Files"].ToString()))
                        dr["IsFiles"] = 1;
                    else
                        dr["IsFiles"] = 0;
                }
                else
                {
                    dr["IsFiles"] = 0;
                }
                List<ButtonGroup.button> buttons = new List<ButtonGroup.button>();
                if (strtab == "2")
                {
                    if (strisaudit=="0")//   strisaudit == "0" 是待审核退回
                    {
                        buttons = ButtonGroup.GetButtons(dr["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw, ispd, dr["IsExport"].ToString());
                    }
                }

                else
                {  
                  buttons = ButtonGroup.GetButtons(dr["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw, ispd, dr["IsExport"].ToString());
                 }
                #region 判断是否存在待督办
                var recount = reminds.Where(r => r.F_WorkOrderId.Equals(dr["F_WorkOrderId"].ToString())).Count();
                var butt = buttons.Find(c => c.key == ButtonGroup.turnsee().key);

                if (userModel.F_RoleCode.ToUpper() == "GLY" || userModel.F_RoleCode.ToUpper() == "ZXLD" )
                {
                    if(dr["F_WorkState"].ToString()=="0"|| dr["F_WorkState"].ToString()=="1")
                    buttons.Add(ButtonGroup.delete());
                }

                if (recount > 0 && butt != null)
                    buttons.Remove(butt);
                #endregion

                

                    //var workoderlists = new BLL.T_Bus_WorkOrder().GetModelList($"F_MainWorkOrderId = '{dr["F_WorkOrderId"].ToString()}' " +
                    //        $"order by F_CreateTime   desc ");
                if ( ( dr["F_MainWorkOrderId"] !=null && dr["F_MainWorkOrderId"].ToString()!="")  )
                //|| (  workoderlists != null && workoderlists.Count > 0))
                {
                    var Runsendbutt = buttons.Find(c => c.key == ButtonGroup.Runsend().key);

                    buttons.Remove(Runsendbutt);
                }



                if (strisaudit=="1" || strisaudit == "2")
                {
                    var delbutt = buttons.Find(c => c.key == ButtonGroup.delete().key);
                    buttons.Remove(delbutt);
                    buttons.Add(ButtonGroup.query());
                }
                //if (userModel.F_RoleCode!="WLDW")
                //{
                //    var delbutt = buttons.Find(c => c.key == ButtonGroup.delay().key);
                //     if (delbutt==null )
                //    buttons.Add(ButtonGroup.delay());
                //}
                if (Convert.ToInt32(dr["F_WorkState"].ToString()) == (int)EnumWorkState.visit)
                {
                    buttons.Add(ButtonGroup.Runsend());
                }
                if (Convert.ToInt32(dr["F_WorkState"].ToString()) == (int)EnumWorkState.finish)
                {
                    var delbutt = buttons.Find(c => c.key == ButtonGroup.edit().key);
                    if (delbutt != null)
                    {
                        buttons.Remove(delbutt);
                    }                  
                     
                }
                else
                {
                    var delbutt = buttons.Find(c => c.key == ButtonGroup.edit().key);
                    if (delbutt == null)
                    {
                        buttons.Add(ButtonGroup.edit());
                    }
                }



                dr["Buttons"] = buttons;
            }
            #endregion

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

        }
        #endregion

        #region MyRegion 
        public ActionResult GetListTimeOut(int isdc = 0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            var configcs1 = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            int cscount = 1;
            if (configcs1 != null)
            {
                cscount= Int32.Parse(configcs1.F_ParamValue);
            }
               
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 and  (F_LimitTime<=  DATEADD(hh, "+ cscount + ", GETDATE()))  and (F_WorkState<6 or F_WorkState=8) and F_MainDeptId >0";
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            int files = RequestString.GetInt("files", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            int dealtype = RequestString.GetInt("dealtype", -1);
            int issend = RequestString.GetInt("issend", -1);
            int deptlevel = RequestString.GetInt("deptlevel", 0);
            int satisfaction = RequestString.GetInt("satisfaction", -1);
            int timesort = RequestString.GetInt("timesort", -1);


            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            int IsExport = RequestString.GetInt("isexport", -1);
            if (IsExport > -1)
            {
                if (IsExport == 0)
                    sql += " and (IsExport != '" + 1 + "'or IsExport is null) ";
                else
                    sql += " and IsExport = '" + IsExport + "' ";
            }

            #region sql 语句相关处理
            if (strstate.Trim() != "" && strstate != "undefined")
            {
                if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString())
                    sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                else
                    sql += " and F_WorkState = '" + strstate.Trim() + "' ";

            }
            if (files > 1)
            {
                sql += " and F_Files  is not null and F_Files!='' ";
            }
            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }


            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";

            }


            if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                    //sql += " and F_CreateUser ='" + strusercode + "' ";
                }
            }
            if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                    //sql += " and F_AssignUser = '" + strddusercode + "' ";
                }
            }
            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (satisfaction > -1)
            {
                sql += " and F_Satisfaction = '" + satisfaction + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            else if (userModel.F_RoleCode == "DFZF")
            {
                sql += " and F_CreateUser ='" + userModel.F_UserCode + "' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }

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

            if (deptid != 0)
            {
                //sql += " and ',' + F_MainDeptID + ',' like '%," + deptid.ToString() + ",%'";
                //sql += " and isnull(F_MainDeptId,null)='"+ deptid + "'";
                sql += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
                #region 20190924 zhengbingbing 主办单位查询以最后办理单位为准
                //if (deptlevel == 0)
                //{
                //    string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                //    sql += " and F_WorkOrderID in(" + sqlwhere + ")";
                //}
                //else
                //{
                //    string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo_Next where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                //    sql += " and F_WorkOrderID in(" + sqlwhere + ")";
                //}
                #endregion
            }
            if (dealtype != -1)
            {
                sql += " and isnull(F_IsResult,0) = '" + dealtype + "' ";
            }
            if (issend != -1)
            {
                sql += " and isnull(F_IsRelease,0) = '" + issend + "' ";
            }

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

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetOverState(F_WorkOrderId) as OverState,"
            //    + "dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetWorkOrderAssign(F_WorkOrderId) as DeptName ,dbo.GetLimitTime(F_WorkOrderId) as LimitTime";
            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";
            string sort = "ORDER BY F_LimitTime desc,F_Id desc";
            if (timesort == 0)
                sort = "ORDER BY F_LimitTime ASC,F_Id desc";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string cols = "F_OldWorkOrderId,F_LimitTime,F_Level,F_WorkOrderId,F_Scanning,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoConBigType) as InfoConBigTypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,IsExport,F_Files,F_WorkRemarks,requirementFinishDay";
            #region 导出
            if (isdc > 0)
            {
                var top = " "; var orderby = " order by F_CreateTime";
                if (sql == " and F_IsDelete=0 ")
                {
                    top = " top 1000 "; orderby += " desc ";
                }
                sql+= " and (F_LimitTime>= DATEADD(hh,"+ cscount + ",F_LimitTime) or F_LimitTime<GETDATE())  and (F_WorkState<6 or F_WorkState=8) ";

                //20190715调整导出字段 zhengbingbing
                //日期，工单号，诉求标题，诉求内容，承办单位，办理结果，是否满意，备注
                //var dtdc = DbHelperSQL.Query(" select " + top + " F_CreateTime 日期, F_OldWorkOrderId 工单号,F_ComTitle 诉求标题,F_CusName 反映人,F_CusPhone 电话号码,F_ComContent 诉求内容,dbo.GetDictionaryName(F_Key) 主题词, "
                //   + " dbo.GetDeptNames(F_MainDeptId) 承办单位, "
                //   + " (select top 1 F_Situation from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId =wo.F_WorkOrderId order by F_CreateTime) 办理结果,"
                //   + " (select top 1 (case F_IsSatisfie when 1 then'满意' when 0 then '不满意'when 2 then '基本满意' else '未评价' end) F_Satisfie from T_Bus_VisitResult WITH(NOLOCK) where F_State = 1 and F_IsDelete = 0 and F_WorkOrderId = wo.F_WorkOrderId order by F_Id desc) 承办单位回访结果" +
                //    " from T_Bus_WorkOrder wo WITH(NOLOCK) where 1=1 " + sql + sort).Tables[0];

                var dtdc = DbHelperSQL.Query("select F_workorderid 案件编号, (case F_IsResult when 0 then '网络转办' when 1 then '当即办理' else '' end) 处理类型,F_ComTitle 题目, F_Event 舆情来源, dbo.GetDeptNames(F_MainDeptId) 承办单位,  F_LimitTime   办理时限 from T_Bus_WorkOrder wo WITH(NOLOCK) where 1=1 " + sql + sort).Tables[0];



                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    //if ( strstate.Trim() == ((int)EnumWorkState.finish).ToString())
                    // {
                    // var dtex= DbHelperSQL.Query("update T_Bus_WorkOrder set IsExport=1 where 1=1 " + sql ).Tables[0];
                    //  }
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            #endregion
            int recordCount = 0;
            

            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
               sort,
               pagesize,
                pageindex,
                true,
                out recordCount);
          //  var dtt = workorderBLL.GetList(" 1=1" +sql);
          //  dt = dtt.Tables[0];

            #region 声音文件和交办超时
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("OverState", typeof(int));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("PDState", typeof(string));//派单状态
            dt.Columns.Add("FilePath", typeof(string));//语音文件路径
            dt.Columns.Add("Buttons", typeof(object));//操作按钮
            dt.Columns.Add("FilePaths", typeof(object));//操作按钮
            dt.Columns.Add("IsFiles", typeof(object));//操作按钮
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            var reminds = remindBLL.GetModelList(" F_State=0 and F_IsDelete=0 and F_Type =1").ToList();
            foreach (DataRow dr in dt.Rows)
            {
                string iszbdw = "0";
                string ispd = "";

                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    //获取最新交办信息
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                    
                        if (dr["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dr["F_MainDeptId"].ToString() + "')");
                        if (dr["F_OtherDeptIds"] != null && dr["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dr["F_OtherDeptIds"].ToString() + "')");
                        }
                        #region 20191016
                      
                        #endregion
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                        #region
                     
                        #endregion
                        var lt = dr["F_LimitTime"].ToString();//限制时间
                        dr["LimitTime"] = lt;
                        #region 超时时限
                        //if (state < 6 || state == 8)
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                            ispd = dtjb.Rows[0]["F_IsNext"] != null ? dtjb.Rows[0]["F_IsNext"].ToString() : "";
                            dr["PDState"] = ispd;
                        }

                        if (state == (int)EnumWorkState.finish || state == (int)EnumWorkState.closed)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            if (!string.IsNullOrEmpty(closetime))
                            {
                                var dttime = DateTime.Parse(closetime);

                                if (!string.IsNullOrEmpty(lt))
                                {
                                    var ltime = DateTime.Parse(lt);
                                    TimeSpan ts = ltime.Subtract(dttime);
                                    int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                    if (tss < 0) { tss = -tss; }
                                    string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                    if (ltime < dttime)
                                    {
                                        dr["OverState"] = 3;
                                        dr["GapTime"] = "超时" + gshsj;
                                    }
                                }

                            }

                        }
                        #endregion
                    }
                }

                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }

                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    if (!string.IsNullOrEmpty(dr["F_Files"].ToString()))
                        dr["IsFiles"] = 1;
                    else
                        dr["IsFiles"] = 0;
                }
                else
                {
                    dr["IsFiles"] = 0;
                }
                var buttons = ButtonGroup.GetButtonstimeout(); 
                dr["Buttons"] = buttons;
            }
            #endregion

            //dt.DefaultView.Sort = "";
         //   dt = dt.DefaultView.ToTable();
          //  var allcount = dt.Rows.Count;
           // dt = GetPagedTable(dt,pageindex,pagesize);
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());

        }
        #endregion
        public DataTable GetPagedTable(DataTable dt, int PageIndex, int PageSize)//PageIndex表示第几页，PageSize表示每页的记录数
        {
            if (PageIndex == 0)
                return dt;//0页代表每页数据，直接返回

            DataTable newdt = dt.Copy();
            newdt.Clear();//copy dt的框架

            int rowbegin = (PageIndex - 1) * PageSize;
            int rowend = PageIndex * PageSize;

            if (rowbegin >= dt.Rows.Count)
                return newdt;//源数据记录数小于等于要显示的记录，直接返回dt

            if (rowend > dt.Rows.Count)
                rowend = dt.Rows.Count;
            for (int i = rowbegin; i <= rowend - 1; i++)
            {
                DataRow newdr = newdt.NewRow();
                DataRow dr = dt.Rows[i];
                foreach (DataColumn column in dt.Columns)
                {
                    newdr[column.ColumnName] = dr[column.ColumnName];
                }
                newdt.Rows.Add(newdr);
            }
            return newdt;
        }

        /// <summary>
        /// 获取坐席处理列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetZXDealList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            string sql = " and F_IsDelete=0";
            string strtab = HttpUtility.UrlDecode(RequestString.GetQueryString("tab"));
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
         
            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);

            int deptid = RequestString.GetInt("deptid", 0);
            int deptlevel = RequestString.GetInt("deptlevel", 0);

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            int IsExport = RequestString.GetInt("isexport",0);

            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            if (IsExport>0)
            {
                sql += " and IsExport = '" + IsExport + "' ";
            }
            switch (strtab)
            {
                case "-1"://待处理工单(其他来源)
                    sql = " and F_IsDelete=1 and F_IsEnabled=0 ";
                    break;
                case "0"://待处理工单
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        if (userModel.F_RoleCode != "ZJZY")
                            sql += " and F_CreateUser='" + userModel.F_UserCode + "'";
                    }

                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString())
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    else
                    {
                        sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + "," + (int)EnumWorkState.dealed + ") ";
                        //sql += " and F_WorkState in (0,6) ";
                    }
                    break;
                case "1"://已提交的工单
                    //sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_SubmitSuper where F_State=1 and F_IsDelete=0  ";
                    sql += " and F_WorkState >0 ";
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "'";
                    }
                    break;
                case "2"://已回访的工单
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_VisitResult WITH(NOLOCK) where F_State=1 and F_IsDelete=0  ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "3"://已回退的工单
                    //sql += "  and F_WorkState=0 and F_IsReturn=1 ";
                    sql += " and F_WorkState in (0,10) and F_IsReturn=1";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode;
                    }

                    break;
            }

            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }
            #region  坐席&调度员
            if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }
            if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                }
            }
            //if (strusercode.Trim() != "" && strusercode != "undefined")
            //{
            //    sql += " and F_CreateUser = '" + strusercode + "' ";
            //}
            #endregion
            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }
            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }
            if (deptid != 0)
            {
                //sql += " and ',' + F_MainDeptID + ',' like '%," + deptid.ToString() + ",%'";
                //sql += " and isnull(F_MainDeptId,null)='" + deptid + "'";
                sql += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
                #region 20190924 zhengbingbing 主办单位查询以最后办理单位为准
                //if (deptlevel == 0)
                //{
                //    string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                //    sql += " and F_WorkOrderID in(" + sqlwhere + ")";
                //}
                //else
                //{
                //    string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo_Next where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                //    sql += " and F_WorkOrderID in(" + sqlwhere + ")";
                //}
                #endregion
            }

            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetOverState(F_WorkOrderId) as OverState,"
            //    + "dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetWorkOrderAssign(F_WorkOrderId) as DeptName ,dbo.GetLimitTime(F_WorkOrderId) as LimitTime";
            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";
            string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoConBigType) as InfoConBigTypeName,bo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks,requirementFinishDay";
            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    //if (strstate.Trim() == ((int)EnumWorkState.finish).ToString())
                    //{
                    //    var dtex = DbHelperSQL.Query("update T_Bus_WorkOrder set IsExport=1 where 1=1 " + sql).Tables[0];
                    //}
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
               sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("OverState", typeof(string));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("FilePath", typeof(string));//语音文件路径
            dt.Columns.Add("Buttons", typeof(object));//操作按钮
            dt.Columns.Add("IsFiles", typeof(object));//操作按钮
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            var reminds = remindBLL.GetModelList("F_State=0 and F_IsDelete=0 and F_Type =1").ToList();
            foreach (DataRow dr in dt.Rows)
            {
                //获取最新交办信息
                string iszbdw = "0";
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        //if (dtjb.Rows[0]["F_MainDeptId"].ToString().Split(',').Contains(userModel.F_DeptId.ToString())) { iszbdw = "1"; }
                        if (dtjb.Rows[0]["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                        #region
                        //int did = Int32.Parse(dtjb.Rows[0]["F_MainDeptId"].ToString());
                        //var deptinfo = new BLL.T_Sys_Department().GetModel(did);
                        //if (deptinfo != null)
                        //{
                        //    if (did == userModel.F_DeptId) { iszbdw = "1"; }
                        //    dr["DeptName"] = deptinfo.F_DeptName;//交办单位
                        //}
                        //if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        //{
                        //    string[] strids = dtjb.Rows[0]["F_OtherDeptIds"].ToString().Split(',');
                        //    string dns = string.Empty;
                        //    foreach (string strid in strids)
                        //    {
                        //        var dinfo = new BLL.T_Sys_Department().GetModel(Int32.Parse(strid));
                        //        if (dinfo != null)
                        //        {
                        //            if (string.IsNullOrEmpty(dns))
                        //            {
                        //                dns = dinfo.F_DeptName;//交办单位
                        //            }
                        //            else
                        //            {
                        //                dns += "," + dinfo.F_DeptName;//交办单位
                        //            }
                        //        }
                        //    }
                        //    dr["OtherDeptName"] = dns;
                        //}
                        #endregion
                        #region
                        //if (state < 6 || state == 8)
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                            dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        if (state == (int)EnumWorkState.finish)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            var dttime = DateTime.Now;
                            if (!string.IsNullOrWhiteSpace(closetime)) { dttime = DateTime.Parse(closetime); }
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                            dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(dttime);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime < dttime)
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        #endregion
                    }
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }
                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    if (!string.IsNullOrEmpty(dr["F_Files"].ToString()))
                        dr["IsFiles"] = 1;
                    else
                        dr["IsFiles"] = 0;
                }
                else
                {
                    dr["IsFiles"] = 0;
                }
                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                if (Int32.Parse(strtab) == 0)
                {
                    btns.Clear();
                    btns = ButtonGroup.GetButtons(dr["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw);
                    #region 判断是否存在待督办
                    var recount = reminds.Where(r => r.F_WorkOrderId == dr["F_WorkOrderId"].ToString()).Count();
                    var butt = btns.Find(c => c.key == ButtonGroup.turnsee().key);
                    if (recount > 0 && butt != null)
                        btns.Remove(butt);
                    #endregion
                }
                else if (Int32.Parse(strtab) == -1)
                {
                    btns.Clear();
                    btns.Add(ButtonGroup.query());
                    btns.Add(ButtonGroup.edit());
                }
                else
                {
                    btns.Clear();
                    btns.Add(ButtonGroup.query());
                    
                }
                dr["Buttons"] = btns;
            }

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

        /// <summary>
        /// 上传阿里云
        /// </summary>
        public class uploadAddWorders
        {
            /// <summary>
            /// 案件编号
            /// </summary>
            public string cenrollid { set; get; }
            /// <summary>
            /// 来电人
            /// </summary>
            public string custname { set; get; }
            /// <summary>
            /// 登记时间
            /// </summary>
            public string tsystime { set; get; }
            /// <summary>
            /// 事件类别
            /// </summary>
            public string ismallcategory { set; get; }
            /// <summary>
            /// 转办人
            /// </summary>
            public string unit_code { set; get; }
            /// <summary>
            /// 转办时间
            /// </summary>
            public string transferTime { set; get; }
            /// <summary>
            /// 转办单位
            /// </summary>
            public string transferunit { set; get; }
            /// <summary>
            /// 详细内容
            /// </summary>
            public string content { set; get; }
            /// <summary>
            /// 拟办意见
            /// </summary>
            public string advice { set; get; }
            /// <summary>
            /// 处理结果
            /// </summary>
            public string result { set; get; }
            /// <summary>
            /// 回访情况
            /// </summary>
            public string remark { set; get; }
           public int  ideliverprogress { set; get; }
            public int type { set; get; }
            public string phone { set; get; }
            public string title { set; get; }
            public string backreason { set; get; }
            public string workorderremark { set; get; }
        }

        public class uploadSatisfaction
        {
            public string cenrollid { set; get; }
            public int Satisfaction { set; get; }
        }
        [HttpPost]
        public ActionResult updateSatisfaction(uploadSatisfaction info)
        {
            if (info == null)
                return Error("内容为空");
            try
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存工单信息

                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
                    modelT_Bus_WorkOrder.F_OldWorkOrderId = info.cenrollid;
                    var workorder = workorderBLL.GetModelList("F_OldWorkOrderId='" + modelT_Bus_WorkOrder.F_OldWorkOrderId + "'" +
                        "and F_IsDelete=0");
                    if (workorder != null && workorder.Count > 0)
                    {
                      //  modelT_Bus_WorkOrder = workorder[0];
                      //  modelT_Bus_WorkOrder.F_Satisfaction = info.Satisfaction;
                      //  var workorderlist = workorderBLL.GetModelList("F_MainWorkOrderId='" + workorder[0].F_WorkOrderId  +
                       // "and F_IsDelete=0");
                      //  if (workorderlist != null && workorderlist.Count > 0)
                       // {
                            foreach (var it in workorder)
                            {
                                it.F_Satisfaction = info.Satisfaction;
                                workorderBLL.Update(it);
                            }
                      //  }
                    }
                    else
                    {
                        return Error("系统不存在此工单");
                    }
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #endregion
                    trans.Complete();
                }
                return Success("操作成功");
            }
            catch (Exception ex)
            {
                return Error("操作失败" + ex.Message);
            }
        }
      

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

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

                    modelT_Bus_WorkOrder.F_OldWorkOrderId = info.cenrollid;
                    var workorder = workorderBLL.GetModelList("F_OldWorkOrderId='" + modelT_Bus_WorkOrder.F_OldWorkOrderId + "'" +
                        "and F_IsDelete=0");
                    if (workorder != null && workorder.Count > 0)
                    {
                        
                        modelT_Bus_WorkOrder = workorder[0];
                        if (info .ideliverprogress  ==11)
                        {
                            if (workorder[0].IsExport !=1 )
                            {
                                return Success("操作成功");
                            }
                            workorder[0].IsExport = 0;
                            workorder[0].F_WorkState = 11;
                        }
                        else
                        {
                            return Success("操作成功");
                            //Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetModelList(" F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' order by F_CreateTime desc ").FirstOrDefault();
                            //if (modelT_Bus_AssignedInfo != null)
                            //{
                            //    Model.T_Bus_Feedback modelT_Bus_Feedback = feedbackBLL.GetModelList(" F_AssignedId=" + modelT_Bus_AssignedInfo.F_Id + " and F_IsFeedEnd=1 and   F_State=1  order by F_CreateTime desc").FirstOrDefault();
                            //    #region 重办驳回时-恢复主办单位 zhengbingbing 20191017
                            //    modelT_Bus_WorkOrder.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;
                            //    modelT_Bus_WorkOrder.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;
                            //    modelT_Bus_WorkOrder.F_DealDeptId = modelT_Bus_Feedback.F_CreateDeptId;
                            //    modelT_Bus_WorkOrder.F_DealUser = modelT_Bus_Feedback.F_CreateUser;
                            //    modelT_Bus_WorkOrder.F_DealTime = modelT_Bus_Feedback.F_CreateTime;
                            //    #endregion
                            //}
                            //workorder[0].F_WorkState = 13;
                        }
                    }
                    else
                    {
                        modelT_Bus_WorkOrder.F_WorkState = 1;
                        modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID("8000");
                    }
                    if (info.ideliverprogress == 11)
                        modelT_Bus_WorkOrder.F_Backreason = info.backreason;
                    if (info .type ==1)
                        modelT_Bus_WorkOrder.F_InfoSource = 2;//信息来源
                    else if (info.type == 3)
                        modelT_Bus_WorkOrder.F_InfoSource = 89;//信息来源
                    else
                        modelT_Bus_WorkOrder.F_InfoSource = 3;//信息来源
                    modelT_Bus_WorkOrder.F_CusName = info.custname;
                    modelT_Bus_WorkOrder.F_NewRemarks = info.workorderremark;
                    modelT_Bus_WorkOrder.F_ConName = info.custname; ;//联系人姓名
                    modelT_Bus_WorkOrder.F_CusPhone = info .phone;//
                    modelT_Bus_WorkOrder.F_ConPhone = info.phone;//联系人
                    try
                    {
                        modelT_Bus_WorkOrder.F_CreateTime =DateTime .Parse ( info.tsystime);
                    }
                    catch
                    {
                        modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;
                    }
                    modelT_Bus_WorkOrder.F_Event = info .ismallcategory ;//事件类别
                    modelT_Bus_WorkOrder.F_Transferor =info .unit_code ;//转办人
                    try
                    {
                        modelT_Bus_WorkOrder.F_TransferTime = DateTime.Parse(info .transferTime );
                    }
                    catch
                    {
                        modelT_Bus_WorkOrder.F_TransferTime = DateTime.Now;
                    }
                    modelT_Bus_WorkOrder.F_ComTitle = info.title;
                    modelT_Bus_WorkOrder.F_Transferunit =info .transferunit ;//转办单位
                    modelT_Bus_WorkOrder.F_ComContent = info .content ;//
                    modelT_Bus_WorkOrder.F_ResultRemarks = info .advice ;//拟办意见
                    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfos = new Model.T_Bus_AssignedInfo();
                    if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_ResultRemarks))
                    {

                        try
                        {
                            string[] limtim = modelT_Bus_WorkOrder.F_ResultRemarks.Split('于', '月', '日', '前');
                            DateTime limittime = DateTime.Parse(DateTime.Now.ToString("yyyy") + "年" + limtim[1] + "月" + limtim[2] + "日" + " 23:59:59");
                            if (limittime < DateTime.Now && limittime.Month == 1)
                            {
                                limittime = limittime.AddYears (1);
                            }
                            modelT_Bus_WorkOrder.F_LimitTime = limittime;
                        }
                        catch
                        {

                        }
                    }
                    modelT_Bus_WorkOrder.F_FinalOpinion =info .result ;//处理结果
                    modelT_Bus_WorkOrder.F_Result = info .remark ;//回访情况
                    modelT_Bus_WorkOrder.F_Remarks = "★以上登记信息仅供市长热线平台及承办人员查阅，未经许可不得向外提供";//
                    modelT_Bus_WorkOrder.F_IsDelete = 0;
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;
                   
                    if (modelT_Bus_WorkOrder.F_Id > 0)
                    {
                        workorderBLL.Update(modelT_Bus_WorkOrder);
                    }
                    else
                    {

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

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

                        string source = string.Empty;
                        switch (info.type)
                        {
                            case 1:source = "信箱";break;
                            case 2: source = "承办"; break;
                            case 3: source = "APP"; break;
                        }
                        var caseobj = new
                        {
                            problemCode = info.cenrollid,//事件id
                            code = info.cenrollid,//事件编号
                            problemTitle = info.title,//事件标题
                            problemType = info.ismallcategory,//事件类型
                            problemSmallType = "",//事件小类
                            ptype = "",//述求类型（建议、咨询、投诉、求助）
                            problemWay = source,//述求来源
                            problemDescription = info.content,//事件内容
                            problemSite = "",//事件地址
                            timeLimit = modelT_Bus_WorkOrder.F_LimitTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",//处理时限
                            reporter = info.custname,//上报人
                            reporterContactInfo = info.phone,//上报人联系电话
                            reportTime = info.tsystime,//上报时间（年月日时分秒格式）
                            forwarder = "",//登记人
                            forwardTime = info.tsystime,//登记时间（年月日时分秒格式）
                            processUser = info.unit_code,//处理人
                            did = "GY12345"//业务系统标识
                        };

                        string url = Configs.GetValue("PushUrl");
                        string result = HttpMethods.HttpPost(url, caseobj.ToJson(), "application/json");
                        LogFactory.GetLogger("PushCase").Info(info.cenrollid + "推送结果：" + result);
                    }
                    #endregion
                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = "郑州市系统";
                    if (modelT_Bus_WorkOrder.F_WorkState ==0 || modelT_Bus_WorkOrder.F_WorkState == 1)
                    {
                        oper.F_Message = userinfo + " 登记了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    else
                    {
                        oper.F_Message = userinfo + " 提交重办了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    oper.F_CreateUser = "8000";
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);
                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            catch (Exception ex)
            {
                return Error("操作失败" + ex.Message);
            }
        }
        [HttpPost]
        public ActionResult AddWorkorders(string message )
        {
            if (string.IsNullOrEmpty(message))
                return Error("内容为空");
            try
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存工单信息

                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
                    string[] value = { "案件编号：", "来电人", "联系电话",
                     "登记时间" ,"事件类别","转办人" ,
                    "转办时间","转办单位","详细内容"
                ,"拟办意见","处理结果","回访情况","★"};
                   
                    string[] values = message.Split(value, StringSplitOptions.RemoveEmptyEntries);
                    modelT_Bus_WorkOrder.F_OldWorkOrderId = values[1].Replace("\r", "")
                      .Replace("\a", "");
                    var workorder = workorderBLL.GetModelList("F_OldWorkOrderId='" + modelT_Bus_WorkOrder.F_OldWorkOrderId + "'" +
                        "and F_IsDelete=0");
                    if (workorder!=null&& workorder.Count >0)
                    {
                        modelT_Bus_WorkOrder = workorder[0];
                        if (workorder[0].F_WorkState <=3)
                        {
                            workorder[0].F_WorkState = 11;
                        }
                        else if (workorder[0].F_WorkState == 4)
                        {
                            workorder[0].F_WorkState = 8;
                        }
                        else
                        {
                            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetModelList(" F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' order by F_CreateTime desc ").FirstOrDefault();
                            if (modelT_Bus_AssignedInfo!=null )
                            {
                                Model.T_Bus_Feedback modelT_Bus_Feedback = feedbackBLL.GetModelList(" F_AssignedId=" + modelT_Bus_AssignedInfo.F_Id + " and F_IsFeedEnd=1 and   F_State=1  order by F_CreateTime desc").FirstOrDefault();
                                #region 重办驳回时-恢复主办单位 zhengbingbing 20191017
                                modelT_Bus_WorkOrder.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;
                                modelT_Bus_WorkOrder.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;
                                modelT_Bus_WorkOrder.F_DealDeptId = modelT_Bus_Feedback.F_CreateDeptId;
                                modelT_Bus_WorkOrder.F_DealUser = modelT_Bus_Feedback.F_CreateUser;
                                modelT_Bus_WorkOrder.F_DealTime = modelT_Bus_Feedback.F_CreateTime;
                                #endregion
                            }

                            workorder[0].F_WorkState = 13;
                        }
                        
                    }
                    else
                        modelT_Bus_WorkOrder.F_WorkState = 1;
                    modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID("8000");

                  
                    if (modelT_Bus_WorkOrder.F_OldWorkOrderId.Contains("xx"))
                        modelT_Bus_WorkOrder.F_InfoSource = 2;//信息来源
                    else
                        modelT_Bus_WorkOrder.F_InfoSource = 3;//信息来源
                    modelT_Bus_WorkOrder.F_CusName = values[2].Replace("\r", "")
                        .Replace("\a", "");//
                    modelT_Bus_WorkOrder.F_ConName = values[2].Replace("\r", "")
                        .Replace("\a", "");//联系人姓名
                    modelT_Bus_WorkOrder.F_CusPhone = values[3].Replace("\r", "")
                        .Replace("\a", "");//
                    modelT_Bus_WorkOrder.F_ConPhone = values[3].Replace("\r", "")
                        .Replace("\a", "");//联系人姓名
                    try
                    {
                        modelT_Bus_WorkOrder.F_CreateTime = DateTime.Parse(values[4].Replace("\r", "")
                        .Replace("\a", ""));
                    }
                    catch
                    {
                        modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;
                    }
                    modelT_Bus_WorkOrder.F_Event = values[5].Replace("\r", "")
                        .Replace("\a", "");//事件类别
                    modelT_Bus_WorkOrder.F_Transferor = values[6].Replace("\r", "")
                        .Replace("\a", "");//转办人
                    try
                    {
                        modelT_Bus_WorkOrder.F_TransferTime = DateTime.Parse(values[7].Replace("\r", "")
                        .Replace("\a", ""));
                    }
                    catch
                    {
                        modelT_Bus_WorkOrder.F_TransferTime = DateTime.Now;
                    }

                    modelT_Bus_WorkOrder.F_Transferunit = values[8].Replace("\r", "")
                        .Replace("\a", "");//转办单位
                    modelT_Bus_WorkOrder.F_ComContent = values[9].Replace("\r", "")
                        .Replace("\a", "");//
                    modelT_Bus_WorkOrder.F_ResultRemarks = values[10].Replace("\r", "")
                        .Replace("\a", "");//拟办意见
                    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfos = new Model.T_Bus_AssignedInfo();
                    if (!string .IsNullOrEmpty(modelT_Bus_WorkOrder.F_ResultRemarks))
                    {

                        try
                        {
                            string[] limtim = modelT_Bus_WorkOrder.F_ResultRemarks.Split('于', '月', '日', '前');
                            DateTime limittime = DateTime.Parse(DateTime.Now.ToString("yyyy") + "年" + limtim[1] + "月" + limtim[2] + "日" + " 23:59:59");
                            modelT_Bus_WorkOrder.F_LimitTime = limittime;
                        }
                        catch
                        {

                        }
                      
                    }
                 

                    modelT_Bus_WorkOrder.F_FinalOpinion = values[11].Replace("\r", "")
                        .Replace("\a", "");//处理结果
                    modelT_Bus_WorkOrder.F_Result = values[12].Replace("\r", "")
                        .Replace("\a", "");//回访情况
                    modelT_Bus_WorkOrder.F_Remarks = "★" + values[13].Replace("\r", "")
                        .Replace("\a", "");//

                    modelT_Bus_WorkOrder.F_IsDelete = 0;
                    modelT_Bus_WorkOrder.F_Files = "";
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;
                    if(modelT_Bus_WorkOrder.F_Id >0)
                    {
                        workorderBLL.Update (modelT_Bus_WorkOrder);
                    }
                    else
                    {
                        workorderBLL.Add(modelT_Bus_WorkOrder);
                    }
                 
                    #endregion

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

                    string userinfo = "系统";
                    //if (modelT_Bus_WorkOrder.F_WorkState == 0)
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.neworder || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)
                    {
                        oper.F_Message = userinfo + " 登记了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    oper.F_CreateUser = "8000";
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;

                    operBLL.Add(oper);


                    #endregion

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

            
           
            
           
        }
        /// <summary>
        /// 获取领导处理列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetLDDealList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            string sql = " and F_IsDelete=0";
            string strtab = HttpUtility.UrlDecode(RequestString.GetQueryString("tab"));
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            int deptlevel = RequestString.GetInt("deptlevel", 0);
            int issatisfie = RequestString.GetInt("issatisfie", -1);//0不满意 1满意
            string strisaudit = HttpUtility.UrlDecode(RequestString.GetQueryString("isaudit"));
            string hcstrstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("hcstrstarttime"));
            string hcstrendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("hcstrendtime"));

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            int IsExport = RequestString.GetInt("isexport", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            //if (IsExport > 0)
            //{
            //    sql += " and IsExport = '" + IsExport + "' ";
            //}
            switch (strtab)
            {
                case "0"://待处理工单
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else if (strstate.Trim() == ((int)EnumWorkState.submit).ToString())
                            sql += " and F_WorkState in (" + (int)EnumWorkState.submit + "," + (int)EnumWorkState.resubmit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        if (strstate.Trim() == ((int)EnumWorkState.visit).ToString() && issatisfie != -1)
                        {
                            sql += "  and F_WorkOrderID in (select F_WorkOrderID from T_Bus_VisitResult WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";
                            sql += "  and F_IsSatisfie='" + issatisfie + "')";
                        }
                        if (strstate.Trim() != ((int)EnumWorkState.submit).ToString())
                        {
                            sql += "  and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";

                            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG"&& userModel.F_RoleCode != "ZXLD")
                            {
                                sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                            }
                            else
                            {
                                sql += ")";
                            }
                            //不限制电话件
                           
                        }
                        else
                        {
                            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                            {
                                sql += " and (F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo WITH(NOLOCK) where F_State = 1 and F_IsDelete = 0 "
                                    + "and F_CreateUser = '" + userModel.F_UserCode + "') or (select top 1 F_WorkOrderId from T_Bus_AssignedInfo WITH(NOLOCK) where"
                                    + " F_State = 1 and F_IsDelete = 0 and T_Bus_AssignedInfo.F_WorkOrderId = T_Bus_WorkOrder.F_WorkOrderId) is null)";
                            }
                          //  sql += " and (F_InfoConBigType =1 or F_InfoConBigType is null )";
                        }
                    }
                    else
                    {
                        //int[] sts = new int[] { (int)EnumWorkState.submit, (int)EnumWorkState.receive, (int)EnumWorkState.auditreback, (int)EnumWorkState.auditdelay, (int)EnumWorkState.visit, (int)EnumWorkState.reload };
                        //sql += " and F_WorkState in (" + string.Join(",", sts.Select(p => p.ToString())) + ")";
                        ////sql += " and F_WorkState in (1,2,3,5,7,8)";

                        //int[] sts = new int[] { (int)EnumWorkState.receive, (int)EnumWorkState.auditreback, (int)EnumWorkState.auditdelay, (int)EnumWorkState.visit, (int)EnumWorkState.reload };
                        //sql += " and (F_WorkState='" + (int)EnumWorkState.submit + "' or ( F_WorkState in (" + string.Join(",", sts.Select(p => p.ToString())) + ") and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";
                        sql += " and (F_WorkState='" + (int)EnumWorkState.submit + "' or   F_WorkState ='" + (int)EnumWorkState.resubmit + "')   ";// and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";


                        if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                        {
                            sql += " and F_CreateUser='" + userModel.F_UserCode + "' ";
                        }
                       
                    }
                    break;
                case "1"://已交办的工单
                    string strjbstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("jbstarttime"));
                    string strjbendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("jbendtime"));
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        // sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";
                    if (strjbstarttime.Trim() != "" && strjbstarttime != "undefined")
                    {
                        sql += " and datediff(day,F_CreateTime,'" + strjbstarttime + "')<=0 ";
                    }
                    if (strjbendtime.Trim() != "" && strjbendtime != "undefined")
                    {
                        sql += " and datediff(day,F_CreateTime,'" + strjbendtime + "')>=0   ";
                    }
                    //if (deptid != 0)
                    //{
                    //    //sql += " and ',' + F_MainDeptID + ',' like '%," + deptid.ToString() + ",%'";
                    //    sql += " and F_MainDeptId = '" + deptid + "'";
                    //}
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    ////根据回传时间判断
                    //if (hcstrstarttime.Trim() != "" && hcstrstarttime != "undefined")
                    //{
                    //    sql += " and F_Hcdatetime >= '" + hcstrstarttime + "  00:00:00'";
                    //    //sql += " and datediff(day,F_Hcdatetime,'" + hcstrstarttime + "')<=0 ";
                    //}
                    //if (hcstrendtime.Trim() != "" && hcstrendtime != "undefined")
                    //{
                    //    sql += "  and F_Hcdatetime<='" + hcstrendtime + " 23:59:59'   ";
                    //    //sql += " and datediff(day,F_Hcdatetime,'" + hcstrendtime + "')>=0   ";
                    //}
                    break;
                case "2"://已审核退回的工单
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in (select F_WorkOrderID from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";// and F_IsAudit>0
                    if (!string.IsNullOrEmpty(strisaudit))
                    {
                        sql += " and F_IsAudit='" + strisaudit + "'";

                        if (deptid > 0)
                        {
                            sql += "  and F_CreateDeptId='" + deptid + "'";
                        }
                    }

                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += " and F_AuditUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "3"://已审核延时的工单
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in (select F_WorkOrderID from T_Bus_DelayTime WITH(NOLOCK) where F_State=1 and F_IsDelete=0  "; //and F_IsAudit>0
                    if (!string.IsNullOrEmpty(strisaudit))
                    {
                        sql += " and F_IsAudit='"+strisaudit+"'";
                    }
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += " and F_AuditUser='" + userModel.F_UserCode + "')";
                    }
                    else 
                    {
                        sql += ")";
                    }
                    break;
                case "4"://已重办的工单
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_IsReload>0 ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += " and F_ReloadUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "5"://已结案的工单
                    string strwjstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("wjstarttime"));
                    string strwjendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("wjendtime"));
                    sql += "  and F_WorkState =9 and F_IsDelete=0 and F_IsClosed=1 ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += " and F_CloseUser='" + userModel.F_UserCode + "'";
                    }
                    if (strwjstarttime.Trim() != "" && strwjstarttime != "undefined")
                    {
                        sql += " and datediff(day,F_CloseTime,'" + strwjstarttime + "')<=0 ";
                    }
                    if (strwjendtime.Trim() != "" && strwjendtime != "undefined")
                    {
                        sql += " and datediff(day,F_CloseTime,'" + strwjendtime + "')>=0   ";
                    }
                    break;
                case "6"://已督办的工单 
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_RemindRecord WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type =1 ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "7"://已监察的工单 
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    //sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_RemindRecord where F_State=1 and F_IsDelete=0 and F_Type =2 ";
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_RemindRecord WITH(NOLOCK) where F_IsDelete=0 and F_Type =2 ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "8"://待督办列表
                    //20190315需求变动，由督办查看督办列表并监管 20190401 zhengbingbing
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_RemindRecord WITH(NOLOCK) where F_State=0 and F_IsDelete=0 and F_Type =1 ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode!= "DBZY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "9"://重办驳回列表
                    sql += " and F_WorkState="+ (int)EnumWorkState.rejload;
                    sql += " and F_WorkOrderID in (select F_WorkOrderId from T_Bus_Operation WITH(NOLOCK) where F_Id in (select max(F_Id) from T_Bus_Operation WITH(NOLOCK) where F_State = " + (int)EnumWorkState.resubmit + " and F_WorkOrderId in (select F_WorkOrderId from T_Bus_Operation WITH(NOLOCK) where F_State=" + (int)EnumWorkState.rejload + ") group by F_WorkOrderId)";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "'";
                    }
                    sql += ")";
                    break;
            }

            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }
            #region  坐席&调度员
            if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }
            if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                }
            }
            //if (strusercode.Trim() != "" && strusercode != "undefined")
            //{
            //    sql += " and F_CreateUser = '" + strusercode + "' ";
            //}
            #endregion

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

            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }
            if (deptid != 0 && strtab != "1")
            {
                if (deptlevel == 0)
                {
                    string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                    //string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo where ',' + F_MainDeptID + ',' like '%," + deptid.ToString() + ",%' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                    sql += " and F_WorkOrderID in(" + sqlwhere + ")";
                }
                else
                {
                    //string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo_Next where ',' + F_MainDeptID + ',' like '%," + deptid.ToString() + ",%' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                    string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo_Next WITH(NOLOCK) where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                    sql += " and F_WorkOrderID in(" + sqlwhere + ")";
                }
            }
            if(deptid!=0)
            {
                sql += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
            }

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

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

            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetOverState(F_WorkOrderId) as OverState,"
            //    + "dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetWorkOrderAssign(F_WorkOrderId) as DeptName ,dbo.GetLimitTime(F_WorkOrderId) as LimitTime";
            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";
            string cols = "F_OldWorkOrderId,F_Level,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetDictionaryName(F_InfoConBigType) as InfoConBigTypeName,F_Files,F_WorkRemarks,requirementFinishDay,F_LimitTime";
            string colst = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetDictionaryName(F_InfoConBigType) as InfoConBigTypeName";
            if (isdc > 0)
            {
                var top = ""; 
                if (sql == " and F_IsDelete=0 ")
                {
                    top = " top 1000 ";
                }
                //日期，工单号，诉求标题，诉求内容，承办单位，办理结果，是否满意，备注
                //var dtdc = DbHelperSQL.Query(" select " + top + " F_CreateTime 日期, F_OldWorkOrderId 工单号,F_ComTitle 诉求标题,F_CusName 反映人,F_CusPhone 电话号码,F_ComContent 诉求内容,dbo.GetDictionaryName(F_Key) 主题词, "
                //   + " dbo.GetDeptNames(F_MainDeptId) 承办单位, "
                //   + " (select top 1 F_Situation from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId =wo.F_WorkOrderId order by F_CreateTime) 办理结果,"
                //   + " (select top 1 (case F_IsSatisfie when 1 then'满意' when 0 then '不满意'when 2 then '基本满意' else '未评价' end) F_Satisfie from T_Bus_VisitResult WITH(NOLOCK) where F_State = 1 and F_IsDelete = 0 and F_WorkOrderId = wo.F_WorkOrderId order by F_Id desc) 承办单位回访结果" +
                //  " from T_Bus_WorkOrder wo WITH(NOLOCK) where 1=1 " + sql + sort).Tables[0];



                var dtdc = DbHelperSQL.Query("select F_workorderid 案件编号, (case F_IsResult when 0 then '网络转办' when 1 then '当即办理' else '' end) 处理类型,F_ComTitle 题目, F_Event 舆情来源, dbo.GetDeptNames(F_MainDeptId) 承办单位,  F_LimitTime   办理时限 from T_Bus_WorkOrder wo WITH(NOLOCK) where 1=1 " + sql + sort).Tables[0];



                //var dtdc = DbHelperSQL.Query(" select " + colst + " from T_Bus_WorkOrder WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    //if (strstate.Trim() == ((int)EnumWorkState.finish).ToString())
                    //{
                    //    var dtex = DbHelperSQL.Query("update T_Bus_WorkOrder set IsExport=1 where 1=1 " + sql).Tables[0];
                    //}
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
                sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("OverState", typeof(string));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("FilePath", typeof(string));//语音文件路径
            dt.Columns.Add("Buttons", typeof(object));//操作按钮
            dt.Columns.Add("IsFiles", typeof(object));//操作按钮
            
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            var reminds = remindBLL.GetModelList("F_State=0 and F_IsDelete=0 and F_Type =1").ToList();
            foreach (DataRow dr in dt.Rows)
            {
                //获取最新交办信息
                string iszbdw = "0";
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        //if (dtjb.Rows[0]["F_MainDeptId"] != null && dtjb.Rows[0]["F_MainDeptId"].ToString().Split(',').Contains(userModel.F_DeptId.ToString())) { iszbdw = "1"; }
                        if (dtjb.Rows[0]["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                        #region
                        //int did = Int32.Parse(dtjb.Rows[0]["F_MainDeptId"].ToString());
                        //var deptinfo = new BLL.T_Sys_Department().GetModel(did);
                        //if (deptinfo != null)
                        //{
                        //    if (did == userModel.F_DeptId) { iszbdw = "1"; }
                        //    dr["DeptName"] = deptinfo.F_DeptName;//交办单位
                        //}
                        //if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        //{
                        //    string[] strids = dtjb.Rows[0]["F_OtherDeptIds"].ToString().Split(',');
                        //    string dns = string.Empty;
                        //    foreach (string strid in strids)
                        //    {
                        //        var dinfo = new BLL.T_Sys_Department().GetModel(Int32.Parse(strid));
                        //        if (dinfo != null)
                        //        {
                        //            if (string.IsNullOrEmpty(dns))
                        //            {
                        //                dns = dinfo.F_DeptName;//交办单位
                        //            }
                        //            else
                        //            {
                        //                dns += "," + dinfo.F_DeptName;//交办单位
                        //            }
                        //        }
                        //    }
                        //    dr["OtherDeptName"] = dns;
                        //}
                        #endregion
                        #region
                        //if (state < 6 || state == 8)
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                            dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        if (state == (int)EnumWorkState.finish)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            var dttime = DateTime.Now;
                            if (!string.IsNullOrWhiteSpace(closetime)) { dttime = DateTime.Parse(closetime); }
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                            dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(dttime);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime < dttime)
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        #endregion
                    }
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }

                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    if (!string.IsNullOrEmpty(dr["F_Files"].ToString()))
                        dr["IsFiles"] = 1;
                    else
                        dr["IsFiles"] = 0;
                }
                else
                {
                    dr["IsFiles"] = 0;
                }
                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                if (Int32.Parse(strtab) <= 1)
                {
                    btns.Add(ButtonGroup.query());
                    if (Int32.Parse(strtab)==1)
                    {
                      //  btns.Add(ButtonGroup.query());
                        if (dr["F_WorkState"].ToString() == "2" || dr["F_WorkState"].ToString() == "4" || dr["F_WorkState"].ToString() == "8")
                        {
                            if (userModel.F_RoleCode.ToUpper() == "ZXLD" || userModel.F_RoleCode.ToUpper() == "ZXLDGLYGLY" || userModel.F_RoleCode.ToUpper() == "GLY" || userModel.F_RoleCode.ToUpper() == "DDZG")
                            {
                                btns.Add(ButtonGroup.takeback());
                            }
                        }
                    }
                    else 
                   btns = ButtonGroup.GetButtons(dr["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw);
                    #region 判断是否存在待督办
                    var recount = reminds.Where(r => r.F_WorkOrderId == dr["F_WorkOrderId"].ToString()).Count();
                    var butt = btns.Find(c => c.key == ButtonGroup.turnsee().key);
                    if (recount > 0 && butt != null)
                        btns.Remove(butt);
                    #endregion
                }
                else
                {
                    btns.Clear();
                    if (Int32.Parse(strtab) == 8)
                        btns = ButtonGroup.GetButtons("12", userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw);
                    else
                        btns.Add(ButtonGroup.query());

                }
                dr["Buttons"] = btns;
            }
            #endregion

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

        /// <summary>
        /// 获取单位处理列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetDWDealList(int isdc = 0)
        {

            DataTable dt = new DataTable();
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            //int userId = 689;
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            string sql = " and F_IsDelete=0";
            string strtab = HttpUtility.UrlDecode(RequestString.GetQueryString("tab"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));

            string strisaudit = HttpUtility.UrlDecode(RequestString.GetQueryString("isaudit"));

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

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            int IsExport = RequestString.GetInt("isexport", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime DESC";
            if (timesort == 0)
                sort = "ORDER BY F_LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            if (IsExport > 0)
            {
                sql += " and IsExport = '" + IsExport + "' ";
            }
            #region 模块
            switch (strtab)
            {
                case "0"://待处理工单
                    sort = "ORDER BY F_LimitTime  ASC ,F_CreateTime desc";
                    int isyq = RequestString.GetInt("isyq", -1);
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                     
                        else 
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    else
                    {
                        int[] sts = new int[] { (int)EnumWorkState.receive, (int)EnumWorkState.dealing, (int)EnumWorkState.reload };
                        sql += " and F_WorkState in (" + string.Join(",", sts.Select(p => p.ToString())) + ")";
                        //sql += " and F_WorkState in (2,4,8)";
                    }
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and "
                        //+ " ISNULL(F_FeedbackTime, '')='' and ((F_MainDeptId =" + userModel.F_DeptId + " and F_IsSure in (0,1)) or "
                        //+ "(','+F_OtherDeptIds+',' like '%," + userModel.F_DeptId + ",%' and F_IsSure=1))";
                        //+ " ISNULL(F_FeedbackTime, '')='' and ',' + F_MainDeptID + ',' like '%," + userModel.F_DeptId + ",%' and F_IsSure in (0,1)";
                        + " ISNULL(F_FeedbackTime, '')='' and F_MainDeptId =" + userModel.F_DeptId + " and F_IsSure in (0,1)";
                        if (isyq != -1)
                        {
                            sql += " and dbo.GetOverState(F_WorkOrderId)=" + isyq;
                        }
                        else
                        {
                            sql += ")";
                        }
                    }
                    break;
                case "1"://已查收的工单
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_IsSure=1 ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_SureUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "2"://已申请退回的工单
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type = 3 ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                        sql += " and F_MainDeptId='" + userModel.F_DeptId + "'";
                    }
                    else
                    {
                        sql += ")";
                    }
                    
                   
                    break;
                case "3"://已申请延时的工单
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_DelayTime WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "4"://已办理的工单 
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sort = "ORDER BY F_CreateTime DESC";
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type in (1,2) ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "5"://被督办的工单 
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_RemindRecord WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type =1 ";

                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_DeptId='" + userModel.F_DeptId + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "6"://被监察的工单 
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    //sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_RemindRecord where F_State=1 and F_IsDelete=0 and F_Type =2 ";
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_RemindRecord WITH(NOLOCK) where F_IsDelete=0 and F_Type =2 ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_DeptId='" + userModel.F_DeptId + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "7"://延时审核中的工单 
                         //sql += " and F_WorkState = '" + (int)EnumWorkState.auditdelay + "' ";
                         //sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";

                    sql += "   and F_WorkOrderID in (select F_WorkOrderID from T_Bus_DelayTime WITH(NOLOCK) where F_State= 1 and F_IsDelete = 0";
                    if (!string.IsNullOrEmpty(strisaudit))
                    {
                        sql += " and F_IsAudit='" + strisaudit + "'";
                    }
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLDGLY" && userModel.F_RoleCode != "ZXLDGLYGLY" && userModel.F_RoleCode != "ZXLD" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "8"://退回审核中的工单 
                    sql += " and F_WorkState = '" + (int)EnumWorkState.auditreback + "' ";
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_IsSure=2 and isnull(F_FeedbackTime,'')=''";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_SureUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                case "9"://需履职界定表
                    sql += " and F_WorkState in ('" + (int)EnumWorkState.visit + "','" + (int)EnumWorkState.resubmit + "','" + (int)EnumWorkState.reload + "','" + (int)EnumWorkState.rejload + "','" + (int)EnumWorkState.finish + "' )";
                    sql += " and F_WorkOrderID not in(select F_WorkOrderID from T_Bus_PerformDuties WITH(NOLOCK) where F_IsDelete=0 and F_State=1 )";
                    sql += " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_VisitResult WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_IsSatisfie=0 and F_AssignedId in(select F_ID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0   ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_MainDeptId='" + userModel.F_DeptId + "' ";
                    }
                    sql += "))";
                    break;
                case "10"://履职界定待审核表
                    
                    sql += " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_PerformDuties WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_IsAudit=0 )";
                    break;
                case "11"://履职界定已审核表

                    sql += " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_PerformDuties WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_IsAudit>0 )";
               
                    break;
                case "12"://领导批示
                   
                    sql += "  and F_WorkOrderID in(select F_WorkOrderId from T_Bus_SubmitSuper WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type=1 )";
                    if (userModel.F_RoleCode != "GLY"  && userModel.F_RoleCode != "ZXLD" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_MainDeptId='" + userModel.F_DeptId + "'";
                    }
                   
                    break;
                   
                #region  增加催办列表：被催办的工单可以在此列表进行显示处理，二级单位可以在此进行催办处理 20220316
                case "13"://被催办的工单 
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString())
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and ReminderNum>0 and F_WorkOrderID in(select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_IsSure in (0,1)";

                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += "  and F_WorkState in ('" + (int)EnumWorkState.receive + "','" + (int)EnumWorkState.dealing + "','" + (int)EnumWorkState.reload + "' )";
                        sql += " and F_MainDeptId='" + userModel.F_DeptId + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
                #endregion
                case "14": //督办列表
                    sql += "  and F_WorkOrderID in( select F_WorkOrderID from T_Bus_RemindRecord where F_Type=1 and F_IsDelete=0)";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLD" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_MainDeptId='" + userModel.F_DeptId + "'";
                    }

                    break;
                case "15"://扫描件未上传列表
                    sql += "    and  F_Files =''";
                    break;

            }
            #endregion

            #region 条件
            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }
            #region  坐席&调度员
            if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }
            if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                }
            }
            //if (strusercode.Trim() != "" && strusercode != "undefined")
            //{
            //    sql += " and F_CreateUser = '" + strusercode + "' ";
            //}
            #endregion

            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }
            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }
            if(deptid!=0)
            {
                sql += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
            }

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

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

            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetOverState(F_WorkOrderId) as OverState,"
            //    + "dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetWorkOrderAssign(F_WorkOrderId) as DeptName ,dbo.GetLimitTime(F_WorkOrderId) as LimitTime";
            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";
            //string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_Scanning,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks,requirementFinishDay"; 

            string cols = "F_OldWorkOrderId,F_Level, F_CusName,F_CusAddress,F_ComTitle,F_SourceAddress,F_Result,F_Key,F_Hcdatetime,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as InfoSourceName,dbo.GetDictionaryName(F_InfoConBigType) as InfoConBigTypeName,dbo.GetAreaName(F_SourceArea) as SourceAreaName,F_Scanning                 , F_WorkOrderId,  F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,  IsExport,F_Files,F_WorkRemarks,requirementFinishDay,F_Event,F_LimitTime";

            if (isdc > 0)
            {
                var top = " "; var orderby = " order by F_CreateTime";
                if (sql == " and F_IsDelete=0 ")
                {
                    top = " top 1000 "; orderby += " desc ";
                }
                //var dtdc = DbHelperSQL.Query(" select " + top + " F_CreateTime 日期, F_OldWorkOrderId 工单号,F_ComTitle 诉求标题,F_CusName 反映人,F_CusPhone 电话号码,F_ComContent 诉求内容,dbo.GetDictionaryName(F_Key) 主题词, "
                //    + " dbo.GetDeptNames(F_MainDeptId) 承办单位, "
                //    + " (select top 1 F_Situation from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId =wo.F_WorkOrderId order by F_CreateTime) 办理结果,"
                //    + " (select top 1 (case F_IsSatisfie when 1 then'满意' when 0 then '不满意'when 2 then '基本满意' else '未评价' end) F_Satisfie from T_Bus_VisitResult WITH(NOLOCK) where F_State = 1 and F_IsDelete = 0 and F_WorkOrderId = wo.F_WorkOrderId order by F_Id desc) 承办单位回访结果" +
                //   " from T_Bus_WorkOrder wo WITH(NOLOCK) where 1=1 " + sql + orderby).Tables[0];


                var dtdc = DbHelperSQL.Query("select F_workorderid 案件编号, (case F_IsResult when 0 then '网络转办' when 1 then '当即办理' else '' end) 处理类型,F_ComTitle 题目, F_Event 舆情来源, dbo.GetDeptNames(F_MainDeptId) 承办单位,  F_LimitTime   办理时限 from T_Bus_WorkOrder wo WITH(NOLOCK) where 1=1 " + sql + sort).Tables[0];

                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    //if (strstate.Trim() == ((int)EnumWorkState.finish).ToString())
                    //{
                    //    var dtex = DbHelperSQL.Query("update T_Bus_WorkOrder set IsExport=1 where 1=1 " + sql).Tables[0];
                    //}
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
                sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OverState", typeof(string));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("FilePath", typeof(string));//语音文件路径
            dt.Columns.Add("PDState", typeof(string));//派单状态
            dt.Columns.Add("Buttons", typeof(object));//操作按钮
            dt.Columns.Add("IsFiles", typeof(object));//操作按钮
            
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            var reminds = remindBLL.GetModelList("F_State=0 and F_IsDelete=0 and F_Type =1").ToList();
            foreach (DataRow dr in dt.Rows)
            {
                //获取最新交办信息
                string iszbdw = "0";
                string ispd = "";
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        if (dtjb.Rows[0]["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                        dr["LimitTime"] = dtjb.Rows[0]["F_LimitTime"].ToString();
                        #region
                        //int did = Int32.Parse(dtjb.Rows[0]["F_MainDeptId"].ToString());
                        //var deptinfo = new BLL.T_Sys_Department().GetModel(did);
                        //if (deptinfo != null)
                        //{
                        //    if (did == userModel.F_DeptId) { iszbdw = "1"; }
                        //    dr["DeptName"] = deptinfo.F_DeptName;//交办单位
                        //}

                        //if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        //{
                        //    string[] strids = dtjb.Rows[0]["F_OtherDeptIds"].ToString().Split(',');
                        //    string dns = string.Empty;
                        //    foreach (string strid in strids)
                        //    {
                        //        var dinfo = new BLL.T_Sys_Department().GetModel(Int32.Parse(strid));
                        //        if (dinfo != null)
                        //        {
                        //            if (string.IsNullOrEmpty(dns))
                        //            {
                        //                dns = dinfo.F_DeptName;//交办单位
                        //            }
                        //            else
                        //            {
                        //                dns += "," + dinfo.F_DeptName;//交办单位
                        //            }
                        //        }
                        //    }
                        //    dr["OtherDeptName"] = dns;
                        //}
                        #endregion
                        #region
                        //if (state < 6 || state == 8)
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                           dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }

                            ispd = dtjb.Rows[0]["F_IsNext"].ToString();
                            dr["PDState"] = ispd;
                        }
                        if (state == (int)EnumWorkState.finish)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            var dttime = DateTime.Now;
                            if (!string.IsNullOrWhiteSpace(closetime)) { dttime = DateTime.Parse(closetime); }
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                           
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(dttime);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime < dttime)
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        #endregion
                    }
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }
                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    if (!string.IsNullOrEmpty(dr["F_Files"].ToString()))
                        dr["IsFiles"] = 1;
                    else
                        dr["IsFiles"] = 0;
                }
                else
                {
                    dr["IsFiles"] = 0;
                }
                //string sqlpd = "SELECT TOP 1 * FROM T_Bus_AssignedInfo_Next WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 ORDER BY F_Id DESC";
                //var dtpd = DbHelperSQL.Query(sqlpd).Tables[0];

                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                if (Int32.Parse(strtab) < 1)
                {
                    btns = ButtonGroup.GetButtons(dr["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw, ispd);
                    #region 判断是否存在待督办
                    var recount = reminds.Where(r => r.F_WorkOrderId == dr["F_WorkOrderId"].ToString()).Count();
                    var butt = btns.Find(c => c.key == ButtonGroup.turnsee().key);
                    if (recount > 0 && butt != null)
                        btns.Remove(butt);
                   
                    #endregion
                }
                else
                {
                    if (Int32.Parse(strtab) == 9)
                    {//需履职界定
                        btns.Add(ButtonGroup.perform());
                    }
                    else if (Int32.Parse(strtab) == 10)
                    {//履职界定待审核
                        btns.Add(ButtonGroup.performaudit());
                    }
                    else if (Int32.Parse(strtab) == 12)
                    {//领导批示
                      //  btns.Add(ButtonGroup.subreload());
                    }
                    else   if (Int32.Parse(strtab) == 4)
                    {//履职界定待审核
                        if (dr["F_WorkState"].ToString()=="6")
                        btns.Add(ButtonGroup.visit());
                        //if (dr["F_Files"].ToString() == "")
                        //{
                        //    if (userModel.F_RoleCode.ToUpper() == "WLDW")
                        //        btns.Add(ButtonGroup.Upload());
                        //}
                            
                    }
                    else if (Int32.Parse(strtab) == 7 && strisaudit=="0")
                    {//履职界定待审核
                        btns.Add(ButtonGroup.auditdelay());
                    }
                    else if (Int32.Parse(strtab) == 13)
                    {//工单催办
                        if (userModel.F_RoleCode.ToUpper() == "ZXLD" || userModel.F_RoleCode.ToUpper() == "GLY")
                        {
                            btns.Add(ButtonGroup.Reminder());
                        }
                        else
                        {
                            btns = ButtonGroup.GetButtons(dr["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw, ispd);
                            var butt = btns.Find(c => c.key == ButtonGroup.Remkers().key);
                            if ( butt != null)
                                btns.Remove(butt);
                        }
                    }
                    btns.Add(ButtonGroup.query());
                }             
                dr["Buttons"] = btns;
            }
            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }
        /// <summary>
        /// 首页获取二级单位的交办数量和处理数量
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTwodeptjbdealcount(string stime, string etime, string deptid)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (string.IsNullOrEmpty(stime) && string.IsNullOrEmpty(etime))
            {
                stime = DateTime.Now.AddDays(1 - DateTime.Now.Day).ToString("yyyy-MM-dd hh:mm:ss");//本月月初
                etime = DateTime.Now.AddDays(1 - DateTime.Now.Day).AddMonths(1).ToString("yyyy-MM-dd hh:mm:ss");//本月月末
            }
            else
            {
                stime += " 00:00:00";
                etime += " 23:59:59";
            }
            //获取所有子类
            var deptlist = DbHelperSQL.Query("select * from T_Sys_Department where F_PartentId=" + deptid).Tables[0];
            List<Models.Dto.DeptJbdealCount> list = new List<Models.Dto.DeptJbdealCount>();
            foreach (DataRow dr in deptlist.Rows)
            {
                Models.Dto.DeptJbdealCount model = new Models.Dto.DeptJbdealCount();
                model.deptname = dr["F_DeptName"].ToString();
                #region 获取本部门的交办数量
                string sql = " select count(*) from T_Bus_WorkOrder  where F_IsDelete=0  and F_IsResult=0   ";
                sql += " and F_WorkOrderID in (select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 ";
                sql += " and datediff(day,F_CreateTime,'" + stime + "')<=0 ";
                sql += " and datediff(day,F_CreateTime,'" + etime + "')>=0   ";
                sql += ")";
                sql += " and F_MainDeptId=" + Convert.ToInt32(dr["F_DeptId"].ToString());
                var jbcount = DbHelperSQL.GetSingle(sql);
                model.jbcount = jbcount.ToString();
                #endregion

                #region 处理工单
                string sql1 = "select  count(*) from T_Bus_WorkOrder where F_IsDelete = 0 ";
                sql1 += "and F_WorkOrderID in(select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK)";
                sql1 += " where F_State= 1 and F_IsDelete = 0 and F_IsSure in (0,1)  ";
                sql1 += "and datediff(day, F_CreateTime,'" + stime + "')<= 0 ";
                sql1 += "and datediff(day, F_CreateTime,'" + etime + "')>= 0 ";
                sql1 += " and datediff(day, F_FeedbackTime,'" + stime + "')<= 0";
                sql1 += "and datediff(day, F_FeedbackTime,'" + etime + "')>= 0 )";
                sql1 += "and F_MainDeptId =" + Convert.ToInt32(dr["F_DeptId"].ToString());

                var dealcount = DbHelperSQL.GetSingle(sql1);
                model.dealcount = dealcount.ToString();
                #endregion
                list.Add(model);
            }
            return Success("成功",list);
        }


        /// <summary>
        /// 获取办理数量、催办数量、未上传数量
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetDcsCount()
        {
            
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
           // int userId = 751;
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            int isyq = RequestString.GetInt("isyq", -1);
            //获取待办理工单数量
            string sql = " select count(*) dblcount from T_Bus_WorkOrder where  F_IsDelete=0  and F_WorkState in (2,4,8) and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and "
                       + " ISNULL(F_FeedbackTime, '')='' and F_MainDeptId =" + userModel.F_DeptId + " and F_IsSure in (0,1)";

            if (isyq != -1)
            {
                sql += " and dbo.GetOverState(F_WorkOrderId)=" + isyq;
            }
            else
            {
                sql += ")";
            }
            //获取催办数量
            string sql1 = " select count(*) dblcount from T_Bus_WorkOrder where  F_IsDelete=0 and F_WorkState in(2,4,8) and ReminderNum>0 and F_WorkOrderID in(select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_IsSure in (0,1) and F_MainDeptId=" + userModel.F_DeptId + ") ";
            //扫描件未上传数量
            string sql2 = " select count(*) dblcount from T_Bus_WorkOrder where  F_IsDelete=0  and  F_Files ='' and F_WorkOrderID in (select F_WorkOrderID from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type in (1,2) and F_CreateUser='"+ userModel.F_UserCode + "') ";


            #region 获取待办理数量
            var dbldatable = DbHelperSQL.Query(sql).Tables[0];
            var dblrow = dbldatable.Rows;
            ///待办理数量
            var dblcount = dblrow[0]["dblcount"].ToString();
            #endregion
            #region 获取催办数量
            var cbdatable = DbHelperSQL.Query(sql1).Tables[0];
            var cblrow = cbdatable.Rows;
            ///催办数量
            var cblcount = cblrow[0]["dblcount"].ToString();
            #endregion
            #region 扫描件未上传数量
            var smjdatable = DbHelperSQL.Query(sql2).Tables[0];
            var smjlrow = smjdatable.Rows;
            ///扫描件未上传数量
            var smjcount = smjlrow[0]["dblcount"].ToString();
            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                dblcount= dblcount,
                cblcount= cblcount,
                smjcount= smjcount
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取单位处理列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetXBDWDealList(int isdc = 0)
        {

            DataTable dt = new DataTable();
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            string sql = " and F_IsDelete=0";
            string strtab = HttpUtility.UrlDecode(RequestString.GetQueryString("tab"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));

            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            switch (strtab)
            {
                case "0"://待处理工单
                    int isyq = RequestString.GetInt("isyq", -1);
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    else
                    {
                        int[] sts = new int[] { (int)EnumWorkState.receive, (int)EnumWorkState.dealing, (int)EnumWorkState.reload };
                        sql += " and F_WorkState in (" + string.Join(",", sts.Select(p => p.ToString())) + ")";
                        //sql += " and F_WorkState in (2,4,8)";
                    }

                    sql += " and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedItemInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and "
                    + " ISNULL(F_FeedbackTime, '')='' ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_DeptId =" + userModel.F_DeptId;
                    }
                    if (isyq != -1)
                    {
                        sql += " and dbo.GetOverState(F_WorkOrderId)=" + isyq;
                    }
                    else
                    {
                        sql += ")";
                    }

                    break;
                case "1"://已办理的工单 
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type in (1,2) ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
            }
            if(deptid!=0)
            {
                sql += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
            }
            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }
            #region  坐席&调度员
            if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }
            if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                }
            }
            //if (strusercode.Trim() != "" && strusercode != "undefined")
            //{
            //    sql += " and F_CreateUser = '" + strusercode + "' ";
            //}
            #endregion

            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }
            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetOverState(F_WorkOrderId) as OverState,"
            //    + "dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetWorkOrderAssign(F_WorkOrderId) as DeptName ,dbo.GetLimitTime(F_WorkOrderId) as LimitTime";
            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";
            string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks";
            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    //if (strstate.Trim() == ((int)EnumWorkState.finish).ToString())
                    //{
                    //    var dtex = DbHelperSQL.Query("update T_Bus_WorkOrder set IsExport=1 where 1=1 " + sql).Tables[0];
                    //}
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
                sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OverState", typeof(string));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("FilePath", typeof(string));//语音文件路径
            dt.Columns.Add("Buttons", typeof(object));//操作按钮
            dt.Columns.Add("IsFiles", typeof(object));//操作按钮
            
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            var reminds = remindBLL.GetModelList("F_State=0 and F_IsDelete=0 and F_Type =1").ToList();
            foreach (DataRow dr in dt.Rows)
            {
                //获取最新交办信息
                string iszbdw = "0";
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        if (dtjb.Rows[0]["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                        #region
                        //int did = Int32.Parse(dtjb.Rows[0]["F_MainDeptId"].ToString());
                        //var deptinfo = new BLL.T_Sys_Department().GetModel(did);
                        //if (deptinfo != null)
                        //{
                        //    if (did == userModel.F_DeptId) { iszbdw = "1"; }
                        //    dr["DeptName"] = deptinfo.F_DeptName;//交办单位
                        //}

                        //if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        //{
                        //    string[] strids = dtjb.Rows[0]["F_OtherDeptIds"].ToString().Split(',');
                        //    string dns = string.Empty;
                        //    foreach (string strid in strids)
                        //    {
                        //        var dinfo = new BLL.T_Sys_Department().GetModel(Int32.Parse(strid));
                        //        if (dinfo != null)
                        //        {
                        //            if (string.IsNullOrEmpty(dns))
                        //            {
                        //                dns = dinfo.F_DeptName;//交办单位
                        //            }
                        //            else
                        //            {
                        //                dns += "," + dinfo.F_DeptName;//交办单位
                        //            }
                        //        }
                        //    }
                        //    dr["OtherDeptName"] = dns;
                        //}
                        #endregion
                        #region
                        //if (state < 6 || state == 8)
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                            dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        if (state == (int)EnumWorkState.finish)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            var dttime = DateTime.Now;
                            if (!string.IsNullOrWhiteSpace(closetime)) { dttime = DateTime.Parse(closetime); }
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                            dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(dttime);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime < dttime)
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        #endregion
                    }
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }
                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    if (!string.IsNullOrEmpty(dr["F_Files"].ToString()))
                        dr["IsFiles"] = 1;
                    else
                        dr["IsFiles"] = 0;
                }
                else
                {
                    dr["IsFiles"] = 0;
                }
                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                if (Int32.Parse(strtab) < 1)
                {
                    btns = ButtonGroup.GetButtons(dr["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw);
                    #region 判断是否存在待督办
                    var recount = reminds.Where(r => r.F_WorkOrderId == dr["F_WorkOrderId"].ToString()).Count();
                    var butt = btns.Find(c => c.key == ButtonGroup.turnsee().key);
                    if (recount > 0 && butt != null)
                        btns.Remove(butt);
                    #endregion
                }
                else
                {
                    btns.Add(ButtonGroup.query());
                }
                dr["Buttons"] = btns;
            }
            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取单位主办协办未处理工单列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetDWNoDealList(int isdc = 0)
        {
            DataTable dt = new DataTable();

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            string sql = " and F_IsDelete=0";
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));

            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            if (userModel.F_RoleCode == "ZXHWY")
            {
                sql += " and F_CreateUser = '" + userModel.F_UserCode + "' ";
            }
            #region  坐席&调度员
            if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }
            if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                }
            }
            //if (strusercode.Trim() != "" && strusercode != "undefined")
            //{
            //    sql += " and F_CreateUser = '" + strusercode + "' ";
            //}
            #endregion


            sql += " and ( F_WorkOrderId in (select F_WorkOrderId  from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and isnull(F_FeedbackTime,'')='' and F_IsSure in (0,1) ";

            if (userModel.F_RoleCode == "WLDW")
            {
                sql += " and  (F_MainDeptId = '" + userModel.F_DeptId + "'  or F_MainDeptID3='" + userModel.F_DeptId + "')";
            }
            else if (deptid != 0)
            {
                sql += " and (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
            }

            sql += ") or F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedItemInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and ISNULL(F_FeedbackTime, '')='' ";

            if (userModel.F_RoleCode == "WLDW")
            {
                sql += " and  (F_DeptId = '" + userModel.F_DeptId + "' or F_MainDeptID3='" + userModel.F_DeptId + "')";
            }
            else if (deptid != 0)
            {
                sql += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
            }

            sql += "))";

            if (strstate.Trim() != "" && strstate != "undefined")
            {
                if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                    sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                else
                    sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
            }
            else
            {
                sql += " and F_WorkState in (2,4,8)";
            }
            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }

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

            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }

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

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

            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName ";
            string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks";
            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    //if (strstate.Trim() == ((int)EnumWorkState.finish).ToString())
                    //{
                    //    var dtex = DbHelperSQL.Query("update T_Bus_WorkOrder set IsExport=1 where 1=1 " + sql).Tables[0];
                    //}
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
                sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OverState", typeof(string));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("FilePath", typeof(string));
            dt.Columns.Add("Buttons", typeof(object));
            dt.Columns.Add("IsFiles", typeof(object));
            
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            foreach (DataRow dr in dt.Rows)
            {
                //获取最新交办信息
                string iszbdw = "0";
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        if (dtjb.Rows[0]["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                        #region
                        //if (state < 6 || state == 8)
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                            dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        if (state == (int)EnumWorkState.finish)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            var dttime = DateTime.Now;
                            if (!string.IsNullOrWhiteSpace(closetime)) { dttime = DateTime.Parse(closetime); }
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                            dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(dttime);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime < dttime)
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        #endregion
                    }
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }
                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    if (!string.IsNullOrEmpty(dr["F_Files"].ToString()))
                        dr["IsFiles"] = 1;
                    else
                        dr["IsFiles"] = 0;
                }
                else
                {
                    dr["IsFiles"] = 0;
                }
                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                btns.Add(ButtonGroup.query());
                dr["Buttons"] = btns;
            }
            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取二级单位处理列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetEJDWDealList(int isdc = 0)
        {

            DataTable dt = new DataTable();
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            string sql = " and F_IsDelete=0";
            string strtab = HttpUtility.UrlDecode(RequestString.GetQueryString("tab"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));

            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            #region 模块
            switch (strtab)
            {
                case "0"://待处理工单
                    int[] sts = new int[] { (int)EnumWorkState.dealing, (int)EnumWorkState.auditdelay };
                    sql += " and F_WorkState in (" + string.Join(",", sts.Select(p => p.ToString())) + ")";
                    //sql += " and F_WorkState in (4,5) ";

                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo_Next WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and "
                            + " ISNULL(F_FeedbackTime, '')='' and F_MainDeptId =" + userModel.F_DeptId + " and F_IsSure in (0,1))"; 
                    }
                    break;
                case "1"://已办理的工单 
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                        //sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_Feedback_Next WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type in (1,2) ";
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
            }
            #endregion

            #region 条件
            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }
            #region  坐席&调度员
            if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }
            if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                }
            }
            //if (strusercode.Trim() != "" && strusercode != "undefined")
            //{
            //    sql += " and F_CreateUser = '" + strusercode + "' ";
            //}
            #endregion
            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }
            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }
            if (deptid != 0)
            {
                sql += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='"+deptid+"')";
            }

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

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

            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetOverState(F_WorkOrderId) as OverState,"
            //    + "dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetWorkOrderAssign(F_WorkOrderId) as DeptName ,dbo.GetLimitTime(F_WorkOrderId) as LimitTime";
            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";
            string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks,dbo.GetDictionaryName(F_InfoConBigType) as InfoConBigTypeName";
            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
                sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OverState", typeof(string));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("FilePath", typeof(string));//语音文件路径
            dt.Columns.Add("PDState", typeof(string));//派单状态
            dt.Columns.Add("Buttons", typeof(object));//操作按钮
            dt.Columns.Add("IsFiles", typeof(object));//操作按钮
            
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            var reminds = remindBLL.GetModelList("F_State=0 and F_IsDelete=0 and F_Type =1").ToList();
            foreach (DataRow dr in dt.Rows)
            {
                //获取最新交办信息
                string iszbdw = "0";
                string ispd = "";
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        if (dtjb.Rows[0]["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();

                        var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                        dr["LimitTime"] = lt;
                        #region
                        //if (state < 6 || state == 8)
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        if (state == (int)EnumWorkState.finish)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            var dttime = DateTime.Now;
                            if (!string.IsNullOrWhiteSpace(closetime)) { dttime = DateTime.Parse(closetime); }
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(dttime);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime < dttime)
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        #endregion
                        ispd = dtjb.Rows[0]["F_IsNext"].ToString();
                        dr["PDState"] = ispd;
                    }
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }
                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    if (!string.IsNullOrEmpty(dr["F_Files"].ToString()))
                        dr["IsFiles"] = 1;
                    else
                        dr["IsFiles"] = 0;
                }
                else
                {
                    dr["IsFiles"] = 0;
                }
                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                if (Int32.Parse(strtab) < 1)
                {
                    btns = ButtonGroup.GetButtons(dr["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw, ispd);
                    #region 判断是否存在待督办
                    var recount = reminds.Where(r => r.F_WorkOrderId == dr["F_WorkOrderId"].ToString()).Count();
                    var butt = btns.Find(c => c.key == ButtonGroup.turnsee().key);
                    if (recount > 0 && butt != null)
                        btns.Remove(butt);
                    #endregion
                }
                else
                {
                    btns.Add(ButtonGroup.query());
                }
                dr["Buttons"] = btns;
            }
            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取三级单位处理列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetSJDWDealList(int isdc = 0)
        {

            DataTable dt = new DataTable();
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            string sql = " and F_IsDelete=0";
            string strtab = HttpUtility.UrlDecode(RequestString.GetQueryString("tab"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));

            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            #region 模块
            switch (strtab)
            {
                case "0"://待处理工单
                    int[] sts = new int[] { (int)EnumWorkState.dealing, (int)EnumWorkState.auditdelay };
                    sql += " and F_WorkState in (" + string.Join(",", sts.Select(p => p.ToString())) + ")";

                    if (userModel.F_RoleCode == "EJWLDW")
                    {
                        sql += " and F_MainDeptID3 ='" + userModel.F_DeptId + "' ";
                    }
                    else if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and ((F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedInfo_Next WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and "
                            + " ISNULL(F_FeedbackTime, '')='' and F_MainDeptID='"+ userModel.F_DeptId + "' and F_IsSure in (0,1)))";
                        if(userModel.F_RoleCode== "WLDW")
                        {
                            sql += " or (F_MainDeptID3 ='" + userModel.F_DeptId + "')"
                                + " or (F_MainDeptID3 in (SELECT F_DeptId FROM T_Sys_Department WITH(NOLOCK) WHERE F_State=0 AND F_PartentId=" + userModel.F_DeptId + "))";
                        }
                        sql += ")";
                    }
                    break;
                case "1"://已办理的工单 
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString())
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and F_WorkOrderID in(select F_WorkOrderID from T_Bus_Feedback_Next WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type in (1,2) ";

                    if (userModel.F_RoleCode == "EJWLDW")
                    {
                        sql += "  and F_MainDeptID3 ='" + userModel.F_DeptId + "' ";
                    }
                    else if (userModel.F_RoleCode == "WLDW")
                    {
                        sql += " and( (F_MainDeptID3 ='" + userModel.F_DeptId + "')"
                            + " or (F_MainDeptID3 in (SELECT F_DeptId FROM T_Sys_Department WITH(NOLOCK) WHERE F_State=0 AND F_PartentId=" + userModel.F_DeptId + ")) )";
                    }
                    else if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                    {
                        sql += " and F_CreateUser='" + userModel.F_UserCode + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
                    break;
            }
            #endregion

            #region 条件
            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and F_WorkOrderId like '%" + strworkid + "%' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }
            #region  坐席&调度员
            if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }
            if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                }
            }
            #endregion
            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }
            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }
            if (deptid != 0)
            {
                sql += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

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

            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";
            string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks";
            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
                sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OverState", typeof(string));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("FilePath", typeof(string));//语音文件路径
            dt.Columns.Add("PDState", typeof(string));//派单状态
            dt.Columns.Add("Buttons", typeof(object));//操作按钮
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            var reminds = remindBLL.GetModelList("F_State=0 and F_IsDelete=0 and F_Type =1").ToList();
            foreach (DataRow dr in dt.Rows)
            {
                //获取最新交办信息
                string iszbdw = "0";
                string ispd = "";
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        if (dtjb.Rows[0]["F_MainDeptId"].ToString()==userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();

                        var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                        dr["LimitTime"] = lt;
                        #region
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        if (state == (int)EnumWorkState.finish)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            var dttime = DateTime.Now;
                            if (!string.IsNullOrWhiteSpace(closetime)) { dttime = DateTime.Parse(closetime); }
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(dttime);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime < dttime)
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        #endregion
                        ispd = dtjb.Rows[0]["F_IsNext"].ToString();
                        dr["PDState"] = ispd;
                    }
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }

                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                if (Int32.Parse(strtab) < 1)
                {
                    btns = ButtonGroup.GetButtons(dr["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw, ispd);
                    #region 判断是否存在待督办
                    var recount = reminds.Where(r => r.F_WorkOrderId == dr["F_WorkOrderId"].ToString()).Count();
                    var butt = btns.Find(c => c.key == ButtonGroup.turnsee().key);
                    if (recount > 0 && butt != null)
                        btns.Remove(butt);
                    #endregion
                }
                else
                {
                    btns.Add(ButtonGroup.query());
                }
                dr["Buttons"] = btns;
            }
            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取自己提交工单
        /// </summary>
        /// <param name="isdc"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetSelfList(int isdc = 0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);

            int deptid = RequestString.GetInt("deptid", 0);
            int dealtype = RequestString.GetInt("dealtype", -1);
            int issend = RequestString.GetInt("issend", -1);
            int deptlevel = RequestString.GetInt("deptlevel", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            #region sql 语句相关处理
            if(userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG")
                sql += " and F_CreateUser ='" + userModel.F_UserCode + "' ";
            if (strstate.Trim() != "" && strstate != "undefined")
            {
                if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString())
                    sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                else
                    sql += " and F_WorkState = '" + strstate.Trim() + "' ";
            }
            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and F_WorkOrderId like '%" + strworkid + "%' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }
            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }

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

            if (deptid != 0)
            {
                sql += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
            }
            if (dealtype != -1)
            {
                sql += " and isnull(F_IsResult,0) = '" + dealtype + "' ";
            }
            if (issend != -1)
            {
                sql += " and isnull(F_IsRelease,0) = '" + issend + "' ";
            }

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

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks";
            #region 导出
            if (isdc > 0)
            {
                var top = " "; var orderby = " order by F_CreateTime";
                if (sql == " and F_IsDelete=0 ")
                {
                    top = " top 1000 "; orderby += " desc ";
                }
                //20190715调整导出字段 zhengbingbing
                //日期，工单号，诉求标题，诉求内容，承办单位，办理结果，是否满意，备注
                var dtdc = DbHelperSQL.Query(" select " + top + " F_CreateTime 日期, F_OldWorkOrderId 工单号,F_ComTitle 诉求标题,F_CusName 反映人,F_CusPhone 电话号码,F_ComContent 诉求内容,dbo.GetDictionaryName(F_Key) 主题词, "
                   + " dbo.GetDeptNames(F_MainDeptId) 承办单位, "
                   + " (select top 1 F_Situation from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId =wo.F_WorkOrderId order by F_CreateTime) 办理结果,"
                   + " (select top 1 (case F_IsSatisfie when 1 then'满意' when 0 then '不满意'when 2 then '基本满意' else '未评价' end) F_Satisfie from T_Bus_VisitResult WITH(NOLOCK) where F_State = 1 and F_IsDelete = 0 and F_WorkOrderId = wo.F_WorkOrderId order by F_Id desc) 承办单位回访结果, case F_Satisfaction when 0 then '不满意'when 1 then" +
                   "'基本满意' when 2 then '满意' else '未评价'end 郑州回访结果"
                   + " from T_Bus_WorkOrder wo WITH(NOLOCK) where 1=1 " + sql + orderby).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }
            #endregion
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
                sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件和交办超时
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("OverState", typeof(string));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("PDState", typeof(string));//派单状态
            dt.Columns.Add("FilePath", typeof(string));//语音文件路径
            dt.Columns.Add("Buttons", typeof(object));//操作按钮
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            var reminds = remindBLL.GetModelList(" F_State=0 and F_IsDelete=0 and F_Type =1").ToList();
            foreach (DataRow dr in dt.Rows)
            {
                string iszbdw = "0";
                string ispd = "";

                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    //获取最新交办信息
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        if (dr["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dr["F_MainDeptId"].ToString() + "')");
                        if (dr["F_OtherDeptIds"] != null && dr["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dr["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                        var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                        dr["LimitTime"] = lt;
                        #region 超时时限
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                            ispd = dtjb.Rows[0]["F_IsNext"] != null ? dtjb.Rows[0]["F_IsNext"].ToString() : "";
                            dr["PDState"] = ispd;
                        }
                        if (state == (int)EnumWorkState.finish)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            var dttime = DateTime.Now;
                            if (!string.IsNullOrWhiteSpace(closetime)) { dttime = DateTime.Parse(closetime); }
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(dttime);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime < dttime)
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        #endregion
                    }
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }

                var buttons = ButtonGroup.GetButtons(dr["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_IsResult"].ToString(), iszbdw, ispd);
                #region 判断是否存在待督办
                var recount = reminds.Where(r => r.F_WorkOrderId.Equals(dr["F_WorkOrderId"].ToString())).Count();
                var butt = buttons.Find(c => c.key == ButtonGroup.turnsee().key);
                if (recount > 0 && butt != null)
                    buttons.Remove(butt);
                #endregion
                dr["Buttons"] = buttons;
            }
            #endregion

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

        /// <summary>
        /// 获取逾期未回复工单列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetTimeOutList(int isdc = 0)
        {
            DataTable dt = new DataTable();

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            string sql = " and F_IsDelete=0";
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));

            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            if (userModel.F_RoleCode == "ZXHWY")
            {
                sql += " and F_CreateUser = '" + userModel.F_UserCode + "' ";
            }
            else
            {
                #region  坐席&调度员
                if (strusercode.Trim() != "" && strusercode != "undefined")
                {//坐席
                    var usercode = strusercode.Trim().Split(',');
                    var newusercode = "";
                    foreach (var item in usercode)
                    {
                        if (!string.IsNullOrWhiteSpace(item.Trim()))
                            newusercode += "'" + item + "',";
                    }
                    newusercode = newusercode.Trim(',');
                    if (newusercode.Trim() != "" && newusercode != "undefined")
                    {
                        sql += " and F_CreateUser in (" + newusercode + ") ";
                    }
                }
                if (strddusercode.Trim() != "" && strddusercode != "undefined")
                {//调度员
                    var ddusercode = strddusercode.Trim().Split(',');
                    var newusercode = "";
                    foreach (var item in ddusercode)
                    {
                        if (!string.IsNullOrWhiteSpace(item.Trim()))
                            newusercode += "'" + item + "',";
                    }
                    newusercode = newusercode.Trim(',');
                    if (newusercode.Trim() != "" && newusercode != "undefined")
                    {
                        sql += " and F_AssignUser in(" + newusercode + ") ";
                    }
                }
                //if (strusercode.Trim() != "" && strusercode != "undefined")
                //{
                //    sql += " and F_CreateUser = '" + strusercode + "' ";
                //}
                #endregion
            }

            string sqlwhere = "";string sqlwhere1 = "";
            sqlwhere += " and ( F_WorkOrderId in (select F_WorkOrderId  from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_LimitTime<getdate() and isnull(F_FeedbackTime,'')='' and F_IsSure in (0,1) ";

            if (userModel.F_RoleCode == "WLDW")
            {
                sqlwhere += " and  F_MainDeptId = '" + userModel.F_DeptId + "') or F_WorkOrderId in (select F_WorkOrderId from T_Bus_AssignedItemInfo WITH(NOLOCK) "
                    + " where F_State=1 and F_IsDelete=0 and F_LimitTime<getdate() and ISNULL(F_FeedbackTime, '')='' and  F_DeptId = '" + userModel.F_DeptId + "' ";
                sqlwhere1 += " and  F_MainDeptId = '" + userModel.F_DeptId + "'";
            }
            else if (deptid != 0)
            {
                sqlwhere += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
                sqlwhere1 += " and  (F_MainDeptId = '" + deptid + "' or F_MainDeptID3='" + deptid + "')";
            }

            if (userModel.F_RoleCode == "ZXLD")
            {
                sqlwhere += " and  F_CreateUser = '" + userModel.F_UserCode + "' ";
                sqlwhere1 += " and  F_CreateUser = '" + userModel.F_UserCode + "'";
            }

            sqlwhere += "))";

            if (strstate.Trim() != "" && strstate != "undefined")
            {
                if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString() )
                    sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                else
                    sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                if (strstate.Trim() == ((int)EnumWorkState.finish).ToString())
                    sql += " and F_LimitTime<F_DealTime " + sqlwhere1;
                else
                    sql += sqlwhere;
            }
            else
            {
                int[] sts = new int[] { (int)EnumWorkState.receive, (int)EnumWorkState.dealing, (int)EnumWorkState.reload };
                sql += " and F_WorkState in (" + string.Join(",", sts.Select(p => p.ToString())) + ")";
                sql += sqlwhere;
                //sql += " and F_WorkState in (2,4,8)";
            }
            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }

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

            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }

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

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

            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName ";
            string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks,dbo.GetDictionaryName(F_InfoConBigType) as InfoConBigTypeName";
            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
                sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("OverState", typeof(string));//超时状态
            dt.Columns.Add("LimitTime", typeof(string));//限制时间
            dt.Columns.Add("GapTime", typeof(string));//时间差
            dt.Columns.Add("FilePath", typeof(string));
            dt.Columns.Add("Buttons", typeof(object));
            dt.Columns.Add("IsFiles", typeof(object));
            
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            var configcs = configBll.GetModelList(" F_ParamCode='CSYJ' ").FirstOrDefault();
            foreach (DataRow dr in dt.Rows)
            {
                //获取最新交办信息
                string iszbdw = "0";
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        if (dtjb.Rows[0]["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                        
                        #region 时限
                        //if (state < 6 || state == 8)
                        if (state < (int)EnumWorkState.dealed || state == (int)EnumWorkState.reload)
                        {
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                            dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(DateTime.Now);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime > DateTime.Now)
                                {
                                    if (configcs != null)
                                    {
                                        int cs = Int32.Parse(configcs.F_ParamValue);
                                        if (ts.TotalHours > cs)
                                        {
                                            dr["OverState"] = 1;
                                        }
                                        else
                                        {
                                            dr["OverState"] = 2;
                                        }
                                    }
                                    dr["GapTime"] = "剩余" + gshsj;
                                }
                                else
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }
                        if (state == (int)EnumWorkState.finish)
                        {
                            var closetime = dr["F_DealTime"].ToString();//关闭工单时间
                            var dttime = DateTime.Now;
                            if (!string.IsNullOrWhiteSpace(closetime)) { dttime = DateTime.Parse(closetime); }
                            var lt = dtjb.Rows[0]["F_LimitTime"].ToString();//限制时间
                            dr["LimitTime"] = lt;
                            if (!string.IsNullOrWhiteSpace(lt))
                            {
                                var ltime = DateTime.Parse(lt);
                                TimeSpan ts = ltime.Subtract(dttime);
                                int tss = Int32.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                if (tss < 0) { tss = -tss; }
                                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
                                if (ltime < dttime)
                                {
                                    dr["OverState"] = 3;
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }
                        }

                        #endregion
                    }
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }
                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    if (!string.IsNullOrEmpty(dr["F_Files"].ToString()))
                        dr["IsFiles"] = 1;
                    else
                        dr["IsFiles"] = 0;
                }
                else
                {
                    dr["IsFiles"] = 0;
                }
                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                btns.Add(ButtonGroup.query());
                dr["Buttons"] = btns;
            }
            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取媒体工单列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetMediaList(int isdc = 0)
        {
            DataTable dt = new DataTable();

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            string sql = " and F_IsDelete=0";
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            sql += " and isnull(F_IsRelease,0) =1 ";

            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }
            #region  坐席&调度员
            if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }
            if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                }
            }
            //if (strusercode.Trim() != "" && strusercode != "undefined")
            //{
            //    sql += " and F_CreateUser = '" + strusercode + "' ";
            //}
            #endregion

            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }
            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }
            if (deptid != 0)
            {
                string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                sql += " and F_WorkOrderID in(" + sqlwhere + ")";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }

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

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

            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,"
            //        + "dbo.GetDictionaryName(F_InfoSource) as SourceName ";
            string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks,dbo.GetDictionaryName(F_InfoConBigType) as InfoConBigTypeName";
            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
                sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("IsReturnMedia", typeof(string));

            dt.Columns.Add("Buttons", typeof(object));

            int IsReturnMedia = 0;
            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "ZXLDGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                IsReturnMedia = 1;
            }
            foreach (DataRow dr in dt.Rows)
            {
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    //获取最新交办信息
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                        //int did = Int32.Parse(dtjb.Rows[0]["F_MainDeptId"].ToString());
                        //var deptinfo = new BLL.T_Sys_Department().GetModel(did);
                        //if (deptinfo != null)
                        //{
                        //    dr["DeptName"] = deptinfo.F_DeptName;//交办单位
                        //}

                        //if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        //{
                        //    string[] strids = dtjb.Rows[0]["F_OtherDeptIds"].ToString().Split(',');
                        //    string dns = string.Empty;
                        //    foreach (string strid in strids)
                        //    {
                        //        var dinfo = new BLL.T_Sys_Department().GetModel(Int32.Parse(strid));
                        //        if (dinfo != null)
                        //        {
                        //            if (string.IsNullOrEmpty(dns))
                        //            {
                        //                dns = dinfo.F_DeptName;//交办单位
                        //            }
                        //            else
                        //            {
                        //                dns += "," + dinfo.F_DeptName;//交办单位
                        //            }
                        //        }
                        //    }
                        //    dr["OtherDeptName"] = dns;
                        //}
                    }
                }
                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                btns.Add(ButtonGroup.query());
                dr["Buttons"] = btns;

                dr["IsReturnMedia"] = IsReturnMedia;
            }

            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }



        ///// <summary>
        ///// 获取通报工单列表
        ///// </summary>
        ///// <returns></returns>
        //[Authority]
        //public ActionResult GetNoticeList(int isdc = 0)
        //{
        //    DataTable dt = new DataTable();

        //    int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

        //    string sql = " and F_IsDelete=0 and isnull(F_IsNotice,0) =1";
        //    string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
        //    string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
        //    string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
        //    string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
        //    string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
        //    string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
        //    string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));

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

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

        //    if (strworkid.Trim() != "" && strworkid != "undefined")
        //    {
        //        sql += " and F_WorkOrderId like '%" + strworkid + "%' ";
        //    }
        //    if (strname.Trim() != "" && strname != "undefined")
        //    {
        //        sql += " and F_CusName like '%" + strname + "%' ";
        //    }
        //    if (strtel.Trim() != "" && strtel != "undefined")
        //    {
        //        sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
        //    }
        //    if (strkey.Trim() != "" && strkey != "undefined")
        //    {
        //        sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
        //    }
        //    if (strusercode.Trim() != "" && strusercode != "undefined")
        //    {
        //        sql += " and F_CreateUser = '" + strusercode + "' ";
        //    }

        //    if (source != 0)
        //    {
        //        sql += " and F_InfoSource = '" + source + "' ";
        //    }
        //    if (keyid != 0)
        //    {
        //        sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
        //    }
        //    if (type != 0)
        //    {
        //        sql += " and F_InfoType = '" + type + "' ";
        //    }
        //    if (bigtype != 0)
        //    {
        //        sql += " and F_InfoConBigType = '" + bigtype + "' ";
        //    }
        //    if (smalltype != 0)
        //    {
        //        sql += " and F_InfoConSmallType = '" + smalltype + "' ";
        //    }
        //    if (sourcearea != 0)
        //    {
        //        sql += " and F_SourceArea = '" + sourcearea + "' ";
        //    }
        //    if (deptid != 0)
        //    {
        //        string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
        //        sql += " and F_WorkOrderID in(" + sqlwhere + ")";
        //    }
        //    if (strstarttime.Trim() != "" && strstarttime != "undefined")
        //    {
        //        sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
        //    }
        //    if (strendtime.Trim() != "" && strendtime != "undefined")
        //    {
        //        sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
        //    }

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

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

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

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

        //    int recordCount = 0;
        //    dt = BLL.PagerBLL.GetListPager(
        //        "T_Bus_WorkOrder",
        //        "F_WorkOrderId",
        //        cols,
        //        sql,
        //        "ORDER BY F_CreateTime DESC",
        //        pagesize,
        //        pageindex,
        //        true,
        //        out recordCount);

        //    #region 声音文件
        //    dt.Columns.Add("DeptName", typeof(string));//交办单位
        //    dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
        //    dt.Columns.Add("NoticeDeptName", typeof(string));//通报单位
        //    dt.Columns.Add("NoticeReson", typeof(string));//通报原因
        //    dt.Columns.Add("IsReturnNotice", typeof(string));
        //    dt.Columns.Add("FilePath", typeof(string));
        //    dt.Columns.Add("Buttons", typeof(object));
        //    var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
        //    var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
        //    int IsReturnNotice = 0;
        //    if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" ||userModel.F_RoleCode == "ZXLDGLY" || userModel.F_RoleCode == "GLY")
        //    {
        //        IsReturnNotice = 1;
        //    }
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        //获取最新交办信息
        //        //string iszbdw = "0";
        //        string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
        //        var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
        //        if (dtjb.Rows.Count > 0)
        //        {
        //            //if (dtjb.Rows[0]["F_MainDeptId"].ToString() == userModel.F_DeptId.ToString()) { iszbdw = "1"; }
        //            dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
        //            if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
        //            {
        //                dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
        //            }
        //            //int did = Int32.Parse(dtjb.Rows[0]["F_MainDeptId"].ToString());
        //            //var deptinfo = new BLL.T_Sys_Department().GetModel(did);
        //            //if (deptinfo != null)
        //            //{
        //            //    //if (did == userModel.F_DeptId) { iszbdw = "1"; }
        //            //    dr["DeptName"] = deptinfo.F_DeptName;//交办单位
        //            //}

        //            //if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
        //            //{
        //            //    string[] strids = dtjb.Rows[0]["F_OtherDeptIds"].ToString().Split(',');
        //            //    string dns = string.Empty;
        //            //    foreach (string strid in strids)
        //            //    {
        //            //        var dinfo = new BLL.T_Sys_Department().GetModel(Int32.Parse(strid));
        //            //        if (dinfo != null)
        //            //        {
        //            //            if (string.IsNullOrEmpty(dns))
        //            //            {
        //            //                dns = dinfo.F_DeptName;//交办单位
        //            //            }
        //            //            else
        //            //            {
        //            //                dns += "," + dinfo.F_DeptName;//交办单位
        //            //            }
        //            //        }
        //            //    }
        //            //    dr["OtherDeptName"] = dns;
        //            //}
        //        }
        //        //获取最新通报信息
        //        string sqltb = "SELECT TOP 1 * FROM T_Bus_NoticeCriticism WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0  ORDER BY F_Id DESC";
        //        var dttb = DbHelperSQL.Query(sqltb).Tables[0];
        //        if (dttb.Rows.Count > 0)
        //        {
        //            if (dttb.Rows[0]["F_DeptIds"] != null && dttb.Rows[0]["F_DeptIds"].ToString() != "")
        //            {
        //                dr["NoticeDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dttb.Rows[0]["F_DeptIds"].ToString() + "')");
        //            }

        //            dr["NoticeReson"] = dttb.Rows[0]["F_Content"] != null? dttb.Rows[0]["F_Content"].ToString():"";
        //        }
        //        if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
        //        {
        //            dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
        //        }
        //        else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
        //        {
        //            dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
        //        }
        //        List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
        //        btns.Add(ButtonGroup.query());
        //        dr["Buttons"] = btns;

        //        dr["IsReturnNotice"] = IsReturnNotice;
        //    }

        //    #endregion

        //    var obj = new
        //    {
        //        state = "success",
        //        message = "成功",
        //        rows = dt,
        //        total = recordCount
        //    };

        //    return Content(obj.ToJson());
        //}

        /// <summary>
        /// 获取通报工单列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetNoticeList(string[] usercode, string[] ddusercode, int isdc = 0)//
        {
            DataTable dt = new DataTable();
            //int userId = 8000;
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            string sql = " and F_IsDelete=0 ";
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            //string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            //string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }
            #region  坐席&调度员
            /*if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }*/
            #region 
            if (usercode != null && usercode.Length > 0)
            {
                var newusercode = "";
                //string codes = "";
                for (int i = 0; i < usercode.Length; i++)
                {
                    if (usercode[i] != "")
                    {
                        newusercode += "'" + usercode[i] + "',";
                    }
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }
            if (ddusercode != null && ddusercode.Length > 0)
            {
                var newusercode = "";
                //string codes = "";
                for (int i = 0; i < ddusercode.Length; i++)
                {
                    if (ddusercode[i] != "")
                    {
                        newusercode += "'" + ddusercode[i] + "',";
                    }
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in (" + newusercode + ") ";
                }
            }
            #endregion
            /*if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                }
            }*/
            //if (strusercode.Trim() != "" && strusercode != "undefined")
            //{
            //    sql += " and F_CreateUser = '" + strusercode + "' ";
            //}
            #endregion

            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }
            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }
            if (deptid != 0)
            {
                string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                sql += " and F_WorkOrderID in(" + sqlwhere + ")";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }

            if (userModel.F_RoleCode == "WLDW")
            {
                string sqlwhere = "select F_WorkOrderID from T_Bus_NoticeCriticism WITH(NOLOCK) where ','+F_DeptIds+',' like  '%," + userModel.F_DeptId + ",%' and F_State=1 and F_IsDelete=0 ";
                sql += " and F_WorkOrderID in(" + sqlwhere + ")";
            }
            else
            {
                sql += " and F_WorkOrderID in(select F_WorkOrderID from T_Bus_NoticeCriticism WITH(NOLOCK) where F_State=1 and F_IsDelete=0) ";
            }

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

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

            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";
            string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks";
            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
                sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("NoticeDeptName", typeof(string));//通报单位
            dt.Columns.Add("NoticeReson", typeof(string));//通报原因
            dt.Columns.Add("IsReturnNotice", typeof(string));
            dt.Columns.Add("FilePath", typeof(string));
            dt.Columns.Add("Buttons", typeof(object));
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            int IsReturnNotice = 0;
            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "ZXLDGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                IsReturnNotice = 1;
            }
            foreach (DataRow dr in dt.Rows)
            {
                //获取最新交办信息
                //string iszbdw = "0";
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                    }
                }
                //获取最新通报信息
                string sqltb = "SELECT TOP 1 * FROM T_Bus_NoticeCriticism WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0  ORDER BY F_Id DESC";
                var dttb = DbHelperSQL.Query(sqltb).Tables[0];
                if (dttb.Rows.Count > 0)
                {
                    if (dttb.Rows[0]["F_DeptIds"] != null && dttb.Rows[0]["F_DeptIds"].ToString() != "")
                    {
                        dr["NoticeDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dttb.Rows[0]["F_DeptIds"].ToString() + "')");
                    }

                    dr["NoticeReson"] = dttb.Rows[0]["F_Content"] != null ? dttb.Rows[0]["F_Content"].ToString() : "";
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }
                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                btns.Add(ButtonGroup.query());
                dr["Buttons"] = btns;

                dr["IsReturnNotice"] = IsReturnNotice;
            }

            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        public ActionResult GetNoticeListOLD(int isdc = 0)
        {
            DataTable dt = new DataTable();

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            string sql = " and F_IsDelete=0 ";
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkid = HttpUtility.UrlDecode(RequestString.GetQueryString("workid"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string strddusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("ddusercode"));//调度员
            int source = RequestString.GetInt("source", 0);
            int keyid = RequestString.GetInt("keyid", 0);
            int type = RequestString.GetInt("type", 0);
            int bigtype = RequestString.GetInt("bigtype", 0);
            int smalltype = RequestString.GetInt("smalltype", 0);
            int sourcearea = RequestString.GetInt("sourcearea", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            int timesort = RequestString.GetInt("timesort", -1);
            string sort = "ORDER BY F_CreateTime ASC";
            if (timesort == 0)
                sort = "ORDER BY LimitTime ASC";
            else if (timesort == 1)
                sort = "ORDER BY F_CreateTime DESC";
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            if (strworkid.Trim() != "" && strworkid != "undefined")
            {
                sql += " and (F_WorkOrderId like '%" + strworkid + "%'or F_OldWorkOrderId like  '%" + strworkid + "%')";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_CusName like '%" + strname + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_CusPhone like '%" + strtel + "%' or F_ConPhone like '%" + strtel + "%') ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_ComTitle like '%" + strkey + "%' or F_ComContent like '%" + strkey + "%') ";
            }
            #region  坐席&调度员
            if (strusercode.Trim() != "" && strusercode != "undefined")
            {//坐席
                var usercode = strusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in usercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_CreateUser in (" + newusercode + ") ";
                }
            }
            if (strddusercode.Trim() != "" && strddusercode != "undefined")
            {//调度员
                var ddusercode = strddusercode.Trim().Split(',');
                var newusercode = "";
                foreach (var item in ddusercode)
                {
                    if (!string.IsNullOrWhiteSpace(item.Trim()))
                        newusercode += "'" + item + "',";
                }
                newusercode = newusercode.Trim(',');
                if (newusercode.Trim() != "" && newusercode != "undefined")
                {
                    sql += " and F_AssignUser in(" + newusercode + ") ";
                }
            }
            //if (strusercode.Trim() != "" && strusercode != "undefined")
            //{
            //    sql += " and F_CreateUser = '" + strusercode + "' ";
            //}
            #endregion

            if (source != 0)
            {
                sql += " and F_InfoSource = '" + source + "' ";
            }
            if (keyid != 0)
            {
                sql += " and ','+F_Key+',' like '%," + keyid + ",%' ";
            }
            if (type != 0)
            {
                sql += " and F_InfoType = '" + type + "' ";
            }
            if (bigtype != 0)
            {
                sql += " and F_InfoConBigType = '" + bigtype + "' ";
            }
            if (smalltype != 0)
            {
                sql += " and F_InfoConSmallType = '" + smalltype + "' ";
            }
            if (sourcearea != 0)
            {
                sql += " and F_SourceArea = '" + sourcearea + "' ";
            }
            if (deptid != 0)
            {
                string sqlwhere = "select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_MainDeptId = '" + deptid + "' and F_IsSure in (0,1) and F_State=1 and F_IsDelete=0 ";
                sql += " and F_WorkOrderID in(" + sqlwhere + ")";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }

            if (userModel.F_RoleCode == "WLDW")
            {
                string sqlwhere = "select F_WorkOrderID from T_Bus_NoticeCriticism WITH(NOLOCK) where ','+F_DeptIds+',' like  '%," + userModel.F_DeptId + ",%' and F_State=1 and F_IsDelete=0 ";
                sql += " and F_WorkOrderID in(" + sqlwhere + ")";
            }
            else
            {
                sql += " and F_WorkOrderID in(select F_WorkOrderID from T_Bus_NoticeCriticism WITH(NOLOCK) where F_State=1 and F_IsDelete=0) ";
            }

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

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

            //string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName";
            string cols = "F_OldWorkOrderId,F_WorkOrderId,F_ComTitle,F_WorkState,F_MainDeptId,F_OtherDeptIds,F_DealTime,F_LeaveRecordId,F_CallRecordId,F_IsResult,F_IsProtect,F_IsReturn,F_CreateTime,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName,dbo.GetDictionaryName(F_InfoSource) as SourceName,F_Files,F_WorkRemarks";
            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Bus_WorkOrder WITH(NOLOCK) where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("工单列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Bus_WorkOrder WITH(NOLOCK)",
                "F_WorkOrderId",
                cols,
                sql,
               sort ,
                pagesize,
                pageindex,
                true,
                out recordCount);

            #region 声音文件
            dt.Columns.Add("DeptName", typeof(string));//交办单位
            dt.Columns.Add("OtherDeptName", typeof(string));//协办单位
            dt.Columns.Add("AssignTime", typeof(string));//交办时间
            dt.Columns.Add("NoticeDeptName", typeof(string));//通报单位
            dt.Columns.Add("NoticeReson", typeof(string));//通报原因
            dt.Columns.Add("IsReturnNotice", typeof(string));
            dt.Columns.Add("FilePath", typeof(string));
            dt.Columns.Add("Buttons", typeof(object));
            var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
            var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
            int IsReturnNotice = 0;
            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "ZXLDGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                IsReturnNotice = 1;
            }
            foreach (DataRow dr in dt.Rows)
            {
                //获取最新交办信息
                //string iszbdw = "0";
                int state = Int32.Parse(dr["F_WorkState"].ToString());
                if (state > 1)
                {
                    string sqljb = "SELECT TOP 1 * FROM T_Bus_AssignedInfo WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0 and F_IsSure<>3   ORDER BY F_Id DESC";
                    var dtjb = DbHelperSQL.Query(sqljb).Tables[0];
                    if (dtjb.Rows.Count > 0)
                    {
                        dr["DeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_MainDeptId"].ToString() + "')");
                        if (dtjb.Rows[0]["F_OtherDeptIds"] != null && dtjb.Rows[0]["F_OtherDeptIds"].ToString() != "")
                        {
                            dr["OtherDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dtjb.Rows[0]["F_OtherDeptIds"].ToString() + "')");
                        }
                        dr["AssignTime"] = dtjb.Rows[0]["F_CreateTime"].ToString();
                    }
                }
                //获取最新通报信息
                string sqltb = "SELECT TOP 1 * FROM T_Bus_NoticeCriticism WITH(NOLOCK) WHERE F_WorkOrderId='" + dr["F_WorkOrderId"].ToString() + "' and F_State=1 and F_IsDelete=0  ORDER BY F_Id DESC";
                var dttb = DbHelperSQL.Query(sqltb).Tables[0];
                if (dttb.Rows.Count > 0)
                {
                    if (dttb.Rows[0]["F_DeptIds"] != null && dttb.Rows[0]["F_DeptIds"].ToString() != "")
                    {
                        dr["NoticeDeptName"] = DbHelperSQL.GetSingle(" select dbo.GetDeptNames('" + dttb.Rows[0]["F_DeptIds"].ToString() + "')");
                    }

                    dr["NoticeReson"] = dttb.Rows[0]["F_Content"] != null ? dttb.Rows[0]["F_Content"].ToString() : "";
                }
                if (dr["F_LeaveRecordId"] != null && dr["F_LeaveRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetLeavePath(dr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                }
                else if (dr["F_CallRecordId"] != null && dr["F_CallRecordId"].ToString() != "")
                {
                    dr["FilePath"] = GetCallPath(dr["F_CallRecordId"].ToString(), config.F_ParamValue);
                }
                List<ButtonGroup.button> btns = new List<ButtonGroup.button>();
                btns.Add(ButtonGroup.query());
                dr["Buttons"] = btns;

                dr["IsReturnNotice"] = IsReturnNotice;
            }

            #endregion

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        public ActionResult GetWorkorderSimp()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
            if (!string.IsNullOrEmpty(strworkorderid))
            {
                string sql = "select F_WorkOrderId,F_CreateTime,F_ComTitle,F_Result,dbo.GetDictionaryName(F_InfoSource) as SourceName,dbo.GetDeptName(F_MainDeptId) deptname "
                    + " from T_Bus_WorkOrder WITH(NOLOCK) where F_WorkOrderId ='" + strworkorderid + "'";
                var dt = DbHelperSQL.Query(sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    return Success("成功", dt);
                }
                return Error("获取失败");
            }
            return Error("参数错误");
        }
        /// <summary>
        /// 获取工单信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
            

            //int type = RequestString.GetInt("type", 0);//0基本信息1监察意见2领导批示3办理情况4回访信息5督办信息6办理过程
            if (!string.IsNullOrEmpty(strworkorderid))
            {
                string sql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDictionaryName(F_InfoType) as TypeName1,"
                    + "dbo.GetDictionaryName(F_InfoConBigType) as infopropertyname,   "
                    //dbo.GetDictionaryName(F_InfoConSmallType) as TypeName3,"
                    //+ "dbo.GetWorkOrderAssign(F_WorkOrderId) as DeptName,dbo.GetDictionaryName(F_InfoSource) as SourceName ,"
                    + "dbo.GetAreaName(F_SourceArea) as AreaName,  (case when F_IsResult =1 then dbo.[GetDeptNameByUserCode](F_CreateUser) else  dbo.GetDeptNames(F_MainDeptId)   end) deptname ," + "F_DeptIdIsSms = (select F_IsSms  from T_Sys_Department where F_DeptId =a.F_MainDeptId)"
                      + " from T_Bus_WorkOrder a WITH(NOLOCK) where F_WorkOrderId ='" + strworkorderid + "'" ;
                   
                var dt = DbHelperSQL.Query(sql).Tables[0];
                

                if (dt.Rows.Count > 0)
                {
                    #region 结果汇总
                    //if (dt.Rows[0]["F_IsResult"] != null && dt.Rows[0]["F_IsResult"].ToString() == "0"){
                    //    string result = "";
                    //    string createtime = DateTime.Parse(dt.Rows[0]["F_CreateTime"].ToString()).ToString("yyyy年MM月dd日");
                    //    string deptname = dt.Rows[0]["deptname"].ToString();
                    //    string sourcename = dt.Rows[0]["SourceName"].ToString();
                    //    string title = dt.Rows[0]["F_ComTitle"].ToString();
                    //    string conresult= dt.Rows[0]["F_Result"].ToString();

                    //    var blmodel = new BLL.T_Bus_Feedback().GetModelList("F_State=1 and F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime desc").FirstOrDefault();
                    //    if (blmodel != null)
                    //    {
                    //        string bljg = blmodel.F_IsProResult != null && blmodel.F_IsProResult == 1 ? "已办理" : "未办理";
                    //        string hfcont = "";
                    //        if (blmodel.F_IsProResult == 1)
                    //        {
                    //            hfcont = "";
                    //            if (blmodel.F_IsProtect == 0)
                    //            {
                    //                string blmy = "未回访";
                    //                switch (blmodel.F_IsSatisfied)
                    //                {
                    //                    case 1:
                    //                        blmy = "满意";
                    //                        break;
                    //                    case 2:
                    //                        blmy = "基本满意";
                    //                        break;
                    //                    case 3:
                    //                        blmy = "不满意";
                    //                        break;
                    //                }
                    //                string connttime = "";
                    //                if (blmodel.F_ConnectTime != null)
                    //                    connttime = "在" + blmodel.F_ConnectTime.Value.ToString("yyyy年MM月dd日HH时mm分");
                    //                hfcont = " 回访：承办人  用" + blmodel.F_ConnectMode + connttime + "对反应人进行了回复，反应人对结果表示" + blmy + "。";
                    //            }
                    //        }
                    //        else if (blmodel.F_IsProResult == 2)
                    //        {
                    //            hfcont = " 处理方案/进程：" + blmodel.F_ProSituation;
                    //        }
                    //        result = createtime + "，" + deptname + "接到" + sourcename + "工单（编号：" + strworkorderid + "）反映" + title + "，经落实，具体情况回复如下：" + conresult + " 办理结果：" + bljg + " 承办人：" + blmodel.F_DealUser + " 职务：" + blmodel.F_Duties + " 联系电话：" + blmodel.F_DealUserContact + hfcont;

                    //        dt.Rows[0]["F_Result"] = result;
                    //    }
                    //}
                    #endregion
                    if (dt.Rows[0]["F_IsProtect"] != null && (userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "EJWLDW"))
                    {
                        string isp = dt.Rows[0]["F_IsProtect"].ToString();
                        if (isp == "1")
                        {
                            dt.Rows[0]["F_CusName"] = "";
                            dt.Rows[0]["F_CusPhone"] = "";
                            dt.Rows[0]["F_ConPhone"] = "";
                        }
                    }
                    if (dt.Rows[0]["F_ComContent"] != null&&!string .IsNullOrEmpty ( dt.Rows[0]["F_ComContent"].ToString ()))
                    {
                        dt.Rows[0]["F_ComContent"] = Regex.Replace(dt.Rows[0]["F_ComContent"].ToString(), "<[^>]+>", "");
                    }




                    if (userModel.F_RoleCode == "WLDW")
                    {
                        dt.Rows[0]["F_WorkRemarks"] = "";
                    }
                        var configly = configBll.GetModelList(" F_ParamCode='PlayLeaveVoice' ").FirstOrDefault();
                    var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
                    var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

                    //string jcsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_DeptId) as DeptName "
                    //                + "from T_Bus_RemindRecord WITH(NOLOCK) where F_Type=2 and F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "'";
                    string jcsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_DeptId) as DeptName "
                                    + "from T_Bus_RemindRecord WITH(NOLOCK) where F_Type=2 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";
                    string dbsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_DeptId) as DeptName "
                                    + "from T_Bus_RemindRecord WITH(NOLOCK) where F_Type=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";
                    string pssql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_SubmitSuper WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type=1 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";
                    string zssql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_SubmitSuper WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type=2 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";
                    string htsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_SubmitSuper WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_Type=3 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";

                    string jbsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_MainDeptId) as DeptName,dbo.GetDeptNames(F_OtherDeptIds) as OtherDeptName,dbo.GetDictionaryNames(F_StandardIDS) as StandardNames  "
                                    + "from T_Bus_AssignedInfo WITH(NOLOCK) where  F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";

                    string ejjbsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_MainDeptId) as DeptName,dbo.GetDeptNames(F_OtherDeptIds) as OtherDeptName "
                                    + "from T_Bus_AssignedInfo_Next WITH(NOLOCK) where  F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";
                    string thsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_CreateDeptId) as DeptName "
                                    + "from T_Bus_Feedback WITH(NOLOCK) where F_State=1 and F_Type=3 and F_IsDelete=0 and  F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";
                    string yssql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_DelayTime WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";
                    string blsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_CreateDeptId) as DeptName "
                                    + "from T_Bus_Feedback WITH(NOLOCK) where  F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";
                    string ejblsql = "select *,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_CreateDeptId) as DeptName "
                                    + "from T_Bus_Feedback_Next WITH(NOLOCK) where  F_Type!=3 and F_IsDelete=0 and  F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";
                    string hfsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_VisitResult WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime ";
                    string gcsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_Operation WITH(NOLOCK) where F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime ";
                    string cbsql = "select *,dbo.GetUserName(F_CreateUser) as UserName "
                                    + "from T_Bus_Additional WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_WorkOrderId ='" + strworkorderid + "' order by F_CreateTime";


                    #region 声音文件
                    dt.Columns.Add("FilePath", typeof(string));

                    if (dt.Rows[0]["F_LeaveRecordId"] != null)
                    {
                        dt.Rows[0]["FilePath"] = GetLeavePath(dt.Rows[0]["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                    }
                    else if (dt.Rows[0]["F_CallRecordId"] != null)
                    {
                        dt.Rows[0]["FilePath"] = GetCallPath(dt.Rows[0]["F_CallRecordId"].ToString(), config.F_ParamValue);
                    }
                    #endregion

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

                    #endregion

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

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

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

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

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

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

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

                    #region 延时信息
                    var ysdt = DbHelperSQL.Query(yssql).Tables[0];
                    if (configfj != null)
                    {
                        ysdt = BindFileData(ysdt, configfj.F_ParamValue);
                    }
                    #endregion

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

                    #region 回访信息
                    var hfdt = DbHelperSQL.Query(hfsql).Tables[0];
                    hfdt.Columns.Add("FilePath", typeof(string));
                    foreach (DataRow bldr in hfdt.Rows)
                    {
                        if (bldr["F_CallRecordId"] != null && config != null)
                        {
                            bldr["FilePath"] = GetCallPath(bldr["F_CallRecordId"].ToString(), config.F_ParamValue);
                        }
                    }
                    #endregion

                    #region 市民催单
                    var cbdt = DbHelperSQL.Query(cbsql).Tables[0];
                    cbdt.Columns.Add("FilePath", typeof(string));
                    foreach (DataRow bldr in cbdt.Rows)
                    {
                        if (bldr["F_CallRecordId"] != null && config != null)
                        {
                            bldr["FilePath"] = GetCallPath(bldr["F_CallRecordId"].ToString(), config.F_ParamValue);
                        }
                    }
                    #endregion

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

                            if (bldr["F_LeaveRecordId"] != null && configly != null)
                            {
                                bldr["FilePath"] = GetLeavePath(bldr["F_LeaveRecordId"].ToString(), config.F_ParamValue);
                            }
                            else if (bldr["F_CallRecordId"] != null && config != null)
                            {
                                bldr["FilePath"] = GetCallPath(bldr["F_CallRecordId"].ToString(), config.F_ParamValue);
                            }
                            if (bldr["F_Message"] != null)
                            {
                                var F_Message = bldr["F_Message"].ToString().Split(')');
                                var a = F_Message.Count();
                                if (F_Message[0] != "" && bldr["F_Message"].ToString().Contains(')'))
                                {
                                    string str = bldr["F_Message"].ToString().Substring(0, F_Message[0].Length + 1);
                                    bldr["czusername"] = str;
                                    bldr["msginfos"] = F_Message[1].ToString();
                                }
                                else {
                                    bldr["czusername"] = "";
                                    bldr["msginfos"] = F_Message[0].ToString();
                                }
                                
                            }
                        }
                    }
                    #endregion

                    #region 操作按钮
                    var btns = new List<ButtonGroup.button>();
                    
                    if (jbdt.Rows.Count > 0)
                    {

                        var jbzx = jbdt.Rows[jbdt.Rows.Count - 1];

                        string ispd = jbzx["F_IsNext"].ToString();
                        string iszbdw = "0";
                        string fmd = jbzx["F_MainDeptId"].ToString();
                        string fod = jbzx["F_OtherDeptIds"] == null ? "" : jbzx["F_OtherDeptIds"].ToString();
                        if (fmd == userModel.F_DeptId.ToString())
                        { iszbdw = "1"; }
                        else if (fod != "" && fod.Split(',').Contains(userModel.F_DeptId.ToString()))
                        {
                            iszbdw = "2";


                            
                        }
                        if (!(userModel.F_RoleCode == "WLDW" && iszbdw == "0"))
                        {
                            btns = ButtonGroup.GetButtons(dt.Rows[0]["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dt.Rows[0]["F_IsResult"].ToString(), iszbdw, ispd);
                        }
                    }
                    else
                    {
                        btns = ButtonGroup.GetButtons(dt.Rows[0]["F_WorkState"].ToString(), userModel.F_RoleCode.ToUpper(), dt.Rows[0]["F_IsResult"].ToString(), "0");
                    }
                   
                    
                    #region 判断是否存在待督办
                    var recount = remindBLL.GetModelList("F_State=0 and F_IsDelete=0 and F_Type=1 and F_WorkOrderId ='" + strworkorderid + "'").ToList().Count();
                    var butt = btns.Find(c => c.key == ButtonGroup.turnsee().key);
                    if (recount > 0)
                    {
                        if (butt != null)
                            btns.Remove(butt);
                        if(userModel.F_RoleCode == "DBZY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
                        {
                            btns.Add(ButtonGroup.oversee());
                            btns.Add(ButtonGroup.turnnosee());
                        }
                    }
                    if (btns == null)
                    {
                        btns.Add(ButtonGroup.query());
                    }
                    else
                    {
                        if (btns.Count == 0)
                            btns.Add(ButtonGroup.query());
                    } 
                    #endregion
                    #endregion

                    #region 其他权限
                    int issend = 0;
                    if (dt.Rows[0]["F_IsRelease"] != null && (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "ZXLDGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG"))
                    {
                        if (dt.Rows[0]["F_IsRelease"].ToString() != "1")
                        {
                            issend = 1;
                        }
                    }
                    int isnotice = 0;
                    if (dt.Rows[0]["F_IsNotice"] != null && (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "ZXLDGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG"))
                    {
                        if (dt.Rows[0]["F_IsNotice"].ToString() != "1")
                        {
                            isnotice = 1;
                        }
                    }
                    int isedit = 0;
                    if (dt.Rows[0]["F_IsRelease"] != null && (userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "ZXLDGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG"))
                    {
                        isedit = 1;
                    }
                    #endregion

                    #region 获取所有工单部门名称
                    var olderworkerid = dt.Rows[0]["F_OldWorkOrderId"].ToString();
                    string alldeptname = "";
                    if (olderworkerid != "")
                    {
                        //var olderallworker = dt.Select(" F_OldWorkOrderId='" + olderworkerid + "'");
                        string sqlallwo = "select *,b.F_DeptName from T_Bus_WorkOrder a  left join  T_Sys_Department b  on a.F_MainDeptId=b.F_DeptId  where  F_IsDelete=0 and F_OldWorkOrderId='" + olderworkerid + "'";
                        var aaa = DbHelperSQL.Query(sqlallwo).Tables[0];
                        var bbb = aaa.Rows;
                        foreach (DataRow oldtrs in aaa.Rows)
                        {
                            alldeptname += oldtrs["F_DeptName"].ToString();
                            alldeptname += ",";
                        }
                    }
                    //else
                    //{
                    //    alldeptname = dt.Rows[0]["DeptName"].ToString();
                    //}

                    #endregion

                    DataTable relateddt = new DataTable();
                  if(dt.Rows[0]["F_RelatedWorkOrder"] != null && dt.Rows[0]["F_WorkOrderType"].ToString()=="1")
                     {
                        string relatesql = " select *  from T_Bus_WorkOrder a WITH(NOLOCK) where F_WorkOrderId ='" + dt.Rows[0]["F_RelatedWorkOrder"].ToString() + "'";

                        relateddt = DbHelperSQL.Query(relatesql).Tables[0];
                    }
                    var obj = new
                    {
                        data = dt,
                        jcdata = jcdt,
                        psdata = psdt,
                        zsdata = zsdt,
                        htdata = htdt,
                        dbdata = dbdt,
                        jbdata = jbdt,
                        ejjbdata = ejjbdt,
                        thdata = thdt,
                        ysdata = ysdt,
                        bldata = bldt,
                        ejbldata = ejbldt,
                        hfdata = hfdt,
                        cbdata = cbdt,
                        gcdata = gcdt,
                        issend = issend,
                        isedit = isedit,
                        isnotice = isnotice,
                        btndata = btns,
                        alldeptname = alldeptname,
                        relatedata = relateddt
                    };
                    return Success("获取成功", obj);
                }
                else
                {
                    return Error("获取失败");
                }
            }
            else
            {
                return Error("参数传输失败");
            }
        }

        /// <summary>
        /// 获取草稿信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetDraftInfo()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
            int type = RequestString.GetInt("type", 0);//1交办信息 2反馈信息 3回访信息 4履职界定信息
            if (!string.IsNullOrEmpty(strworkorderid) && type != 0)
            {
                string sql = string.Empty;
                switch (type)
                {
                    case 1:
                        sql = "select top 1 *,dbo.GetDeptName(F_MainDeptId) as DeptName,dbo.GetDeptNames(F_OtherDeptIds) as OtherDeptName,dbo.GetDictionaryName(F_StandardIDS) as StandardNames from T_Bus_AssignedInfo WITH(NOLOCK)"; break;
                    case 2: sql = "select top 1 * from T_Bus_Feedback WITH(NOLOCK)"; break;
                    case 3: sql = "select top 1 * from T_Bus_VisitResult WITH(NOLOCK)"; break;
                    case 4: sql = "select top 1 * from T_Bus_PerformDuties WITH(NOLOCK)"; break;
                }
                sql += " where F_WorkOrderId='" + strworkorderid + "' and F_State=0 and F_IsDelete=0 and F_CreateUser='" + userModel.F_UserCode + "' order by F_CreateTime desc";
                var dt = DbHelperSQL.Query(sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    #region 附件
                    var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

                    if (!string.IsNullOrEmpty(configfj.F_ParamValue))
                    {
                        BindFileData(dt, configfj.F_ParamValue);
                    }
                    #endregion
                }

                return Success("获取成功", dt);
            }
            else
            {
                return Error("参数传输失败");
            }
        }

        /// <summary>
        /// 获取审核信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetAuditInfo()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
            int type = RequestString.GetInt("type", 0);//1退回信息2延时信息
            if (!string.IsNullOrEmpty(strworkorderid) && type != 0)
            {
                string sql = string.Empty;
                switch (type)
                {
                    case 1: sql = "select top 1 * from T_Bus_Feedback WITH(NOLOCK) where F_Type=3 and "; break;
                    case 2: sql = "select top 1 * from T_Bus_DelayTime WITH(NOLOCK) where "; break;
                    case 3: sql = "select top 1 * from T_Bus_PerformDuties WITH(NOLOCK) where "; break;
                }
                if (type ==2)
                {
                    sql += " F_WorkOrderId='" + strworkorderid + "'  and F_IsDelete=0 and F_IsAudit=0 order by F_CreateTime desc";
                }
                else
                {
                    sql += " F_WorkOrderId='" + strworkorderid + "' and F_State=1 and F_IsDelete=0 and F_IsAudit=0 order by F_CreateTime desc";
                }
              
                var dt = DbHelperSQL.Query(sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    #region 附件

                    var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

                    if (!string.IsNullOrEmpty(configfj.F_ParamValue))
                    {
                        BindFileData(dt, configfj.F_ParamValue);
                    }
                    #endregion
                }

                return Success("获取成功", dt);
            }
            else
            {
                return Error("参数传输失败");
            }
        }

        /// <summary>
        /// 获取所有交办单位
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetAllAssignDept()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(strworkorderid);
            if (modelT_Bus_WorkOrder != null)
            {
                string ids = string.Empty;
                var Assigns = assignBLL.GetModelList(" F_WorkOrderId='" + strworkorderid + "' and F_IsDelete=0 and F_IsSure in (0,1,2) ");
                foreach (var assign in Assigns)
                {
                    if (string.IsNullOrEmpty(ids))
                    {
                        ids = assign.F_MainDeptId.Value.ToString();
                        if (!string.IsNullOrEmpty(assign.F_OtherDeptIds))
                        {
                            ids += "," + assign.F_OtherDeptIds;
                        }
                    }
                    else
                    {
                        ids += "," + assign.F_MainDeptId.Value.ToString();
                        if (!string.IsNullOrEmpty(assign.F_OtherDeptIds))
                        {
                            ids += "," + assign.F_OtherDeptIds;
                        }
                    }
                }
                if (string.IsNullOrEmpty(ids))
                {
                    ids = "0";
                }
                var dt = new BLL.T_Sys_Department().GetModelList(" F_DeptId in ( " + ids + " ) ");

                return Success("获取成功", dt);
            }
            else
            {
                return Error("操作失败");
            }
        }
       
        /// <summary>
        /// 获取二级单位处理信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetSecondDealInfo()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
            if (!string.IsNullOrEmpty(strworkorderid))
            {
                //string sql = "SELECT an.F_Id, an.F_WorkOrderId, an.F_MainDeptId, an.F_OtherDeptIds, an.F_AssignedOpinion, an.F_Remark, an.F_CreateUser, an.F_CreateTime, an.F_IsSure, an.F_State, ";
                //sql += " an.F_SureTime, an.F_IsDelete, an.F_DeleteUser, an.F_DeleteTime, an.F_SureUser, an.F_FeedbackTime, an.F_LimitTime, an.F_IsOverdue, an.F_IsSatisfie, ";
                //sql += " an.F_IsReload, an.F_ReloadUser, an.F_ReloadTime, an.F_File, an.F_IsNotice, an.F_NoticeUser, an.F_NoticeTime,  fn.F_AssignedId, ";
                //sql += " fn.F_Result, fn.F_CreateDeptId, fn.F_IsFeedEnd, fn.F_IsAudit, fn.F_AuditUser, fn.F_AuditTime, fn.F_AuditReason ";
                //sql += " FROM T_Bus_AssignedInfo_Next AS an LEFT OUTER JOIN T_Bus_Feedback_Next AS fn ON an.F_Id = fn.F_AssignedId AND an.F_IsDelete = 0 AND fn.F_IsDelete = 0";
                //sql += " where an.F_WorkOrderId='" + strworkorderid + "' order by F_CreateTime desc";
                //var dt = DbHelperSQL.Query(sql).Tables[0];

                string sql = "select top 1 * from T_Bus_AssignedInfo_Next WITH(NOLOCK) where F_WorkOrderId='" + strworkorderid + "' and F_IsDelete = 0 order by F_CreateTime desc";
                string sql1 = "select * from T_Bus_Feedback_Next WITH(NOLOCK) where  F_WorkOrderId='" + strworkorderid + "' and F_IsDelete = 0 ";

                var bldt = DbHelperSQL.Query(sql1).Tables[0];
                var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                if (configfj != null)
                {
                    bldt = BindFileData(bldt, configfj.F_ParamValue);
                }

                var obj = new {
                    pdinfo = DbHelperSQL.Query(sql).Tables[0],
                    fkinfo = bldt
                };

                return Success("获取成功", obj);
            }
            else
            {
                return Error("参数传输失败");
            }
        }

        /// <summary>
        /// 获取二级单位最新处理信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetNewSecondDealInfo()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
            if (!string.IsNullOrEmpty(strworkorderid))
            {
                string sql = "select top 1 * from T_Bus_Feedback_Next WITH(NOLOCK) where  F_WorkOrderId='" + strworkorderid + "' and F_IsDelete = 0 order by F_CreateTime desc";

                var bldt = DbHelperSQL.Query(sql).Tables[0];
                var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                if (configfj != null)
                {
                    bldt = BindFileData(bldt, configfj.F_ParamValue);
                }

                return Success("获取成功", bldt);
            }
            else
            {
                return Error("参数传输失败");
            }
        }

        /// <summary>
        /// 查看回访信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetVisitInfo()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));

            if (!string.IsNullOrEmpty(strworkorderid))
            {
                string sqlvisit = "select * from T_Bus_VisitResult WITH(NOLOCK) where F_WorkOrderId='" + strworkorderid + "' and F_State=1 and F_IsDelete=0 and F_IsSatisfie=0 order by F_CreateTime";
                string sqlassgin = "select * from T_Bus_AssignedInfo WITH(NOLOCK) where F_WorkOrderId ='" + strworkorderid + "' and F_State=1 and F_IsDelete=0 order by F_CreateTime";

                var dtvisit = DbHelperSQL.Query(sqlvisit).Tables[0];
                var dtassgin = DbHelperSQL.Query(sqlassgin).Tables[0];
                var config = configBll.GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
                dtvisit.Columns.Add("FilePath", typeof(string));
                dtvisit.Columns.Add("IsShowCheck", typeof(string));
                if (dtvisit.Rows.Count > 0)
                {
                    foreach (DataRow bldr in dtvisit.Rows)
                    {
                        #region 是否可勾选
                        var IsShowCheck = 0;
                        var drass = dtassgin.Select(" F_ID='" + bldr["F_AssignedId"].ToString() + "'");
                        if (drass.Length > 0)
                        {
                            var ass = (from DataRow dr in drass select dr.Field<int>("F_MainDeptId")).FirstOrDefault();
                            if(ass>0)
                            {
                                if (ass == userModel.F_DeptId)
                                    IsShowCheck = 1;
                            }
                        }
                        bldr["IsShowCheck"] = IsShowCheck;
                        #endregion
                        #region 录音
                        if (bldr["F_CallRecordId"] != null && config != null)
                        {
                            bldr["FilePath"] = GetCallPath(bldr["F_CallRecordId"].ToString(), config.F_ParamValue);
                        }
                        #endregion
                    }

                }

                return Success("获取成功", dtvisit);
            }
            else
            {
                return Error("参数传输失败");
            }
        }
       
        #endregion

        #region 新增工单
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UploadFile()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            #region 单个上传 no use
            //string path = string.Empty;
            //HttpPostedFile _upfile = RequestString.GetFile("upFile");
            //if (_upfile != null)
            //{
            //    //byte[] buffer = new Byte[(int)_upfile.InputStream.Length]; //声明文件长度的二进制类型
            //    //_upfile.InputStream.Read(buffer, 0, buffer.Length); //将文件转成二进制
            //    string name = string.Empty;
            //    FileUp fu = new FileUp();
            //    var model = configBll.GetModelList(" F_ParamCode='FilePath' ").FirstOrDefault();
            //    if (model != null)
            //    {
            //        name = fu.Upload(_upfile, model.F_ParamValue);

            //        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 = name;//附件名称
            //        model_T_Sys_Accessories.F_FileType = System.IO.Path.GetExtension(_upfile.FileName);//附件类型
            //        model_T_Sys_Accessories.F_FileUrl = model.F_ParamValue + name;//附件地址
            //        model_T_Sys_Accessories.F_Size = _upfile.ContentLength;
            //        model_T_Sys_Accessories.F_UserCode = userModel.F_UserCode;//上传人  
            //        int p_fuId = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);

            //        return Success("成功", model_T_Sys_Accessories);
            //    }
            //    else
            //    {
            //        return Error("上传失败");
            //    }

            //}
            //else
            //{
            //    return Error("请选择要上传的文件");
            //} 
            #endregion

            #region 多个上传
            HttpFileCollection files = RequestString.GetFiles();
            if (files.Count > 0)
            {
                List<Model.T_Sys_Accessories> acs = new List<Model.T_Sys_Accessories>();
                string path = "/Upload/Files/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[i];
                    FileUp fu = new FileUp();
                    string fileExtension = Configs.GetValue("fileExtension");
                    if (!fileExtension.Contains((System.IO.Path.GetExtension(file.FileName).ToLower())))
                    {
                        return Error("附件格式不正确");
                    }
                    string name = fu.Upload(file, path);

                    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 = name;//附件名称
                    model_T_Sys_Accessories.F_FileType = System.IO.Path.GetExtension(file.FileName);//附件类型
                    model_T_Sys_Accessories.F_FileUrl = path + name;//附件地址
                    model_T_Sys_Accessories.F_Size = file.ContentLength;
                    model_T_Sys_Accessories.F_UserCode = userModel.F_UserCode;//上传人  
                    int id = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    model_T_Sys_Accessories.F_FileId = id;
                    acs.Add(model_T_Sys_Accessories);
                }

                return Success("成功", acs);
            }
            else
            {
                return Error("请选择要上传的文件");
            }
            #endregion
        }
        private BLL.T_Sys_SystemConfig sysConfigBLL = new BLL.T_Sys_SystemConfig();
        /// <summary>
        /// 添加工单模板
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// [Authority]
        public ActionResult AddConfig(string id)
        {
            var model = sysConfigBLL.GetModelList("F_ParamCode='GDMB'");
            if (model !=null )
            {
                var sysConfig = model.FirstOrDefault();
                sysConfig.F_ParamValue = id;
                if (sysConfigBLL.Update (sysConfig))
                    return Success("修改成功");
                else
                    return Error("修改失败");
            }
            else
            {
                var sysConfig = new Model.T_Sys_SystemConfig();
                sysConfig.F_ParamCode = "GDMB";
                sysConfig.F_ParamValue = id;
                sysConfig.F_ParamDes = "工单模板";
                sysConfig.F_State = 1;
                if (sysConfigBLL.Add(sysConfig) > 0)
                    return Success("添加成功");
                else
                    return Error("添加失败");
            }
          
        }
        /// <summary>
        /// 添加基础数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// [Authority]
        public ActionResult GetConfig()
        {
            var model = sysConfigBLL.GetModelList("F_ParamCode='GDMB'");
            if (model!=null )
            {
                DataTable dt = new DataTable();
                var sysConfig = model.FirstOrDefault();
                dt = BindFileConfig(dt, sysConfig.F_ParamValue);

                return Success("获取成功");
            }
            else
            {
                return Error("附件不存在");
            }
       
        }
        /// <summary>
        /// 绑定附件信息
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public DataTable BindFileConfig(DataTable dt, string prefix)
        {

            dt.Columns.Add("Files", typeof(object));
            foreach (DataRow dr in dt.Rows)
            {

                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    dr["Files"] = GetFileData(dr["F_Files"].ToString(), prefix);
                }
            }
            return dt;
        }
        /// <summary>
        /// 添加工单信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AddWorkOrder()
        {

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "ZXBZ" 
                || userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY"
                || userModel.F_RoleCode == "ZJZY" || userModel.F_RoleCode == "DBZY"
                || userModel.F_RoleCode == "11"   || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG"
                || userModel.F_RoleCode == "DFZF" || userModel.F_RoleCode == "WLDW") //增加新闻媒体(编号11)的添加工单权限 
            {

                string workorderid = RequestString.GetFormString("workorderid"); //工单编号
                int  id = RequestString.GetInt("id", 0); //编号
                string  time = RequestString.GetFormString("time");

                string title = RequestString.GetFormString("title"); //题目
                string cusname = RequestString.GetFormString("cusname");//作者
                string keys = RequestString.GetFormString("keys");//内容简介
                string cusaddress = RequestString.GetFormString("cusaddress");//主要地址
                int sourcearea = RequestString.GetInt("sourcearea", 0);//精准地域
                string publishtime = RequestString.GetFormString("publishtime");//网络发布时间
                string sourceaddress = RequestString.GetFormString("sourceaddress");//精准地域 详细地址
                string source = RequestString.GetFormString("source"); //题目 RequestString.GetInt("source", 0);//舆情来源
                int infoproperty = RequestString.GetInt("infoproperty", 0);//信息属性
                int level= RequestString.GetInt("level", 0);//舆情等级
                int type = RequestString.GetInt("type", 0);//舆情类型           
                string files = RequestString.GetFormString("files");//附件
                int isresult = RequestString.GetInt("isresult", 0);//1是当即处理 0网络转办
                int issubmit = RequestString.GetInt("issubmit", 0);

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

                string result = RequestString.GetFormString("result");//当即处理时的处理内容

                string  relatedworkorder = RequestString.GetFormString("relatedworkorder");//频发工单创建时关联的工单号

                int  workordertype = RequestString.GetInt("workordertype", 0);//工单类型 0 是舆情工单 1 是频发舆情工单


                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存工单信息
                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
                    if (workordertype==1 && !workorderBLL.Exists(relatedworkorder))
                    {
                        return Error("关联提示函编号不存在");
                    }


                    if (workordertype==0)
                    {
                        if (!string.IsNullOrEmpty(workorderid))
                        {
                            if (id <= 0)
                                return Error("请输入正确编号");
                            if (workorderBLL.Exists(workorderid))
                                return Error("工单编号重复");
                            if (string.IsNullOrEmpty(time))
                                return Error("请选择年份");
                            DateTime times = DateTime.Now;
                            try
                            {
                                times = DateTime.Parse(time + DateTime.Now.ToString("-MM-dd HH:mm:ss"));
                            }
                            catch
                            {
                                return Error("请输入正确年份");
                            }

                            modelT_Bus_WorkOrder.F_WorkOrderId =
                                DbHelperSQL.GetSingle($"exec [GetNewWorkOrderIdByYear1] '{id}','{times.ToString("yyyy-MM-dd HH:mm:ss")}'").ToString();

                        }
                        else
                        {
                            modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID(userModel.F_UserCode);
                            var information = DbHelperSQL.GetSingle( "select dbo.GetDictionaryNames('" + infoproperty + "')");
                            if (information!=null&& information.ToString()=="敏感")
                            {
                                modelT_Bus_WorkOrder.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId + "-敏感";
                            }

                        }

                    }
                    else //1 是频发舆情工单
                    {
                        if (!string.IsNullOrEmpty(workorderid))
                        {
                            if (id <= 0)
                                return Error("请输入正确编号");
                            if (workorderBLL.Exists(workorderid))
                                return Error("工单编号重复");
                            if (string.IsNullOrEmpty(time))
                                return Error("请选择年份");
                            DateTime times = DateTime.Now;
                            try
                            {
                                times = DateTime.Parse(time + DateTime.Now.ToString("-MM-dd HH:mm:ss"));
                            }
                            catch
                            {
                                return Error("请输入正确年份");
                            }

                            modelT_Bus_WorkOrder.F_WorkOrderId =
                                DbHelperSQL.GetSingle($"exec [GetNewWorkOrderIdByYearPF1] '{id}','{times.ToString("yyyy-MM-dd HH:mm:ss")}'").ToString();

                        }
                        else
                        {
                            modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderIDPF(userModel.F_UserCode);
                            var information = DbHelperSQL.GetSingle("select dbo.GetDictionaryNames('" + infoproperty + "')");
                            if (information != null && information.ToString() == "敏感")
                            {
                                modelT_Bus_WorkOrder.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId + "-敏感";
                            }
                        }
                        modelT_Bus_WorkOrder.F_RelatedWorkOrder = relatedworkorder; //频发工单创建时关联的工单号

                    }



                    modelT_Bus_WorkOrder.F_WorkOrderType = workordertype; //工单类型 0 是舆情工单 1 是频发舆情工单
                    modelT_Bus_WorkOrder.F_ComTitle = title;//题目
                    modelT_Bus_WorkOrder.F_CusName = cusname;//作者
                    modelT_Bus_WorkOrder.F_ComContent = keys;//内容简介
                    modelT_Bus_WorkOrder.F_CusAddress = cusaddress;//主要地址
                    modelT_Bus_WorkOrder.F_SourceArea = sourcearea;//精准地域
                    if ( !string.IsNullOrEmpty( publishtime))
                    {
                        modelT_Bus_WorkOrder.F_Hcdatetime = Convert.ToDateTime( publishtime);//网络发布时间
                    }
                    modelT_Bus_WorkOrder.F_SourceAddress = sourceaddress;///精准地域 详细地址
                    modelT_Bus_WorkOrder.F_Event = source;//舆情来源
                    modelT_Bus_WorkOrder.F_InfoConBigType = infoproperty;//信息属性
                    modelT_Bus_WorkOrder.F_Level = level;// 舆情等级
                    modelT_Bus_WorkOrder.F_InfoType = type;//舆情类型
                    modelT_Bus_WorkOrder.F_File = files;//附件
 

                    //是否直办（即时答复）0:，否1： 是         
                    modelT_Bus_WorkOrder.F_IsResult = isresult;
                    modelT_Bus_WorkOrder.F_Result = result;//处理结果

                    modelT_Bus_WorkOrder.F_CreateUser = userModel.F_UserCode;//登记人工号
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;//登记时间
                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.neworder;// 0;//工单状态0登记中
                    modelT_Bus_WorkOrder.F_IsClosed = 0;//工单是否关闭
                    modelT_Bus_WorkOrder.F_IsOverdue = 0;//是否逾期(0:否，1：是)
                    modelT_Bus_WorkOrder.F_IsDelete = 0;//是否删除(0:否，1：是)

                    //如果选择即刻答复：是，即为直办，工单结束
                    if (isresult == 1)
                    {
                        if (userModel.F_RoleCode == "WLDW")
                        {
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;//
                        }
                        else
                        {
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;// 9;//已结案
                            modelT_Bus_WorkOrder.F_DealDeptId = userModel.F_DeptId;
                            modelT_Bus_WorkOrder.F_DealUser = userModel.F_UserCode;
                            modelT_Bus_WorkOrder.F_DealTime = DateTime.Now;
                            modelT_Bus_WorkOrder.F_IsClosed = 1;
                            modelT_Bus_WorkOrder.F_CloseUser = userModel.F_UserCode;
                            modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;
                            modelT_Bus_WorkOrder.F_MainDeptId = userModel.F_DeptId;
                        }
                       
                        
                    }
                    //else if (userModel.F_RoleCode == "WLDW")
                    //{
                    //    #region 插入交办记录

                    //    string  limittime = RequestString.GetFormString("limittime");
                    //    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = new T_Bus_AssignedInfo();
                    //    modelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    //    modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                    //    modelT_Bus_AssignedInfo.F_MainDeptId = maindeptid;//主办单位id
                    //    modelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                    //    modelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见
                    //    modelT_Bus_AssignedInfo.F_State = 1;//0草稿  1正式
                    //    modelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                    //    modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                    //    modelT_Bus_AssignedInfo.F_IsDelete = 0;
                    //    modelT_Bus_AssignedInfo.F_IsOverdue = 0;
                    //    modelT_Bus_AssignedInfo.F_IsSure = 0;
                    //    modelT_Bus_AssignedInfo.F_IsReload = 0;
                    //    modelT_Bus_AssignedInfo.F_IsNext = 0;
                    //    modelT_Bus_AssignedInfo.F_TimeResp = assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                    //    int aid = assignBLL.Add(modelT_Bus_AssignedInfo);
                    //    #endregion

                    //}
                    else if (issubmit == 1)
                    {
                        modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;// 1;//提交领导
                    }
                    #region
                    //20190715需求变动，去掉审核环节 提交后直接调度指派 zhengbingbing
                    //else
                    //{
                    //    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.audit;//待审核
                    //}
                    #region
                    //20190315需求变动，保存并提交按钮取消，保存后提交待审核 20190329 zhengbingbing
                    //else if (issubmit == 1)
                    //{
                    //    modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                    //    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;// 1;//提交领导
                    //}
                    #endregion
                    #endregion
                    if (!string.IsNullOrEmpty(callid))
                    {
                        modelT_Bus_WorkOrder.F_CallId = callid;
                        var rd = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
                        if (rd != null)
                        {
                            rd.IsExitWorkOrder = true;
                            new BLL.T_Call_CallRecords().Update(rd);

                            modelT_Bus_WorkOrder.F_CallRecordId = rd.CallRecordsId;
                        }
                    }

                 
                    #endregion

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

                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                    //if (modelT_Bus_WorkOrder.F_WorkState == 0)
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.neworder || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)
                    {
                        oper.F_Message = userinfo + " 登记了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    //if (modelT_Bus_WorkOrder.F_WorkState == 1)
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)
                    {
                        oper.F_Message = userinfo + " 登记并提交了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    //if (modelT_Bus_WorkOrder.F_WorkState == 9)
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)
                    {
                        oper.F_Message = userinfo + " 登记并结案了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }

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

                    operBLL.Add(oper);

                    //推送消息表
                    if (modelT_Bus_WorkOrder.F_WorkState != (int)EnumWorkState.neworder && modelT_Bus_WorkOrder.F_WorkState != (int)EnumWorkState.audit) //0)
                    {
                        var role = new BLL.T_Sys_RoleInfo().GetModelList(" (F_RoleCode='ZXLD' or F_RoleCode='ZXLDGLYGLY')  ").Select(p => p.F_RoleId);
                        var users = userBLL.GetModelList(" F_RoleId in (" + string.Join(",", role) + ")  ");

                        foreach (var u in users)
                        {
                            msg.AddInternalMessagesInfo("工单消息", oper.F_Message, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.workorder);
                        }
                    }

                    if (isresult==1 && userModel.F_RoleCode == "WLDW" && modelT_Bus_WorkOrder.F_WorkState==1)
                    {
                        //二级单位交办给他自己
                        string resdatetime = "";
                        int limittime = 5;
                       
                            string resdate = DateTime.Now.Date.ToString("yyyy-MM-dd");
                            DataTable dt = DbHelperSQL.Query("select top " + limittime + " F_OffDate from  T_Sys_WorkOFFDays  with(nolock) where F_OffState = 1   and F_OffDate>'" + resdate + "' order by F_OffDate").Tables[0];
                            resdatetime = dt.Rows[dt.Rows.Count - 1]["F_OffDate"].ToString();
                         
                        resdatetime = Convert.ToDateTime(resdatetime).ToString("yyyy-MM-dd") + " 23:59:59 ";

                        #region 插入交办记录
                        Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = new T_Bus_AssignedInfo();
                        modelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                        modelT_Bus_AssignedInfo.F_LimitTime = Convert.ToDateTime( resdatetime);//办理时限
                        modelT_Bus_AssignedInfo.F_MainDeptId = userModel.F_DeptId;//主办单位id
                        modelT_Bus_AssignedInfo.F_OtherDeptIds = "";//协办单位id
                        modelT_Bus_AssignedInfo.F_AssignedOpinion = "自主办理";//交办意见

                        modelT_Bus_AssignedInfo.F_State = 1;//0草稿  1正式
                        modelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                        modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                        modelT_Bus_AssignedInfo.F_IsDelete = 0;
                        modelT_Bus_AssignedInfo.F_IsOverdue = 0;
                        modelT_Bus_AssignedInfo.F_IsSure = 1;
                        modelT_Bus_AssignedInfo.F_IsReload = 0;
                        modelT_Bus_AssignedInfo.F_IsNext = 0;
                        modelT_Bus_AssignedInfo.F_SureUser = userModel.F_UserCode;
                        modelT_Bus_AssignedInfo.F_SureTime = DateTime.Now;
                        modelT_Bus_AssignedInfo.F_TimeResp = assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                       int  aid = assignBLL.Add(modelT_Bus_AssignedInfo);

                        #endregion

                      
                        #region 保存工单信息
                        modelT_Bus_WorkOrder.F_WorkState = 4;//办理中
                      //  workorderBLL.Update(modelT_Bus_WorkOrder);
                        #endregion

                      
                 
                       


                    }

                    workorderBLL.Add(modelT_Bus_WorkOrder);
                    #endregion

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

            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 添加工单信息
        /// </summary>
        /// <returns></returns>
        public string AddWorkOrderBySource(int source, string cusname, string cussex, string cusphone, string cusaddress, string email,
            string zipcode, string conname, string conphone, string title, string content, int sourcearea, string sourceaddress,
            string keys, string splituser, int type, int bigtype, int smalltype, int isprotect, int level, string files = null)
        {
            string workorderid = string.Empty;

            using (TransactionScope trans = new TransactionScope())
            {
                #region 保存工单信息
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
                modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID(source.ToString().PadLeft(4, '0'));

                modelT_Bus_WorkOrder.F_InfoSource = source;//信息来源

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

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

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

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

                //modelT_Bus_WorkOrder.F_Latitude = latitude != "" ? decimal.Parse(latitude) : 0;//纬度
                //modelT_Bus_WorkOrder.F_Longitude = longitude != "" ? decimal.Parse(longitude) : 0;//经度

                //modelT_Bus_WorkOrder.F_CreateUser = userModel.F_UserCode;//登记人工号
                modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;//登记时间
                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.neworder;// 0;//工单状态0登记中
                //modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.audit;//审核环节去掉 20190715
                modelT_Bus_WorkOrder.F_IsClosed = 0;//工单是否关闭
                modelT_Bus_WorkOrder.F_IsOverdue = 0;//是否逾期(0:否，1：是)
                modelT_Bus_WorkOrder.F_IsDelete = 1;//是否删除(0:否，1：是)
                modelT_Bus_WorkOrder.F_IsEnabled = 0;//是否处理

                workorderBLL.Add(modelT_Bus_WorkOrder);
                workorderid = modelT_Bus_WorkOrder.F_WorkOrderId;
                #endregion

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

                string userinfo = "";
                var sourceinfo = new BLL.T_Sys_DictionaryValue().GetModel(source);
                if (sourceinfo != null) { userinfo = "由 " + sourceinfo.F_Value; }
                if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.neworder || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)//0)
                {
                    oper.F_Message = userinfo + " 登记了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                }

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

                operBLL.Add(oper);
                #endregion

                trans.Complete();
            }

            return workorderid;
        }

        /// <summary>
        /// 添加工单信息留言
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AddWorkOrderByLY()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "ZXBZ" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {

                int source = RequestString.GetInt("source", 0);

                string cusname = RequestString.GetFormString("cusname");
                string cussex = RequestString.GetFormString("cussex");
                string cusphone = RequestString.GetFormString("cusphone");
                string cusaddress = RequestString.GetFormString("cusaddress");
                string email = RequestString.GetFormString("email");
                string zipcode = RequestString.GetFormString("zipcode");
                string conname = RequestString.GetFormString("conname");
                string conphone = RequestString.GetFormString("conphone");

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

                int isresult = RequestString.GetInt("isresult", 0);
                string result = RequestString.GetFormString("result");

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

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

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

                int lyid = RequestString.GetInt("lyid", 0);


                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存工单信息
                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new Model.T_Bus_WorkOrder();
                    modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID(userModel.F_UserCode);
                   
                    modelT_Bus_WorkOrder.F_InfoSource = source;//信息来源

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

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

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

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

                    //是否直办（即时答复）0:，否1： 是         
                    modelT_Bus_WorkOrder.F_IsResult = isresult;
                    modelT_Bus_WorkOrder.F_Result = result;//处理结果

                    modelT_Bus_WorkOrder.F_CreateUser = userModel.F_UserCode;//登记人工号
                    modelT_Bus_WorkOrder.F_CreateTime = DateTime.Now;//登记时间
                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.neworder;// 0;//工单状态0登记中
                    modelT_Bus_WorkOrder.F_IsClosed = 0;//工单是否关闭
                    modelT_Bus_WorkOrder.F_IsOverdue = 0;//是否逾期(0:否，1：是)
                    modelT_Bus_WorkOrder.F_IsDelete = 0;//是否删除(0:否，1：是)

                    //如果选择即刻答复：是，即为直办，工单结束
                    if (isresult == 1)
                    {
                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;// 9;//已结案
                        modelT_Bus_WorkOrder.F_DealUser = userModel.F_UserCode;
                        modelT_Bus_WorkOrder.F_DealTime = DateTime.Now;
                        modelT_Bus_WorkOrder.F_IsClosed = 1;
                        modelT_Bus_WorkOrder.F_CloseUser = userModel.F_UserCode;
                        modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;
                    }
                    else if (issubmit == 1)
                    {
                        modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;// 1;//提交领导
                    }
                    #region
                    //20190715去掉审核环节
                    //else
                    //{
                    //    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.audit;//待审核
                    //}

                    //else if (issubmit == 1)
                    //{
                    //    modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                    //    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;// 1;//提交领导
                    //}
                    #endregion
                    if (lyid != 0)
                    {
                        var rd = new BLL.T_Call_LeaveRecord().GetModel(lyid);
                        if (rd != null)
                        {
                            modelT_Bus_WorkOrder.F_LeaveRecordId = rd.F_Id;
                        }
                    }

                    workorderBLL.Add(modelT_Bus_WorkOrder);
                    #endregion

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

                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.neworder || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)//0)
                    {
                        oper.F_Message = userinfo + " 登记了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)//1)
                    {
                        oper.F_Message = userinfo + " 登记并提交了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)//9)
                    {
                        oper.F_Message = userinfo + " 登记并结案了工单,工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId;
                    }

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

                    operBLL.Add(oper);

                    //推送消息表
                    if (modelT_Bus_WorkOrder.F_WorkState != (int)EnumWorkState.neworder && modelT_Bus_WorkOrder.F_WorkState != (int)EnumWorkState.audit)//0)
                    {
                        var role = new BLL.T_Sys_RoleInfo().GetModelList(" (F_RoleCode='ZXLD' or F_RoleCode='ZXLDGLYGLY')  ").Select(p => p.F_RoleId);
                        var users = userBLL.GetModelList(" F_RoleId in (" + string.Join(",", role) + ")  ");

                        foreach (var u in users)
                        {
                            msg.AddInternalMessagesInfo("工单消息", oper.F_Message, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.workorder);
                        }
                    }
                    #endregion

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

            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 添加工单信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AddWorkOrderByAPP()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            int source = RequestString.GetInt("source", 6);

            string cusname = RequestString.GetFormString("cusname");
            string cussex = RequestString.GetFormString("cussex");
            string cusphone = RequestString.GetFormString("cusphone");
            string cusaddress = RequestString.GetFormString("cusaddress");
            string email = RequestString.GetFormString("email");
            string zipcode = RequestString.GetFormString("zipcode");
            string conname = RequestString.GetFormString("conname");
            string conphone = RequestString.GetFormString("conphone");

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

            int isresult = RequestString.GetInt("isresult", 0);
            string result = RequestString.GetFormString("result");

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

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

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


            string workorderid = AddWorkOrderBySource(6, cusname, cussex, cusphone, cusaddress, email, zipcode, conname,
                    conphone, title, content, sourcearea, sourceaddress, keys, splituser, type, bigtype, smalltype, isprotect, level, files);
            if (!string.IsNullOrEmpty(workorderid))
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存用户工单信息
                    var model = new BLL.T_Sys_Users().GetModel(userModel.F_UserCode);
                    if (model == null)
                    {
                        model = new Model.T_Sys_Users();
                        model.F_OpenId = userModel.F_UserCode;
                        model.F_Type = (int)EnumUserType.app;//3;
                        model.F_CreateTime = DateTime.Now;
                        model.F_Id = new BLL.T_Sys_Users().Add(model);
                    }

                    Model.T_Bus_UserWorkOrder tbu = new Model.T_Bus_UserWorkOrder();
                    tbu.F_UserId = model.F_Id;
                    tbu.F_WorkOrderId = workorderid;
                    new BLL.T_Bus_UserWorkOrder().Add(tbu);
                    #endregion

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


        }
        #endregion

        #region 操作工单
      
        /// <summary>
        /// 修改工单信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult EditWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "ZXBZ" || userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                //if (modelT_Bus_WorkOrder != null && (modelT_Bus_WorkOrder.F_WorkState == 1 || modelT_Bus_WorkOrder.F_WorkState == 0))
               
                    string title = RequestString.GetFormString("title"); //题目
                    string cusname = RequestString.GetFormString("cusname");//作者
                    string keys = RequestString.GetFormString("keys");//内容简介
                    string cusaddress = RequestString.GetFormString("cusaddress");//主要地址
                    int sourcearea = RequestString.GetInt("sourcearea", 0);//精准地域
                    string publishtime = RequestString.GetFormString("publishtime");//网络发布时间
                    string sourceaddress = RequestString.GetFormString("sourceaddress");//精准地域 详细地址
                string source = RequestString.GetFormString("source");
                int infoproperty = RequestString.GetInt("infoproperty", 0);//信息属性
                    int level = RequestString.GetInt("level", 0);//舆情等级
                    int type = RequestString.GetInt("type", 0);//舆情类型           
                    string files = RequestString.GetFormString("files");//附件
                    int isresult = RequestString.GetInt("isresult", 0);//1是当即处理 网络转办
                    int issubmit = RequestString.GetInt("issubmit", 0);
                    string result = RequestString.GetFormString("result"); //处理结果

                string relatedworkorder = RequestString.GetFormString("relatedworkorder");//频发工单关联的工单号

                using (TransactionScope trans = new TransactionScope())
                    {
                    #region 保存工单信息
                    if (!string.IsNullOrEmpty( relatedworkorder) && !workorderBLL.Exists(relatedworkorder))
                    {
                        return Error("关联提示函编号不存在");
                    }



                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    dic.Add("F_ComTitle", title);
                    dic.Add("F_CusName", cusname);
                    dic.Add("F_ComContent", keys);
                    dic.Add("F_CusAddress", cusaddress);
                    dic.Add("F_SourceArea", sourcearea);

                    //modelT_Bus_WorkOrder.F_ComTitle = title;//题目
                    //    modelT_Bus_WorkOrder.F_CusName = cusname;//作者
                    //    modelT_Bus_WorkOrder.F_Key = keys;//内容简介
                    //    modelT_Bus_WorkOrder.F_CusAddress = cusaddress;//主要地址
                    //    modelT_Bus_WorkOrder.F_SourceArea = sourcearea;//精准地域
                    if (modelT_Bus_WorkOrder.F_WorkOrderType==1)
                    {
                        dic.Add("F_RelatedWorkOrder", relatedworkorder);
                    }
                        if (!string.IsNullOrEmpty(publishtime))
                        {
                        dic.Add("F_Scanning", Convert.ToDateTime(publishtime));
                       // modelT_Bus_WorkOrder.F_Scanning = Convert.ToDateTime(publishtime);//网络发布时间
                        }
                    dic.Add("F_SourceAddress", sourceaddress);
                    dic.Add("F_Event", source);
                    dic.Add("F_InfoConBigType", infoproperty);


                    //modelT_Bus_WorkOrder.F_SourceAddress = sourceaddress;///精准地域 详细地址
                    //    modelT_Bus_WorkOrder.F_InfoSource = source;//舆情来源
                    //    modelT_Bus_WorkOrder.F_InfoConBigType = infoproperty;//信息属性
                    //    modelT_Bus_WorkOrder.F_Level = level;// 舆情等级
                    //    modelT_Bus_WorkOrder.F_InfoType = type;//舆情类型
                    //    modelT_Bus_WorkOrder.F_File = files;//附件
                    dic.Add("F_Level", level);
                    dic.Add("F_InfoType", type);
                    dic.Add("F_File", files);



                    //是否直办（即时答复）0:，否1： 是         
                    //modelT_Bus_WorkOrder.F_IsResult = isresult;
                    // modelT_Bus_WorkOrder.F_Result = result;//处理结果

                    dic.Add("F_IsResult", isresult);
                    dic.Add("F_Result", result);

                    //如果选择即刻答复：是，即为直办，工单结束
                    if (modelT_Bus_WorkOrder.F_WorkState<=1)
                    {
                        if (isresult == 1)
                        {
                            //modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;// 9;//已结案
                            //modelT_Bus_WorkOrder.F_DealDeptId = userModel.F_DeptId;
                            //modelT_Bus_WorkOrder.F_DealUser = userModel.F_UserCode;
                            //modelT_Bus_WorkOrder.F_DealTime = DateTime.Now;
                            //modelT_Bus_WorkOrder.F_IsClosed = 1;
                            //modelT_Bus_WorkOrder.F_CloseUser = userModel.F_UserCode;
                            //modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;

                            dic.Add("F_WorkState", (int)EnumWorkState.finish);
                            dic.Add("F_DealDeptId", userModel.F_DeptId);
                            dic.Add("F_DealUser", userModel.F_UserCode);
                            dic.Add("F_DealTime", DateTime.Now);
                            dic.Add("F_IsClosed", 1);

                            dic.Add("F_CloseUser", userModel.F_UserCode);
                            dic.Add("F_CloseTime", DateTime.Now);


                        }
                        else if (issubmit == 1)
                        {
                            //modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                            //modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;// 1;//提交领导


                            dic.Add("F_SubmitTime", DateTime.Now);
                            dic.Add("F_WorkState", (int)EnumWorkState.submit);
                        }

                    }


                    #region
                    //20190715 审核环节去掉 zhengbingbing
                    //else
                    //{
                    //    if(modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.neworder || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)
                    //        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.audit;
                    //}
                    //else if (issubmit == 1)
                    //{
                    //    modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                    //    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;// 1;//提交领导
                    //}
                    #endregion

                    workorderBLL.UpdateWorkOrder(modelT_Bus_WorkOrder.F_Id,dic);
                        #endregion

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

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.neworder || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)//0)
                        {
                            oper.F_Message = userinfo + " 修改了工单";
                        }
                        if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)//1)
                        {
                            oper.F_Message = userinfo + " 修改并提交了工单";
                        }
                        if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)//9)
                        {
                            oper.F_Message = userinfo + " 修改并结案了工单";
                        }

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

                        operBLL.Add(oper);

                        //推送消息表
                        if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)//1)
                        {
                            var role = new BLL.T_Sys_RoleInfo().GetModelList(" (F_RoleCode='ZXLD' or F_RoleCode='ZXLDGLYGLY')  ").Select(p => p.F_RoleId);
                            var users = userBLL.GetModelList(" F_RoleId in (" + string.Join(",", role) + ")  ");

                            foreach (var u in users)
                            {
                                msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.workorder);
                            }
                        }
                        //调用科大讯飞
                        if (modelT_Bus_WorkOrder.F_InfoSource == 7 && modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)//9)
                        {
                            ShangQiuWorkOrderController sqwo = new ShangQiuWorkOrderController();
                            bool bl = sqwo.SaveReplyInfo(oper.F_WorkOrderId, userModel.F_UserCode, userModel.depname, modelT_Bus_WorkOrder.F_Result, "3", modelT_Bus_WorkOrder.F_InfoType.Value.ToString());
                            if (bl)
                            {
                                Success("调用成功,工单号：" + oper.F_WorkOrderId);
                            }
                            else
                            {
                                Error("调用失败,工单号：" + oper.F_WorkOrderId);
                            }
                        }
                        #endregion

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

                
            }
            else
            {
                return Success("权限不足");
            }
        }
        /// <summary>
        /// 修改工单信息
        /// </summary>       

        /// <returns></returns>
        [Authority]
        public ActionResult UpdateWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "ZXBZ" || userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
              //  string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                int isover = RequestString.GetInt("isover", 0);
                //if (modelT_Bus_WorkOrder != null && (modelT_Bus_WorkOrder.F_WorkState == 1 || modelT_Bus_WorkOrder.F_WorkState == 0))
                if (modelT_Bus_WorkOrder != null && (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealed || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.visit || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish))
                {
                    string newresult = RequestString.GetFormString("newresult");
                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存工单信息

                        modelT_Bus_WorkOrder.F_NewResult = newresult;//


                        workorderBLL.Update(modelT_Bus_WorkOrder);

                        Model.T_Bus_Feedback feedbackmodel = feedbackBLL.GetNewModelByWorkOrderID(workorderid);
                        feedbackmodel.F_ClosingResult = newresult;
                        feedbackBLL.Update(feedbackmodel);
                        #endregion

                        #region 插入操作记录
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                        oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                        oper.F_CallRecordId = modelT_Bus_WorkOrder.F_CallRecordId;
                        oper.F_File = modelT_Bus_WorkOrder.F_File;
                                #region 修改工单记录
                        if (isover==1&& modelT_Bus_WorkOrder.F_WorkState!=9)
                        {
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;
                            modelT_Bus_WorkOrder.F_IsClosed = 1;
                            modelT_Bus_WorkOrder.F_CloseUser = userModel.F_UserCode;
                            modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;
                            modelT_Bus_WorkOrder.F_FinalOpinion = newresult;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                        }
                        #endregion
                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        if (isover==1)
                        {
                            oper.F_Message = userinfo + " 修改办理内容并结案了工单";
                        }
                        else  
                        {
                            oper.F_Message = userinfo + " 修改了办理内容";
                        }
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;
                        operBLL.Add(oper);

                        #endregion

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

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Success("权限不足");
            }
        }
        /// <summary>
        /// 修改工单信息
        /// </summary>       

        /// <returns></returns>
        [Authority]
        public ActionResult UpdateRemarks()
        {
            
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "ZXBZ" || userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                // string workorderid = RequestString.GetFormString("workorderid");
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);

                string workRemarks = RequestString.GetFormString("workRemarks");
                using (TransactionScope trans = new TransactionScope())
                {
                    #region 保存工单信息
                    modelT_Bus_WorkOrder.F_WorkRemarks = workRemarks;//
                    workorderBLL.Update(modelT_Bus_WorkOrder);
                    #endregion

                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    oper.F_CallRecordId = modelT_Bus_WorkOrder.F_CallRecordId;
                    oper.F_File = modelT_Bus_WorkOrder.F_File;
                    #region 修改工单记录

                    #endregion
                    oper.F_Message = " 修改了备注信息:" + workRemarks;
                    oper.F_CreateUser = userModel.F_UserCode;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;
                    operBLL.Add(oper);

                    #endregion

                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Success("权限不足");
            }
        }
        
        /// <summary>
        /// 修改工单信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult EditWorkOrderBySource()
        {

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "ZXBZ" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {

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

                int source = RequestString.GetInt("source", 0);

                string cusname = RequestString.GetFormString("cusname");
                string cussex = RequestString.GetFormString("cussex");
                string cusphone = RequestString.GetFormString("cusphone");
                string cusaddress = RequestString.GetFormString("cusaddress");
                string email = RequestString.GetFormString("email");
                string zipcode = RequestString.GetFormString("zipcode");
                string conname = RequestString.GetFormString("conname");
                string conphone = RequestString.GetFormString("conphone");

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

                int isresult = RequestString.GetInt("isresult", 0);
                string result = RequestString.GetFormString("result");
                string resultremarks = RequestString.GetFormString("resultremarks");
                string keys = RequestString.GetFormString("keys");
                string splituser = RequestString.GetFormString("splituser");

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

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

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                if (modelT_Bus_WorkOrder != null)
                {
                    if (modelT_Bus_WorkOrder.F_IsEnabled == 0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 保存工单信息

                            modelT_Bus_WorkOrder.F_InfoSource = source;//信息来源

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

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

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

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

                            //是否直办（即时答复）0:，否1： 是         
                            modelT_Bus_WorkOrder.F_IsResult = isresult;
                            modelT_Bus_WorkOrder.F_Result = result;//处理结果
                            modelT_Bus_WorkOrder.F_ResultRemarks = resultremarks;
                            //如果选择即刻答复：是，即为直办，工单结束
                            if (isresult == 1)
                            {
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;// 9;//已结案
                                modelT_Bus_WorkOrder.F_DealDeptId = userModel.F_DeptId;
                                modelT_Bus_WorkOrder.F_DealUser = userModel.F_UserCode;
                                modelT_Bus_WorkOrder.F_DealTime = DateTime.Now;
                                modelT_Bus_WorkOrder.F_IsClosed = 1;
                                modelT_Bus_WorkOrder.F_CloseUser = userModel.F_UserCode;
                                modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;
                            }
                            else if (issubmit == 1)
                            {
                                modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;// 1;//提交领导
                            }
                            #region
                            //20190715 去掉审核环节 zhengbingbing
                            //else
                            //{
                            //    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.neworder || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)
                            //        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.audit;
                            //}
                            //20190329
                            //else if (issubmit == 1)
                            //{
                            //    modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                            //    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;// 1;//提交领导
                            //}
                            #endregion
                            modelT_Bus_WorkOrder.F_CreateUser = userModel.F_UserCode;
                            modelT_Bus_WorkOrder.F_IsEnabled = 1;
                            modelT_Bus_WorkOrder.F_EnableTime = DateTime.Now;
                            modelT_Bus_WorkOrder.F_IsDelete = 0;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.neworder || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)//0)
                            {
                                oper.F_Message = userinfo + " 处理了工单";
                            }
                            if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)//1)
                            {
                                oper.F_Message = userinfo + " 处理并提交了工单";
                            }
                            if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)//9)
                            {
                                oper.F_Message = userinfo + " 处理并结案了工单";
                            }

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

                            operBLL.Add(oper);

                            //推送消息表
                            if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)//1)
                            {
                                var role = new BLL.T_Sys_RoleInfo().GetModelList(" (F_RoleCode='ZXLD' or F_RoleCode='ZXLDGLYGLY')  ").Select(p => p.F_RoleId);
                                var users = userBLL.GetModelList(" F_RoleId in (" + string.Join(",", role) + ")  ");

                                foreach (var u in users)
                                {
                                    msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.workorder);
                                }
                            }
                            //调用科大讯飞
                            if (modelT_Bus_WorkOrder.F_InfoSource == 7 && modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)//9)
                            {
                                ShangQiuWorkOrderController sqwo = new ShangQiuWorkOrderController();
                                bool bl = sqwo.SaveReplyInfo(oper.F_WorkOrderId, userModel.F_UserCode, userModel.depname, modelT_Bus_WorkOrder.F_Result, "3", modelT_Bus_WorkOrder.F_InfoType.Value.ToString());
                                if (bl)
                                {
                                    Success("调用成功,工单号：" + oper.F_WorkOrderId);
                                }
                                else
                                {
                                    Error("调用失败,工单号：" + oper.F_WorkOrderId);
                                }
                            }
                            #endregion

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("已经处理过了");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Success("权限不足");
            }
        }

        #region 新增审核工单流程
        /// <summary>
        /// 20190315需求变动，新增审核工单，由组长审核
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult AuditWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel.F_RoleCode == "ZXBZ" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int state = RequestString.GetInt("state", 0);
                string reason = RequestString.GetFormString("reason");

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                if (modelT_Bus_WorkOrder != null)
                {
                    using (TransactionScope trans = new TransactionScope())
                    {

                        if (modelT_Bus_WorkOrder != null)
                        {
                            if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)
                            {
                                var opt = "审核并提交"; var re = "";
                                #region 保存工单信息
                                if (state == 1)
                                {
                                    modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;//待交办
                                }
                                else
                                {
                                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.neworder;
                                    opt = "审核并退回";
                                    re = "，退回原因：" + reason;
                                }
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                #endregion

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

                                string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                oper.F_Message = userinfo + " " + opt + "了工单" + re;
                                oper.F_CreateUser = userModel.F_UserCode;
                                oper.F_CreateTime = DateTime.Now;
                                oper.F_IsDelete = 0;

                                operBLL.Add(oper);

                                //推送消息表
                                //if (modelT_Bus_WorkOrder.F_WorkState == 1)
                                if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)
                                {
                                    var role = new BLL.T_Sys_RoleInfo().GetModelList(" (F_RoleCode='ZXLD' or F_RoleCode='ZXLDGLYGLY')  ").Select(p => p.F_RoleId);
                                    var users = userBLL.GetModelList(" F_RoleId in (" + string.Join(",", role) + ")  ");

                                    foreach (var u in users)
                                    {
                                        msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.workorder);
                                    }
                                }
                                #endregion
                            }

                        }
                        trans.Complete();
                    }

                    return Success("操作成功");
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }
        #endregion
        //  var dtex = DbHelperSQL.Query("update T_Bus_WorkOrder set IsExport=1 where 1=1 " + sql).Tables[0];
       private  thirdController third = new thirdController();
        /// <summary>
        /// 巩义舆情 这个工单删掉 回传工单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult  Sendback(string[] ids,string file,string Result)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

             if (ids != null && ids.Length > 0)
                {
                    foreach (string str in ids)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(str);
                            if (modelT_Bus_WorkOrder != null)
                            {
                            if (string.IsNullOrEmpty(Result))
                                return Error("请输入处理结果");
                          

                            
                           
                                //if (modelT_Bus_WorkOrder.F_WorkState == 0)
                                if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealed || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)
                                {
                                    #region 保存工单信息
                                    modelT_Bus_WorkOrder.IsExport = 1;
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.closed;
                                modelT_Bus_WorkOrder.F_Hcdatetime = DateTime.Now;//回传时间
                                modelT_Bus_WorkOrder.F_HCFiles = file;
                                modelT_Bus_WorkOrder.F_NewResult = Result;
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                //Task.Run(() =>
                                //{
                                //    Thread.Sleep(300000);
                                //    string message = third.HandleWorkOrder(modelT_Bus_WorkOrder, userModel);
                                //});

                                #endregion

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

                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " 回传了工单";
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;

                                    operBLL.Add(oper);

                                    //推送消息表
                                    //if (modelT_Bus_WorkOrder.F_WorkState == 1)

                                    #endregion
                                }
                            
                               

                            }
                            trans.Complete();
                        }
                    }
                    return Success("操作成功");
                }
                else
                {
                    return Error("操作失败");
                }
          
        }
        /// <summary>
        /// 提交工单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult SubmitWorkOrder(string[] ids)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "ZXBZ" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                if (ids != null && ids.Length > 0)
                {
                    foreach (string str in ids)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(str);
                            if (modelT_Bus_WorkOrder != null)
                            {
                                //if (modelT_Bus_WorkOrder.F_WorkState == 0)
                                if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.neworder || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)
                                {
                                    #region 保存工单信息
                                    modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                                    //modelT_Bus_WorkOrder.F_WorkState = 1;//待交办
                                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;//待交办
                                    workorderBLL.Update(modelT_Bus_WorkOrder);
                                    #endregion

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

                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " 提交了工单";
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;

                                    operBLL.Add(oper);

                                    //推送消息表
                                    //if (modelT_Bus_WorkOrder.F_WorkState == 1)
                                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)
                                    {
                                        var role = new BLL.T_Sys_RoleInfo().GetModelList(" (F_RoleCode='ZXLD' or F_RoleCode='ZXLDGLYGLY')  ").Select(p => p.F_RoleId);
                                        var users = userBLL.GetModelList(" F_RoleId in (" + string.Join(",", role) + ")  ");

                                        foreach (var u in users)
                                        {
                                            msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.workorder);
                                        }
                                    }
                                    #endregion
                                }

                            }
                            trans.Complete();
                        }
                    }
                    return Success("操作成功");
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }
        
        /// <summary>
        /// 回退工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult ReturnWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

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

            string backuser = RequestString.GetFormString("backuser");
            string backreason = RequestString.GetFormString("backreason");
            string files = RequestString.GetFormString("files");
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = new BLL.T_Bus_WorkOrder().GetModel(workorderid);
            if (modelT_Bus_WorkOrder != null)
            {
                //if (modelT_Bus_WorkOrder.F_WorkState == 1 || (modelT_Bus_WorkOrder.F_WorkState == 9 && modelT_Bus_WorkOrder.F_IsResult==1))
                if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit || (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish && modelT_Bus_WorkOrder.F_IsResult == 1))
                {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存工单信息
                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.neworder;// 0;
                        //modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.audit;// 0;
                        modelT_Bus_WorkOrder.F_IsResult = 0;
                        modelT_Bus_WorkOrder.F_IsReturn = 1;
                        modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                        modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;
                        workorderBLL.Update(modelT_Bus_WorkOrder);
                        #endregion

                        #region 插入批示记录
                        //批示记录
                        Model.T_Bus_SubmitSuper model_T_Bus_SubmitSuper = new Model.T_Bus_SubmitSuper();
                        model_T_Bus_SubmitSuper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单流水号
                        model_T_Bus_SubmitSuper.F_Type = 3;//1领导批示 2市长指示 3回退
                        model_T_Bus_SubmitSuper.F_BatchReason = backuser;//批示人
                        model_T_Bus_SubmitSuper.F_SuperOpinion = backreason;//批示内容
                        model_T_Bus_SubmitSuper.F_File = files;//附件
                        model_T_Bus_SubmitSuper.F_CreateUser = userModel.F_UserCode;//呈批人
                        model_T_Bus_SubmitSuper.F_CreateTime = DateTime.Now;//呈批时间
                        model_T_Bus_SubmitSuper.F_IsDelete = 0;
                        model_T_Bus_SubmitSuper.F_State = 1;//审批状态（0:未处理，1:通过）
                        new BLL.T_Bus_SubmitSuper().Add(model_T_Bus_SubmitSuper);
                        #endregion

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

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        oper.F_Message = userinfo + " 回退了工单";
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);
                        #endregion

                        trans.Complete();
                    }
                    return Success("操作成功");
                }
                else
                {
                    return Error("已经处理过了");
                }
            }
            else
            {
                return Error("操作失败");
            }
        }

        /// <summary>
        /// 领导批示/市长指示
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult SuperWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

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

            int type = RequestString.GetInt("type", 0);//1领导批示 2市长指示 3转督办
            string superuser = RequestString.GetFormString("superuser");
            string superopinion = RequestString.GetFormString("superopinion");
            string files = RequestString.GetFormString("files");
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
            if (modelT_Bus_WorkOrder != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {

                    #region 保存工单信息 no use
                    //modelT_Bus_WorkOrder.F_WorkState = 2;//领导批示
                    //workorderBLL.Update(modelT_Bus_WorkOrder);
                    #endregion

                    #region 插入批示记录
                    //批示记录
                    Model.T_Bus_SubmitSuper model_T_Bus_SubmitSuper = new Model.T_Bus_SubmitSuper();
                    model_T_Bus_SubmitSuper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单流水号
                    model_T_Bus_SubmitSuper.F_Type = type;//1领导批示 2市长指示
                    model_T_Bus_SubmitSuper.F_BatchReason = superuser;//批示人
                    model_T_Bus_SubmitSuper.F_SuperOpinion = superopinion;//批示内容
                    model_T_Bus_SubmitSuper.F_File = files;//附件
                    model_T_Bus_SubmitSuper.F_CreateUser = userModel.F_UserCode;//呈批人
                    model_T_Bus_SubmitSuper.F_CreateTime = DateTime.Now;//呈批时间
                    model_T_Bus_SubmitSuper.F_IsDelete = 0;
                    model_T_Bus_SubmitSuper.F_State = 1;//审批状态（0:未处理，1:通过）
                    new BLL.T_Bus_SubmitSuper().Add(model_T_Bus_SubmitSuper);
                    #endregion

                    #region 插入操作记录
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                    oper.F_Message = userinfo+ " 批示了工单";
                    oper.F_CreateUser = userModel.F_UserCode;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;

                    operBLL.Add(oper);
                    #endregion

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

        /// <summary>
       
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AssignWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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


            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
              //  string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int state = RequestString.GetInt("state", 0);
                int assignid = RequestString.GetInt("assignid", 0);
                int maindeptid = RequestString.GetInt("maindeptid", 0);
                string otherdeptids = RequestString.GetFormString("otherdeptids");
                DateTime limittime = DateTime.Parse(RequestString.GetFormString("limittime") + " 23:59:59");
                string assignedopinion = RequestString.GetFormString("assignedopinion");

                var modelT_Bus_AssignedInfoLasts = assignBLL.GetList(0, $" F_WorkOrderId='{workorderid}' and F_IsDelete='0' and  F_State='1' ", " F_CreateTime desc").Tables[0];
                if (modelT_Bus_AssignedInfoLasts.Rows.Count > 0)
                {
                    if (modelT_Bus_AssignedInfoLasts.Rows[0]["F_CreateUser"].ToString() != userModel.F_UserCode)
                    {
                        return Error("操作失败");
                    }
                }

                if (!string.IsNullOrEmpty(otherdeptids))
                {
                    if (otherdeptids.Split(',').Contains(maindeptid.ToString()))
                    {
                        return Error("主办单位不能出现在协办单位");
                    }
                }
                if (limittime < DateTime.Now)
                {
                    return Error("办理时限不能小于当前时间");
                }

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                var deptinfo = new BLL.T_Sys_Department().GetModel(maindeptid);
                if (modelT_Bus_WorkOrder != null && deptinfo != null)
                {
                    //if (modelT_Bus_WorkOrder.F_WorkState == 1)
                    //if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)
                    {
                        int aid = 0;
                        using (TransactionScope trans = new TransactionScope())
                        {
                            if (assignid == 0)
                            {
                                #region 插入交办记录
                                modelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                modelT_Bus_AssignedInfo.F_MainDeptId = maindeptid;//主办单位id
                                modelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                                modelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见

                                modelT_Bus_AssignedInfo.F_State = state;//0草稿  1正式
                                modelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                modelT_Bus_AssignedInfo.F_IsDelete = 0;
                                modelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                modelT_Bus_AssignedInfo.F_IsSure = 0;
                                modelT_Bus_AssignedInfo.F_IsReload = 0;
                                modelT_Bus_AssignedInfo.F_IsNext = 0;
                                modelT_Bus_AssignedInfo.F_TimeResp= assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                                aid = assignBLL.Add(modelT_Bus_AssignedInfo);

                                #endregion
                            }
                            else
                            {
                                #region 修改交办记录
                                modelT_Bus_AssignedInfo = assignBLL.GetModel(assignid);
                                if (modelT_Bus_AssignedInfo != null)
                                {
                                    modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                    modelT_Bus_AssignedInfo.F_MainDeptId = maindeptid;//主办单位id
                                    modelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                                    modelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见
                                    modelT_Bus_AssignedInfo.F_TimeResp = assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                                    modelT_Bus_AssignedInfo.F_State = state;//0草稿  1正式
                                    modelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                    modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                    assignBLL.Update(modelT_Bus_AssignedInfo);
                                    aid = modelT_Bus_AssignedInfo.F_Id;
                                }

                                #endregion
                            }

                            if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_State == 1)
                            {
                                #region 保存工单信息
                                //modelT_Bus_WorkOrder.F_WorkState = 2;//待查收
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.receive;//待查收
                                modelT_Bus_WorkOrder.F_LimitTime = limittime;
                                modelT_Bus_WorkOrder.F_Scanning = limittime.AddDays (3);
                                
                                modelT_Bus_WorkOrder.F_MainDeptId = maindeptid;
                                modelT_Bus_WorkOrder.F_OtherDeptIds = otherdeptids;
                                modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                                modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                #endregion

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

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

                                    assignBLL.Update(cg);
                                }
                                #endregion

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

                                string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";

                                oper.F_Message = userinfo + " 交办了工单，主办单位：" + deptinfo.F_DeptName;
                                if (!string.IsNullOrEmpty(otherdeptids))
                                {
                                    string sql = "select dbo.GetDeptNames('" + otherdeptids + "')";
                                    oper.F_Message += "，协办单位：" + DbHelperSQL.GetSingle(sql);
                                }
                                oper.F_CreateUser = userModel.F_UserCode;
                                oper.F_CreateTime = DateTime.Now;
                                oper.F_IsDelete = 0;

                                operBLL.Add(oper);

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

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

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



                                }
                                #endregion
                            }

                            trans.Complete();
                        }
                        return Success("操作成功", modelT_Bus_AssignedInfo.F_Id);
                    }
                    else
                    {
                        return Error("已经交办过了");
                    }
                }
                else
                {
                    return Error("操作失败");
                }

            }
            else
            {
                return Error("权限不足");
            }
        }
        [Authority]
        /// 交办工单
        public ActionResult AssignWorkOrderNew()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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


            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
               // string workorderid = RequestString.GetFormString("workorderid");
                int state = RequestString.GetInt("state", 0);
                int assignid = RequestString.GetInt("assignid", 0);
                string maindeptid = RequestString.GetFormString("maindeptid");
                string otherdeptids = RequestString.GetFormString("otherdeptids");
                DateTime limittime = DateTime.Parse(RequestString.GetFormString("limittime") );
                string assignedopinion = RequestString.GetFormString("assignedopinion");//提示信息



               
                string cusaddress = RequestString.GetFormString("cusaddress");//主要网址F_CusAddress


                string title = RequestString.GetFormString("title");//题目F_ComTitle


                string keys = RequestString.GetFormString("keys");//内容简介F_Key





                var modelT_Bus_AssignedInfoLasts = assignBLL.GetList(0, $" F_WorkOrderId='{workorderid}' and F_IsDelete='0' and  F_State='1' ", " F_CreateTime desc").Tables[0];
                if (modelT_Bus_AssignedInfoLasts.Rows.Count > 0)
                {
                    if (modelT_Bus_AssignedInfoLasts.Rows[0]["F_CreateUser"].ToString() != userModel.F_UserCode)
                    {
                        return Error("操作失败");
                    }
                }

                if (!string.IsNullOrEmpty(otherdeptids))
                {
                    var both = otherdeptids.Split(',').Intersect(maindeptid.Split(','));
                    if (both.Count()>0)
                    //if (otherdeptids.Split(',').Contains(maindeptid.ToString()))
                    {
                        return Error("主办单位不能出现在协办单位");
                    }
                }
                if (limittime < DateTime.Now)
                {
                    return Error("办理时限不能小于当前时间");
                }
                string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_WorkOrder tempT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                var deptlist = new BLL.T_Sys_Department().GetModelList("F_DeptId in (" + maindeptid+")");
                if (modelT_Bus_WorkOrder != null && deptlist != null&& deptlist.Count>0)
                {
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)
                    {
                        int aid = 0; var rre = "";
                        using (TransactionScope trans = new TransactionScope())
                        {
                            if (deptlist.Count == 1)
                            {
                                var deptinfo = deptlist.FirstOrDefault();

                                if (assignid == 0)
                                {
                                    #region 插入交办记录
                                    modelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                    modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                    modelT_Bus_AssignedInfo.F_MainDeptId = deptinfo.F_DeptId;//主办单位id
                                    modelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                                    modelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见

                                    modelT_Bus_AssignedInfo.F_State = state;//0草稿  1正式
                                    modelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                    modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                    modelT_Bus_AssignedInfo.F_IsDelete = 0;
                                    modelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                    modelT_Bus_AssignedInfo.F_IsSure = 0;
                                    modelT_Bus_AssignedInfo.F_IsReload = 0;
                                    modelT_Bus_AssignedInfo.F_IsNext = 0;
                                    modelT_Bus_AssignedInfo.F_TimeResp = assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                                    aid = assignBLL.Add(modelT_Bus_AssignedInfo);

                                    #endregion
                                }
                                else
                                {
                                    #region 修改交办记录
                                    modelT_Bus_AssignedInfo = assignBLL.GetModel(assignid);
                                    if (modelT_Bus_AssignedInfo != null)
                                    {
                                        modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                        modelT_Bus_AssignedInfo.F_MainDeptId = deptinfo.F_DeptId;//主办单位id
                                        modelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                                        modelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见
                                        modelT_Bus_AssignedInfo.F_TimeResp = assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                                        modelT_Bus_AssignedInfo.F_State = state;//0草稿  1正式
                                        modelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                        modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                        assignBLL.Update(modelT_Bus_AssignedInfo);
                                        aid = modelT_Bus_AssignedInfo.F_Id;
                                    }

                                    #endregion
                                }

                                if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_State == 1)
                                {
                                    #region 保存工单信息
                                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.receive;//待查收
                                    modelT_Bus_WorkOrder.F_LimitTime = limittime;
                                    modelT_Bus_WorkOrder.F_Scanning = limittime.AddDays(3);
                                    modelT_Bus_WorkOrder.F_MainDeptId = deptinfo.F_DeptId;
                                    modelT_Bus_WorkOrder.F_OtherDeptIds = otherdeptids;
                                    modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                                    modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;
                                    if (!string .IsNullOrEmpty (cusaddress))
                                        modelT_Bus_WorkOrder.F_CusAddress = cusaddress;
                                    if (!string.IsNullOrEmpty(title))
                                        modelT_Bus_WorkOrder.F_ComTitle = title;
                                    if (!string.IsNullOrEmpty(keys))
                                        modelT_Bus_WorkOrder.F_ComContent = keys;

                                    workorderBLL.Update(modelT_Bus_WorkOrder);
                                    #endregion

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

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

                                        assignBLL.Update(cg);
                                    }
                                    #endregion

                                    #region 插入操作记录
                                    var msgss = userinfo + " 交办了工单，主办单位：" + deptinfo.F_DeptName;
                                    if (!string.IsNullOrEmpty(otherdeptids))
                                    {
                                        string sql = "select dbo.GetDeptNames('" + otherdeptids + "')";
                                        msgss += "，协办单位：" + DbHelperSQL.GetSingle(sql);
                                    }
                                    addoptlog(modelT_Bus_WorkOrder.F_WorkOrderId, modelT_Bus_WorkOrder.F_WorkState, modelT_Bus_AssignedInfo.F_Id, msgss, userModel.F_UserCode);
                                   
                                    //推送消息表
                                    var users = userBLL.GetModelList(" F_DeptId='" + deptinfo.F_DeptId + "' ");

                                    foreach (var u in users)
                                    {//有新提示函【2023第xx号】未查收，请及时查收处理
                                        //msg.AddInternalMessagesInfo("工单消息", msgss + "，工单编号：" + modelT_Bus_WorkOrder.F_WorkOrderId, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.workorder);
                                        msg.AddInternalMessagesInfo("工单消息",  "有新提示函" + modelT_Bus_WorkOrder.F_WorkOrderId+ "未查收，请及时查收处理", u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.attention);
                                        if (!string.IsNullOrEmpty(u.F_Mobile))
                                        {
                                            string count = "你有新的工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                            //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                            //bool  n = new SMSController().AddSmS(1963450, userId, count, mag, u.F_Mobile);
                                            //string mag = "[\"" + modelT_Bus_WorkOrder.F_WorkOrderId + "\"]";
                                            //string v = SMSNewController.AddSmS(userId, count, u.F_Mobile, "1132299838815801344", mag, modelT_Bus_WorkOrder.F_WorkOrderId);
                                            string n = sendjscs(userId, count, u.F_Mobile, modelT_Bus_WorkOrder.F_WorkOrderId);

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

                                        }
                                    }
                                    #endregion
                                }
                            }
                            else
                            {
                                    string newids = ""; string errdeptid = ""; string deptname = "";
                                foreach (var deptmasinfo in deptlist)
                                {
                                    deptname += deptmasinfo.F_DeptName + ",";
                                }
                                int son = 0; string whorkorderid = tempT_Bus_WorkOrder.F_WorkOrderId;

                               
                                foreach (var deptinfo in deptlist)
                                    {
                                    son++;
                                        #region 新增工单
                                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder1 = new Model.T_Bus_WorkOrder();
                                        modelT_Bus_WorkOrder1 = tempT_Bus_WorkOrder;
                                    if (!string.IsNullOrEmpty(cusaddress))
                                        modelT_Bus_WorkOrder1.F_CusAddress = cusaddress;
                                    if (!string.IsNullOrEmpty(title))
                                        modelT_Bus_WorkOrder1.F_ComTitle = title;
                                    if (!string.IsNullOrEmpty(keys))
                                        modelT_Bus_WorkOrder1.F_ComContent = keys;
                                    modelT_Bus_WorkOrder1.F_WorkOrderId = whorkorderid +"-"+ son;
                                    modelT_Bus_WorkOrder1.F_MainWorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                        modelT_Bus_WorkOrder1.F_Id = workorderBLL.Add(modelT_Bus_WorkOrder1);
                                        if (modelT_Bus_WorkOrder1.F_Id <= 0)
                                        {
                                            errdeptid += deptinfo.F_DeptName + ",";
                                            continue;
                                        }
                                        #endregion
                                        #region 交办
                                            #region 插入交办记录
                                            modelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder1.F_WorkOrderId;
                                            modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                            modelT_Bus_AssignedInfo.F_MainDeptId = deptinfo.F_DeptId;//主办单位id
                                            modelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                                            modelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见
                                    modelT_Bus_AssignedInfo.F_TimeResp = assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                                    modelT_Bus_AssignedInfo.F_State = state;//0草稿  1正式
                                            modelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                            modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                            modelT_Bus_AssignedInfo.F_IsDelete = 0;
                                            modelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                            modelT_Bus_AssignedInfo.F_IsSure = 0;
                                            modelT_Bus_AssignedInfo.F_IsReload = 0;
                                            modelT_Bus_AssignedInfo.F_IsNext = 0;
                                            aid = assignBLL.Add(modelT_Bus_AssignedInfo);

                                            #endregion
                                        #endregion
                                        if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_State == 1)
                                        {
                                            #region 保存工单信息
                                            modelT_Bus_WorkOrder1.F_WorkState = (int)EnumWorkState.receive;//待查收
                                            modelT_Bus_WorkOrder1.F_LimitTime = limittime;
                                        modelT_Bus_WorkOrder1.F_Scanning = limittime.AddDays(3);
                                          modelT_Bus_WorkOrder1.F_MainDeptId = deptinfo.F_DeptId;
                                            modelT_Bus_WorkOrder1.F_OtherDeptIds = otherdeptids;
                                            modelT_Bus_WorkOrder1.F_AssignUser = userModel.F_UserCode;
                                            modelT_Bus_WorkOrder1.F_AssignTime = DateTime.Now;
                                            workorderBLL.Update(modelT_Bus_WorkOrder1);
                                            #endregion
                                            #region 删除草稿信息
                                            var cglist = assignBLL.GetModelList(" F_IsDelete=0 and F_State=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder1.F_WorkOrderId + "'");

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

                                                assignBLL.Update(cg);
                                            }
                                            #endregion
                                            #region 插入操作记录
                                            var msgss = userinfo + " 交办了工单，主办单位：" + deptname;
                                            if (!string.IsNullOrEmpty(otherdeptids))
                                            {
                                                string sql = "select dbo.GetDeptNames('" + otherdeptids + "')";
                                                msgss += "，协办单位：" + DbHelperSQL.GetSingle(sql);
                                            }

                                            addoptlog(modelT_Bus_WorkOrder1.F_WorkOrderId, modelT_Bus_WorkOrder1.F_WorkState, modelT_Bus_AssignedInfo.F_Id, msgss, userModel.F_UserCode);

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

                                            foreach (var u in users)
                                            {

                                            //msg.AddInternalMessagesInfo("工单消息", msgss + "，工单编号：" + modelT_Bus_WorkOrder1.F_WorkOrderId, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.workorder);

                                            msg.AddInternalMessagesInfo("工单消息", "有新提示函" + modelT_Bus_WorkOrder1.F_WorkOrderId + "未查收，请及时查收处理", u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.attention);

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

                                            }
                                        }

                                            #endregion
                                        }
                                        newids += modelT_Bus_WorkOrder1.F_WorkOrderId + ",";
                                        //deptname += deptinfo.F_DeptName + ",";
                                }
                                    newids = newids.Trim(','); deptname = deptname.Trim(',');
                                    var msgs = "";
                                    if (errdeptid == "")
                                    {
                                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;//待查收
                                        modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;
                                        modelT_Bus_WorkOrder.F_CloseUser = userModel.F_UserCode;
                                        modelT_Bus_WorkOrder.F_IsDelete = 1;//删除旧工单
                                        workorderBLL.Update(modelT_Bus_WorkOrder);
                                        msgs = userinfo + " 交办多单位，工单编号为：" + newids;
                                    }
                                    else
                                    {
                                        errdeptid = errdeptid.Trim(',');
                                        msgs = userinfo + " 交办的单位有" + deptname + "，部分操作成功，新工单编号为：" + newids + "，交办失败的部门为：" + errdeptid;
                                    }
                                    #region 插入操作记录
                                    addoptlog(modelT_Bus_WorkOrder.F_WorkOrderId, modelT_Bus_WorkOrder.F_WorkState, modelT_Bus_AssignedInfo.F_Id, msgs, userModel.F_UserCode);
                                var WorkOrder = newids.Split(',');
                                if (WorkOrder!=null && WorkOrder.Length >0)
                                {
                                    foreach (var it in WorkOrder)
                                    {
                                        addoptlog(it, modelT_Bus_WorkOrder.F_WorkState, modelT_Bus_AssignedInfo.F_Id, msgs, userModel.F_UserCode);
                                    }
                                }

                                #endregion

                            }
                            trans.Complete();

                            #region
                            if (("," + maindeptid + ",").Contains(",304,"))
                            {
                                var conname = modelT_Bus_WorkOrder.F_CusName; var conphone = modelT_Bus_WorkOrder.F_ConPhone;
                                if(modelT_Bus_WorkOrder.F_IsProtect==1)
                                {
                                    conphone = "保密";
                                    conname= "保密";
                                }
                                rre = new ShangQiuWorkOrderController().SendToGrdding(modelT_Bus_AssignedInfo.F_Id, workorderid, modelT_Bus_WorkOrder.F_ComTitle, modelT_Bus_WorkOrder.F_ComContent, modelT_Bus_WorkOrder.F_SourceAddress, conphone, conname, modelT_Bus_WorkOrder.F_File, userModel.F_UserCode, modelT_Bus_WorkOrder.F_InfoType.Value,modelT_Bus_WorkOrder.F_Latitude.ToString(),modelT_Bus_WorkOrder.F_Longitude.ToString()).ToString();
                            }
                            #endregion
                        }
                        return Success("操作成功"+ rre, modelT_Bus_AssignedInfo.F_Id);
                    }
                    else
                    {
                        return Error("已经交办过了");
                    }
                }
                else
                {
                    return Error("操作失败");
                }

            }
            else
            {
                return Error("权限不足");
            }
        }
        /// <summary>
        /// 二次转派工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult TurnSendWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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


            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
              //  string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int state = RequestString.GetInt("state", 0);
                int assignid = RequestString.GetInt("assignid", 0);
                string maindeptid = RequestString.GetFormString("maindeptid");
                string otherdeptids = RequestString.GetFormString("otherdeptids");
                DateTime limittime = DateTime.Parse(RequestString.GetFormString("limittime"));
                string assignedopinion = RequestString.GetFormString("assignedopinion");


                string cusaddress = RequestString.GetFormString("cusaddress");//主要网址F_CusAddress


                string title = RequestString.GetFormString("title");//题目F_ComTitle


                string keys = RequestString.GetFormString("keys");//内容简介F_Key


                if (!string.IsNullOrEmpty(otherdeptids))
                {
                    var both = otherdeptids.Split(',').Intersect(maindeptid.Split(','));
                    if (both.Count() > 0)
                    //if (otherdeptids.Split(',').Contains(maindeptid.ToString()))
                    {
                        return Error("主办单位不能出现在协办单位");
                    }
                }
                if (limittime < DateTime.Now)
                {
                    return Error("办理时限不能小于当前时间");
                }
                string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_WorkOrder tempT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                var deptlist = new BLL.T_Sys_Department().GetModelList("F_DeptId in (" + maindeptid + ")");
                string newids = ""; string errdeptid = ""; string deptname = "";
                int son = 0; string whorkorderid = tempT_Bus_WorkOrder.F_WorkOrderId;
                
                    try
                    {
                       
                     //   whorkorderid = tempT_Bus_WorkOrder.F_WorkOrderId.Split('-')[0];
                        var workoder = new BLL.T_Bus_WorkOrder().GetModelList($"F_MainWorkOrderId = '{whorkorderid}' " +
                            $"order by F_id   desc ");
                        if (workoder!=null && workoder.Count >0)
                        {
                            son = int.Parse(workoder.FirstOrDefault ().F_WorkOrderId.Split('-')[1]);
                        }
                    }
                    catch
                    {
                        son = 0;
                    }
               
                if (modelT_Bus_WorkOrder != null && deptlist != null && deptlist.Count > 0)
                {
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealing|| modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.receive || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.visit)
                    {
                        int aid = 0; var rre = ""; deptname = "";
                        using (TransactionScope trans = new TransactionScope())
                        {
                            if (deptlist.Count == 1)
                            {
                                son++;
                                var deptinfo = deptlist.FirstOrDefault();
                                deptname = deptinfo.F_DeptName;
                                #region 新增工单
                                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder1 = new Model.T_Bus_WorkOrder();
                                modelT_Bus_WorkOrder1 = tempT_Bus_WorkOrder;
                                modelT_Bus_WorkOrder1.F_LimitTime = limittime;
                                modelT_Bus_WorkOrder1.F_WorkOrderId = whorkorderid+"-"+ son;
                                modelT_Bus_WorkOrder1.F_MainWorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                modelT_Bus_WorkOrder1.F_Files = "";
                                if (!string.IsNullOrEmpty(cusaddress))
                                    modelT_Bus_WorkOrder1.F_CusAddress = cusaddress;
                                if (!string.IsNullOrEmpty(title))
                                    modelT_Bus_WorkOrder1.F_ComTitle = title;
                                if (!string.IsNullOrEmpty(keys))
                                    modelT_Bus_WorkOrder1.F_ComContent = keys;

                                modelT_Bus_WorkOrder1.F_Id = workorderBLL.Add(modelT_Bus_WorkOrder1);
                               
                                #endregion
                                #region 插入交办记录
                                modelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder1.F_WorkOrderId;
                                    modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                    modelT_Bus_AssignedInfo.F_MainDeptId = deptinfo.F_DeptId;//主办单位id
                                    modelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                                    modelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见
                                    //modelT_Bus_AssignedInfo.F_LimitTime = null;//办理时间
                                    modelT_Bus_AssignedInfo.F_State = state;//0草稿  1正式
                                    modelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                    modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                    modelT_Bus_AssignedInfo.F_IsDelete = 0;
                                    modelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                    modelT_Bus_AssignedInfo.F_IsSure = 0;
                                    modelT_Bus_AssignedInfo.F_IsReload = 0;
                                    modelT_Bus_AssignedInfo.F_IsNext = 0;
                                    modelT_Bus_AssignedInfo.F_TimeResp = assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                                    aid = assignBLL.Add(modelT_Bus_AssignedInfo);

                                    #endregion
                                if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_State == 1)
                                {
                                    #region 保存工单信息
                                    modelT_Bus_WorkOrder1.F_WorkState = (int)EnumWorkState.receive;//待查收
                                    modelT_Bus_WorkOrder1.F_LimitTime = limittime;
                                    modelT_Bus_WorkOrder1.F_Scanning = limittime.AddDays(3);
                                    modelT_Bus_WorkOrder1.F_MainDeptId = deptinfo.F_DeptId;
                                    modelT_Bus_WorkOrder1.F_OtherDeptIds = otherdeptids;
                                    modelT_Bus_WorkOrder1.F_AssignUser = userModel.F_UserCode;
                                    modelT_Bus_WorkOrder1.F_AssignTime = DateTime.Now;
                                    modelT_Bus_WorkOrder1.F_DealTime = null;
                                    workorderBLL.Update(modelT_Bus_WorkOrder1);
                                    newids += ',' + modelT_Bus_WorkOrder1.F_WorkOrderId;
                                    #endregion

                                    #region 删除草稿信息

                                    #endregion

                                    #region 插入操作记录
                                    var msgss = userinfo +"原工单"+ modelT_Bus_WorkOrder.F_WorkOrderId + " 二次转派交办了工单，主办单位：" + deptinfo.F_DeptName;
                                    if (!string.IsNullOrEmpty(otherdeptids))
                                    {
                                        string sql = "select dbo.GetDeptNames('" + otherdeptids + "')";
                                        msgss += "，协办单位：" + DbHelperSQL.GetSingle(sql);
                                    }
                                    addoptlog(modelT_Bus_WorkOrder1.F_WorkOrderId, modelT_Bus_WorkOrder1.F_WorkState, modelT_Bus_AssignedInfo.F_Id, msgss, userModel.F_UserCode);

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

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

                                        }
                                    }
                                    #endregion
                                }
                                var msgss1 = userinfo + "原工单" + modelT_Bus_WorkOrder.F_WorkOrderId + " 二次转派交办了工单，主办单位：" + deptinfo.F_DeptName;
                                addoptlog(modelT_Bus_WorkOrder.F_WorkOrderId, modelT_Bus_WorkOrder1.F_WorkState, modelT_Bus_AssignedInfo.F_Id, msgss1, userModel.F_UserCode);

                            }
                            else
                            {
                                foreach (var deptmasinfo in deptlist)
                                {
                                    deptname += deptmasinfo.F_DeptName + ",";
                                }

                                foreach (var deptinfo in deptlist)
                                {
                                    son++;
                                    //deptname += deptinfo.F_DeptName + ",";
                                    #region 新增工单
                                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder1 = new Model.T_Bus_WorkOrder();
                                    modelT_Bus_WorkOrder1 = tempT_Bus_WorkOrder;
                                    modelT_Bus_WorkOrder1.F_WorkOrderId = whorkorderid+"-"+son ;
                                    modelT_Bus_WorkOrder1.F_MainWorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                    modelT_Bus_WorkOrder1.F_Id = workorderBLL.Add(modelT_Bus_WorkOrder1);
                                    if (modelT_Bus_WorkOrder1.F_Id <= 0)
                                    {
                                        errdeptid += deptinfo.F_DeptName + ",";
                                        continue;
                                    }
                                    #endregion
                                    #region 交办
                                    #region 插入交办记录
                                    modelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder1.F_WorkOrderId;
                                    modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                    modelT_Bus_AssignedInfo.F_MainDeptId = deptinfo.F_DeptId;//主办单位id
                                    modelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                                    modelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见
                                    modelT_Bus_AssignedInfo.F_TimeResp = assignBLL.GetRepTimly(DateTime.Now);//及时查收时间点
                                    modelT_Bus_AssignedInfo.F_State = state;//0草稿  1正式
                                    modelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                    modelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                    modelT_Bus_AssignedInfo.F_IsDelete = 0;
                                    modelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                    modelT_Bus_AssignedInfo.F_IsSure = 0;
                                    modelT_Bus_AssignedInfo.F_IsReload = 0;
                                    modelT_Bus_AssignedInfo.F_IsNext = 0;
                                    aid = assignBLL.Add(modelT_Bus_AssignedInfo);

                                    #endregion
                                    #endregion
                                    if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_State == 1)
                                    {
                                        #region 保存工单信息
                                        modelT_Bus_WorkOrder1.F_WorkState = (int)EnumWorkState.receive;//待查收
                                        modelT_Bus_WorkOrder1.F_LimitTime = limittime;
                                        modelT_Bus_WorkOrder1.F_Scanning = limittime.AddDays(3);
                                        modelT_Bus_WorkOrder1.F_MainDeptId = deptinfo.F_DeptId;
                                        modelT_Bus_WorkOrder1.F_OtherDeptIds = otherdeptids;
                                        modelT_Bus_WorkOrder1.F_AssignUser = userModel.F_UserCode;
                                        modelT_Bus_WorkOrder1.F_AssignTime = DateTime.Now;
                                        workorderBLL.Update(modelT_Bus_WorkOrder1);
                                        #endregion
                                        #region 删除草稿信息
                                       
                                        #endregion
                                        #region 插入操作记录
                                        var msgss = userinfo + " 交办了工单，主办单位：" + deptname;
                                        if (!string.IsNullOrEmpty(otherdeptids))
                                        {
                                            string sql = "select dbo.GetDeptNames('" + otherdeptids + "')";
                                            msgss += "，协办单位：" + DbHelperSQL.GetSingle(sql);
                                        }

                                        addoptlog(modelT_Bus_WorkOrder1.F_WorkOrderId, modelT_Bus_WorkOrder1.F_WorkState, modelT_Bus_AssignedInfo.F_Id, msgss, userModel.F_UserCode);

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

                                        foreach (var u in users)
                                        {

                                            msg.AddInternalMessagesInfo("工单消息", msgss + "，工单编号：" + modelT_Bus_WorkOrder1.F_WorkOrderId, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.workorder);
                                            if (!string.IsNullOrEmpty(u.F_Mobile))
                                            {
                                                string count = "你有新的工单，工单号" + modelT_Bus_WorkOrder1.F_WorkOrderId + ",请及时查收。";
                                                //string[] mag = { modelT_Bus_WorkOrder1.F_WorkOrderId };
                                                //bool n = new SMSController().AddSmS(1963450, userId, count, mag, u.F_Mobile);
                                                string n = sendjscs(userId, count, u.F_Mobile, modelT_Bus_WorkOrder1.F_WorkOrderId);
                                            }
                                            if (!string.IsNullOrEmpty(u.F_Telephone))
                                            {
                                                var userlist = u.F_Telephone.Split(',');
                                                if (userlist != null)
                                                {
                                                    string count = "你有新的工单，工单号" + modelT_Bus_WorkOrder1.F_WorkOrderId + ",请及时查收。";
                                                    //string[] mag = { modelT_Bus_WorkOrder1.F_WorkOrderId };
                                                    //bool n = new SMSController().AddSmSGroup(1963450, userId, count, mag, userlist, u.F_Telephone);
                                                    string n = sendjscs(userId, count, u.F_Telephone, modelT_Bus_WorkOrder1.F_WorkOrderId);
                                                }

                                            }
                                        }

                                        #endregion
                                    }
                                    newids += modelT_Bus_WorkOrder1.F_WorkOrderId + ",";

                                }
                                newids = newids.Trim(','); deptname = deptname.Trim(',');
                                var msgs = "";
                                if (errdeptid == "")
                                {
                                    //modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;//待查收
                                    //modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;
                                    //modelT_Bus_WorkOrder.F_CloseUser = userModel.F_UserCode;
                                    //modelT_Bus_WorkOrder.F_IsDelete = 1;//删除旧工单
                                    //workorderBLL.Update(modelT_Bus_WorkOrder);
                                    msgs = userinfo + " 二次转派交办了工单，工单编号为：" + newids;
                                }
                                else
                                {
                                    errdeptid = errdeptid.Trim(',');
                                    msgs = userinfo + " 交办的单位有" + deptname + "，部分操作成功，新工单编号为：" + newids + "，交办失败的部门为：" + errdeptid;
                                }
                                #region 插入操作记录
                                var msgss1 = userinfo + " 二次转派交办了工单，主办单位：" + deptname;
                                addoptlog(modelT_Bus_WorkOrder.F_WorkOrderId, modelT_Bus_WorkOrder.F_WorkState, modelT_Bus_AssignedInfo.F_Id, msgss1, userModel.F_UserCode);
                                addoptlog(modelT_Bus_WorkOrder.F_WorkOrderId, modelT_Bus_WorkOrder.F_WorkState, modelT_Bus_AssignedInfo.F_Id, msgs, userModel.F_UserCode);
                                var WorkOrder = newids.Split(',');
                                if (WorkOrder != null && WorkOrder.Length > 0)
                                {
                                    foreach (var it in WorkOrder)
                                    {
                                        addoptlog(it, modelT_Bus_WorkOrder.F_WorkState, 0, msgs, userModel.F_UserCode);
                                    }
                                }

                                #endregion

                            }
                            trans.Complete();

                            #region
                            if (("," + maindeptid + ",").Contains(",304,"))
                            {
                                var conname = modelT_Bus_WorkOrder.F_CusName; var conphone = modelT_Bus_WorkOrder.F_ConPhone;
                                if (modelT_Bus_WorkOrder.F_IsProtect == 1)
                                {
                                    conphone = "保密";
                                    conname = "保密";
                                }
                                rre = new ShangQiuWorkOrderController().SendToGrdding(modelT_Bus_AssignedInfo.F_Id, workorderid, modelT_Bus_WorkOrder.F_ComTitle, modelT_Bus_WorkOrder.F_ComContent, modelT_Bus_WorkOrder.F_SourceAddress, conphone, conname, modelT_Bus_WorkOrder.F_File, userModel.F_UserCode, modelT_Bus_WorkOrder.F_InfoType.Value, modelT_Bus_WorkOrder.F_Latitude.ToString(), modelT_Bus_WorkOrder.F_Longitude.ToString()).ToString();
                            }
                            #endregion
                        }
                        return Success("操作成功" + rre, modelT_Bus_AssignedInfo.F_Id);
                    }
                    else
                    {
                        return Error("已经交办过了");
                    }
                }
                else
                {
                    return Error("操作失败");
                }

            }
            else
            {
                return Error("权限不足");
            }
        }



        /// <summary>
        /// 工单提醒
        /// </summary>
        /// <param name="workordercode"></param>
        /// <param name="deptid"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SendSms(string workordercode,string  deptid,int type=0,int isfs=0)
        {
            if (string .IsNullOrEmpty (deptid))
                return Error("请选择部门");

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            string msg = "";
            try
            {
                var deptsprit = deptid.Split(',');
                if (deptsprit != null)
                {
                    foreach (var iv in deptsprit)
                    {
                        var dept = new BLL.T_Sys_Department().GetModel(int.Parse(iv));
                        if (dept.F_IsSms==1|| isfs==1)
                        {
                            var user = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId=" + iv + "and F_DeleteFlag=0");
                            if (user != null)
                            {
                                foreach (var it in user)
                                {
                                    if (!string.IsNullOrEmpty(it.F_Mobile))
                                    {
                                        string count = "";
                                        string templetid = "";
                                        if (type == 0)
                                        {
                                            templetid = "43683";
                                            count = "您有新的工单，请及时查收处理，工单编号"+ workordercode + "，（如通过手机APP登陆，若待查收中无工单，请注意查看重办中列表）" ;
                                        }
                                        else if (type == 1)
                                        {
                                            templetid = "26155";
                                            count = "您有工单正在被督办，请及时处理，工单编号" + workordercode;
                                        }
                                        else if (type == 2)
                                        {
                                            templetid = "26154";
                                            count = "您有紧急工单，请及时处理，工单编号" + workordercode;
                                        }
                                        else
                                        {
                                            templetid = "29265";
                                            count = "您有工单已经超时，请尽快处理，工单编号" + workordercode;
                                        }

                                   //   bool n = SMSController.AddSmS(userId, count, workordercode, it.F_Mobile, templetid);
                                      //  if (n == false)
                                            msg += it.F_UserName + "发送短信失败。";
                                    }
                                }
                               
                            }
                        }
                    }
                }
            }
            catch
            {
                return Error("发送失败");
            }
            if (msg != "")
                return Error(msg);
            else
                return Success("发送成功");
            return Error("暂无人员");
        }
        /// <summary>
        /// 办理结果通知
        /// </summary>
        /// <param name="msg1"></param>
        /// <param name="msg2"></param>
        /// <param name="msg3"></param>
        /// <param name="msg4"></param>
        /// <param name="mobile"></param>
        /// <returns></returns>

        public ActionResult SmsHand(string msg1 , string msg2 , string msg3,string msg4,string mobile)
        {
            
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            string msg = msg1+","+ msg2 + "," + msg3 + "," + msg4;

            string count = "尊敬的市民，您于" + msg1 + "反映的" + msg2 + "问题，工单号：" + msg3 + "，处理结果如下：" + msg4 + "。如有异议，请您再次致电12345，感谢您的支持。";


         //   bool n = SMSController.AddSmS(userId, count, msg, mobile, "26213");
         //   if (n)
                return Success("发送成功");
         //   else
               // return Error ("发送失败");
        }
     
       public ActionResult SmsOverTime(int Sms=0)
         {
            List<T_Bus_WorkOrder> workorder = new List<T_Bus_WorkOrder>();
            
              workorder = new BLL.T_Bus_WorkOrder().GetModelList("F_IsDelete=0 and  F_WorkState in (2,4) and (F_IsSms<"+ 3 + " or  F_IsSms is null)");
           
            if (workorder != null&& workorder.Count >0)
            {
                foreach (var it in workorder)
                {
                   
                    System.TimeSpan time = DateTime.Parse(it.F_LimitTime.ToString()) - DateTime.Now ;
                    if (time.TotalHours <= -24)
                    {

                        int  ivn = int.Parse(string.Format("{0:f0}", time.TotalHours / 24));
                        if ((ivn + 2) > it.F_IsSms)
                        {
                            if (it.F_IsSms < 3 )
                            {
                                var user = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId=" + it.F_MainDeptId + "and F_DeleteFlag=0");
                                if (user != null)
                                {
                                    foreach (var iv in user)
                                    {
                                        msg.AddInternalMessagesInfo("催单消息", "您有工单已超期"+string .Format ("{0:f0}", ivn*24) +"小时，请及时处理，工单号" + it.F_WorkOrderId, iv.F_UserCode, "8000", (int)EnumSmsType.additional);
                                        if (!string.IsNullOrEmpty(iv.F_Mobile))
                                        {

                                            //   string count = " 您有工单已超期24小时，请及时处理，工单号" + it.F_WorkOrderId;
                                            string count = "你有工单" + it.F_WorkOrderId + "已超期" + string.Format("{0:f0}", ivn * 24) + "小时，请及时处理";
                                            //string[] mag = { it.F_WorkOrderId, "" + string.Format("{0:f0}", ivn * 24) + "小时" };
                                            //bool n = new SMSController().AddSmS(1963443, 0, count, mag, iv.F_Mobile);

                                            string n = sendcqtx(0, count, iv.F_Mobile, it.F_WorkOrderId, ivn * 24);
                                            it.F_IsSms = ivn + 2;
                                            bool t = new BLL.T_Bus_WorkOrder().Update(it);

                                        }
                                        if (!string.IsNullOrEmpty(iv.F_Telephone))
                                        {
                                            var userlist = iv.F_Telephone.Split(',');
                                            if (userlist != null)
                                            {
                                                foreach (var io in userlist)
                                                {
                                                    string count = "你有工单" + it.F_WorkOrderId + "已超期" + string.Format("{0:f0}", ivn * 24) + "小时，请及时处理";
                                                    //string[] mag = { it.F_WorkOrderId, "" + string.Format("{0:f0}", ivn * 24) + "小时" };
                                                    //bool n = new SMSController().AddSmS(1963443, 0, count, mag, io);

                                                    string n = sendcqtx(0, count, io, it.F_WorkOrderId, ivn * 24);
                                                    it.F_IsSms = ivn + 2;
                                                    bool t = new BLL.T_Bus_WorkOrder().Update(it);
                                                }
                                            }
                                            //   string count = " 您有工单已超期24小时，请及时处理，工单号" + it.F_WorkOrderId;


                                        }

                                    }
                                }
                            }
                        }
                         
                    }
                    else if (time.TotalHours <= 1)
                    {
                        if (it.F_IsSms < 2 )
                        {
                            var user = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId=" + it.F_MainDeptId + "and F_DeleteFlag=0");
                            if (user != null)
                            {
                                foreach (var iv in user)
                                {
                                    msg.AddInternalMessagesInfo("催单消息", "您有工单1小时后超期，请及时处理，工单号" + it.F_WorkOrderId, iv.F_UserCode, "8000", (int)EnumSmsType.additional);
                                    if (!string.IsNullOrEmpty(iv.F_Mobile))
                                    {
                                        string count = "你有工单" + it.F_WorkOrderId + ",1小时后超期,请及时处理";
                                        //string[] mag = { it.F_WorkOrderId+ ",1" };
                                        //bool n = new SMSController().AddSmS(1963446, 0, count, mag, iv.F_Mobile);
                                        //string mag = "[\"" + it.F_WorkOrderId + "\",\"" + 1 + "\"]";
                                        // string v = SMSNewController.AddSmS(0, count, iv.F_Mobile, "1132299811154366464", mag, it.F_WorkOrderId);
                                        string v = sendjjcq(0, count, iv.F_Mobile, it.F_WorkOrderId, 1);


                                        it.F_IsSms = 2;
                                        bool t = new BLL.T_Bus_WorkOrder().Update(it);
                                    }
                                    if (!string.IsNullOrEmpty(iv.F_Telephone ))
                                    {
                                        var userlist = iv.F_Telephone.Split(',');
                                        if (userlist != null)
                                        {
                                            foreach (var io in userlist)
                                            {
                                                string count = "你有工单" + it.F_WorkOrderId + ",1小时后超期,请及时处理";
                                                //string[] mag = { it.F_WorkOrderId + ",1" };
                                                //bool n = new SMSController().AddSmS(1963446, 0, count, mag, io );
                                                //string mag = "[\"" + it.F_WorkOrderId + "\",\"" + 1 + "\"]";
                                                //string v = SMSNewController.AddSmS(0, count, io, "1132299811154366464", mag, it.F_WorkOrderId);
                                                string v = sendjjcq(0, count, io, it.F_WorkOrderId, 1);
                                                it.F_IsSms = 2;
                                                bool t = new BLL.T_Bus_WorkOrder().Update(it);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (time.TotalHours <= 4)
                    {
                        if (it.F_IsSms < 1 )
                        {
                            var user = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId=" + it.F_MainDeptId + "and F_DeleteFlag=0");
                            if (user != null)
                            {
                                foreach (var iv in user)
                                {
                                    msg.AddInternalMessagesInfo("催单消息", "您有工单4小时后超期，请及时处理，工单号" + it.F_WorkOrderId, iv.F_UserCode, "8000", (int)EnumSmsType.additional);
                                    if (!string.IsNullOrEmpty(iv.F_Mobile))
                                    {
                                        string count = "你有工单" + it.F_WorkOrderId + ",4小时后超期,请及时处理";
                                        //string[] mag = { it.F_WorkOrderId + ",4" };
                                        //bool n = new SMSController().AddSmS(1963446, 0, count, mag, iv.F_Mobile);
                                        //string mag = "[\"" + it.F_WorkOrderId + "\",\"" + 4 + "\"]";
                                        //string v = SMSNewController.AddSmS(0, count, iv.F_Mobile, "1132299811154366464", mag, it.F_WorkOrderId);

                                        string v = sendjjcq(0, count, iv.F_Mobile, it.F_WorkOrderId, 4);

                                        it.F_IsSms = 1;
                                        bool t = new BLL.T_Bus_WorkOrder().Update(it);
                                    }
                                    if (!string.IsNullOrEmpty(iv.F_Telephone ))
                                    {
                                        var userlist = iv.F_Telephone.Split(',');
                                        if (userlist != null)
                                        {
                                            foreach (var io in userlist)
                                            {
                                                string count = "你有工单" + it.F_WorkOrderId + ",4小时后超期,请及时处理";
                                                //string[] mag = { it.F_WorkOrderId + ",4" };
                                                //bool n = new SMSController().AddSmS(1963446, 0, count, mag, io );
                                                //string mag = "[\"" + it.F_WorkOrderId + "\",\"" + 4 + "\"]";
                                                //string v = SMSNewController.AddSmS(0, count, io, "1132299811154366464", mag, it.F_WorkOrderId);

                                                string v = sendjjcq(0, count, io, it.F_WorkOrderId, 4);
                                                it.F_IsSms = 1;
                                                bool t = new BLL.T_Bus_WorkOrder().Update(it);
                                            }
                                        }
                                        //   string count = " 您有工单已超期24小时，请及时处理，工单号" + it.F_WorkOrderId;
                                       
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return Success("发送成功");
        }


        /// <summary>
        /// 市长办使用人员可以对需要催办的转办件进行短信催办或系统催办系统  20220315
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult Reminders(string workorderid)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            //int userId = 133;
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            
            if (userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "ZXLD")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                var womodel = workorderBLL.GetModel(workorderid);
                var assignmodel = assignBLL.GetNewModelByWorkOrderID(workorderid);
                if (womodel != null && assignmodel != null)
                {
                    if (assignmodel.F_IsNext == 1 || assignmodel.F_IsNext == 2)
                    {
                        Model.T_Bus_AssignedInfo_Next assign_next = new BLL.T_Bus_AssignedInfo_Next().GetNewModelByWorkOrderID(workorderid);
                        var user = new BLL.T_Sys_UserAccount().GetModelList("F_DeptId=" + (assign_next.F_MainDeptId ?? 0) + " and F_DeleteFlag=0");
                        if (user != null)
                        {
                            foreach (var item in user)
                            {
                                msg.AddInternalMessagesInfo("催单消息", "您的工单" + workorderid + "收到催办，请及时处理！", item.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.additional);
                                if (!string.IsNullOrEmpty(item.F_Mobile))
                                {
                                    string count = "你有工单" + womodel.F_WorkOrderId + "收到催办,请及时处理";
                                    //string[] mag = { womodel.F_WorkOrderId };
                                    //bool n = new SMSController().AddSmS(1963438, 0, count, mag, item.F_Mobile);

                                    string n = sendcbtx(0, count, item.F_Mobile, womodel.F_WorkOrderId);

                                }
                                if (!string.IsNullOrEmpty(item.F_Telephone))
                                {
                                    var phonlist = item.F_Telephone.Split(',');
                                    if (phonlist.Count() > 0)
                                    {
                                        foreach (var phon in phonlist)
                                        {
                                            string count = "你有工单" + womodel.F_WorkOrderId + "收到催办,请及时处理";
                                            //string[] mag = { womodel.F_WorkOrderId };
                                            //bool n = new SMSController().AddSmS(1963438, 0, count, mag, phon);

                                            string n = sendcbtx(0, count, phon, womodel.F_WorkOrderId);
                                        }
                                    }
                                }
                            }
                            womodel.ReminderNum += 1;
                            bool t = new BLL.T_Bus_WorkOrder().Update(womodel);
                            #region 插入操作记录
                            Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                            oper.F_WorkOrderId = womodel.F_WorkOrderId;
                            oper.F_State = womodel.F_WorkState;

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 催办工单";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;
                            operBLL.Add(oper);
                            #endregion
                        }
                    }
                    else
                    {
                        var user = new BLL.T_Sys_UserAccount().GetModelList("F_DeptId=" + womodel.F_MainDeptId ?? 0 + " and F_DeleteFlag=0");
                        if (user != null)
                        {
                            foreach (var item in user)
                            {
                                msg.AddInternalMessagesInfo("催办提醒", "【催办】提示函" + workorderid + "未处理，请及时处理", item.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.attention);
                                if (!string.IsNullOrEmpty(item.F_Mobile))
                                {
                                    string count = "您有工单" + womodel.F_WorkOrderId + "收到催办，请及时处理";
                                    //string[] mag = { womodel.F_WorkOrderId };
                                    //bool n = new SMSController().AddSmS(1963438, 0, count, mag, item.F_Mobile);

                                    string n = sendcbtx(0, count, item.F_Mobile, womodel.F_WorkOrderId);
                                }
                                if (!string.IsNullOrEmpty(item.F_Telephone))
                                {
                                    var phonlist = item.F_Telephone.Split(',');
                                    if (phonlist.Count() > 0)
                                    {
                                        foreach (var phon in phonlist)
                                        {
                                            string count = "您有工单" + womodel.F_WorkOrderId + "收到催办，请及时处理";
                                            //string[] mag = { womodel.F_WorkOrderId };
                                            //bool n = new SMSController().AddSmS(1963438, 0, count, mag, phon);

                                            string n = sendcbtx(0, count, phon, womodel.F_WorkOrderId);
                                        }
                                    }
                                }
                            }
                            womodel.ReminderNum += 1;
                            bool t = new BLL.T_Bus_WorkOrder().Update(womodel);

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 催办工单";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;
                            operBLL.Add(oper);
                            #endregion
                        }

                    }
                    return Success("催单成功！");
                }
                else return Error("操作失败");
            }
            else
                return Error("权限不足！");

        }
        /// <summary>
        /// 收回工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult TakeBackWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");

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

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null)
                {
                    if (modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                    {
                        return Error("操作失败");
                    }

                    //if (modelT_Bus_AssignedInfo.F_IsSure == 0 || (modelT_Bus_AssignedInfo.F_IsSure == 1 && modelT_Bus_WorkOrder.F_WorkState == 4))
                    if (modelT_Bus_AssignedInfo.F_IsSure == 0 || (modelT_Bus_AssignedInfo.F_IsSure == 1 && modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealing))
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 插入交办记录
                            Model.T_Bus_AssignedInfo AssignedInfo = new Model.T_Bus_AssignedInfo();
                            AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                            AssignedInfo.F_LimitTime = modelT_Bus_AssignedInfo.F_LimitTime;//办理时限
                            AssignedInfo.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;//主办单位id
                            AssignedInfo.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;//协办单位id
                            AssignedInfo.F_AssignedOpinion = modelT_Bus_AssignedInfo.F_AssignedOpinion;//交办意见

                            AssignedInfo.F_State = 0;//0草稿  1正式
                            AssignedInfo.F_CreateUser = modelT_Bus_AssignedInfo.F_CreateUser;
                            AssignedInfo.F_CreateTime = modelT_Bus_AssignedInfo.F_CreateTime;
                            AssignedInfo.F_IsDelete = 0;
                            AssignedInfo.F_IsOverdue = 0;
                            AssignedInfo.F_IsSure = 0;
                            AssignedInfo.F_IsReload = 0;
                            AssignedInfo.F_IsNext = 0;

                            assignBLL.Add(AssignedInfo);

                            #endregion

                            #region 保存工单信息
                            //modelT_Bus_WorkOrder.F_WorkState = 1;//待交办
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;//待交办
                            modelT_Bus_WorkOrder.F_MainDeptId = null;
                            modelT_Bus_WorkOrder.F_OtherDeptIds = "";
                            modelT_Bus_WorkOrder.ReminderNum = 0;//清空催办记录
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

                            #region 删除交办信息
                            modelT_Bus_AssignedInfo.F_State  = 0;
                           
                            assignBLL.Update(modelT_Bus_AssignedInfo);
                            #endregion

                            #region 删除派单信息
                           var pdlist = new BLL.T_Bus_AssignedInfo_Next().GetModelList(" F_IsDelete=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' ");

                            foreach (var cg in pdlist)
                            {
                                //cg.F_IsDelete = 1;
                                //cg.F_DeleteUser = userModel.F_UserCode;
                                //cg.F_DeleteTime = DateTime.Now;
                                cg.F_State = 0;
                                new BLL.T_Bus_AssignedInfo_Next().Update(cg);
                            }
                            #endregion

                            #region 删除二级单位处理信息
                            var cglist = new BLL.T_Bus_Feedback_Next().GetModelList(" F_IsDelete=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' ");

                            foreach (var cg in cglist)
                            {
                               // cg.F_IsDelete = 1;
                               // cg.F_DeleteUser = userModel.F_UserCode;
                               // cg.F_DeleteTime = DateTime.Now;
                                cg.F_State = 0;
                               new BLL.T_Bus_Feedback_Next().Update(cg);
                            }
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 收回了工单";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);
                            #endregion

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("单位已查收，不能收回");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }







        /// <summary>
        /// 上报工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult Escalation()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "WLDW" )
            {
                //  string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null)
                {
                    if (modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                    {
                        return Error("操作失败");
                    }

                    //if (modelT_Bus_AssignedInfo.F_IsSure == 0 || (modelT_Bus_AssignedInfo.F_IsSure == 1 && modelT_Bus_WorkOrder.F_WorkState == 4))
                    if (modelT_Bus_AssignedInfo.F_IsSure == 0 || (modelT_Bus_AssignedInfo.F_IsSure == 1 && modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealing))
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                           

                            #region 保存工单信息
                            //modelT_Bus_WorkOrder.F_WorkState = 1;//待交办
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;//待交办
                            modelT_Bus_WorkOrder.F_MainDeptId = null;
                            modelT_Bus_WorkOrder.F_OtherDeptIds = "";
                            modelT_Bus_WorkOrder.ReminderNum = 0;//清空催办记录
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

                            #region 删除交办信息
                            modelT_Bus_AssignedInfo.F_State = 0;

                            assignBLL.Update(modelT_Bus_AssignedInfo);
                            #endregion

                            #region 删除派单信息
                            var pdlist = new BLL.T_Bus_AssignedInfo_Next().GetModelList
                                (" F_IsDelete=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' ");

                            foreach (var cg in pdlist)
                            {
                                cg.F_State = 0;
                                new BLL.T_Bus_AssignedInfo_Next().Update(cg);
                            }
                            #endregion

                            #region 删除二级单位处理信息
                            var cglist = new BLL.T_Bus_Feedback_Next().GetModelList(" F_IsDelete=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' ");

                            foreach (var cg in cglist)
                            {
                                cg.F_State = 0;
                                new BLL.T_Bus_Feedback_Next().Update(cg);
                            }
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 上报了工单";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);
                            #endregion

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("单位已查收，不能收回");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 查收工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult ReceiveWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "WLDW")
            {
               // string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

                //操作前新增判断状态
                //if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_MainDeptId == userModel.F_DeptId)
                if (modelT_Bus_WorkOrder != null && (modelT_Bus_WorkOrder.F_WorkState==(int)EnumWorkState.receive|| modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.reload) && modelT_Bus_AssignedInfo != null && (modelT_Bus_AssignedInfo.F_MainDeptId == userModel.F_DeptId || userModel.F_RoleCode == "GLY"))
                {
                    if (modelT_Bus_AssignedInfo.F_IsSure == 0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 保存工单信息
                            modelT_Bus_WorkOrder.F_WorkState = 4;//办理中
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion
                            #region 保存查收信息
                            modelT_Bus_AssignedInfo.F_IsSure = 1;//查收
                            modelT_Bus_AssignedInfo.F_SureUser = userModel.F_UserCode;
                            modelT_Bus_AssignedInfo.F_SureTime = DateTime.Now;
                            assignBLL.Update(modelT_Bus_AssignedInfo);
                            #endregion

                            #region 保存明细信息
                            if (!string.IsNullOrEmpty(modelT_Bus_AssignedInfo.F_OtherDeptIds))
                            {
                                string[] strids = modelT_Bus_AssignedInfo.F_OtherDeptIds.Split(',');
                                foreach (string strid in strids)
                                {
                                    Model.T_Bus_AssignedItemInfo modelT_Bus_AssignedItemInfo = new Model.T_Bus_AssignedItemInfo();
                                    modelT_Bus_AssignedItemInfo.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                                    modelT_Bus_AssignedItemInfo.F_AssignedOpinion = modelT_Bus_AssignedInfo.F_AssignedOpinion;
                                    modelT_Bus_AssignedItemInfo.F_DeptId = Int32.Parse(strid);
                                    modelT_Bus_AssignedItemInfo.F_LimitTime = modelT_Bus_AssignedInfo.F_LimitTime;
                                    modelT_Bus_AssignedItemInfo.F_Remark = modelT_Bus_AssignedInfo.F_Remark;
                                    modelT_Bus_AssignedItemInfo.F_State = 1;
                                    modelT_Bus_AssignedItemInfo.F_Type = 2;
                                    modelT_Bus_AssignedItemInfo.F_WorkOrderId = modelT_Bus_AssignedInfo.F_WorkOrderId;
                                    modelT_Bus_AssignedItemInfo.F_IsSure = 0;
                                    modelT_Bus_AssignedItemInfo.F_CreateTime = DateTime.Now;
                                    modelT_Bus_AssignedItemInfo.F_CreateUser = userModel.F_UserCode;
                                    modelT_Bus_AssignedItemInfo.F_IsDelete = 0;

                                    new BLL.T_Bus_AssignedItemInfo().Add(modelT_Bus_AssignedItemInfo);

                                }
                            }
                            #endregion
                            if(modelT_Bus_WorkOrder.F_IsEnabled ==2)
                            {
                                third.updateProgress(modelT_Bus_WorkOrder.F_WorkOrderId );
                            }


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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 查收了工单";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);
                            #endregion

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("单位已查收，不能再次查收");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                //return Error("权限不足");
                return Success("操作成功！");
            }
        }

        /// <summary>
        /// 退回工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult RebackWorkOrder()
        {

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
              //  string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));

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

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_MainDeptId == userModel.F_DeptId) 
                {
                    if (modelT_Bus_AssignedInfo.F_IsSure == 0|| modelT_Bus_AssignedInfo.F_IsSure == 1)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 保存工单信息
                            if (modelT_Bus_WorkOrder.F_IsEnabled ==2)
                            {
                                string message = third.DWBackWorkOrder(modelT_Bus_WorkOrder.F_WorkOrderId,
                                backreason, userModel.F_UserName, userModel.F_UserCode);
                                if (message != "")
                                    return Error(message);
                            }
                            
                           

                            //modelT_Bus_WorkOrder.F_WorkState = 3;//退回审核中
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.auditreback;//退回审核中
                            modelT_Bus_WorkOrder.ReminderNum = 0;//催办数量清零
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

                            #region 插入退回申请信息
                            Model.T_Bus_Feedback model_T_Bus_Feedback = new Model.T_Bus_Feedback();
                            model_T_Bus_Feedback.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单编号
                            model_T_Bus_Feedback.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;//交办id
                            model_T_Bus_Feedback.F_Result = backreason;//退回原因
                            model_T_Bus_Feedback.F_IsAudit = 0;
                            model_T_Bus_Feedback.F_IsDelete = 0;
                            model_T_Bus_Feedback.F_CreateUser = userModel.F_UserCode;//退回人
                            model_T_Bus_Feedback.F_CreateTime = DateTime.Now;//退回时间
                            model_T_Bus_Feedback.F_CreateDeptId = userModel.F_DeptId;//退回部门
                            model_T_Bus_Feedback.F_IsFeedEnd = 1;
                            model_T_Bus_Feedback.F_State = 1;
                            model_T_Bus_Feedback.F_Type = 3;

                            new BLL.T_Bus_Feedback().Add(model_T_Bus_Feedback);
                            #endregion

                            #region 保存交办信息
                            //modelT_Bus_AssignedInfo.F_FeedbackTime = DateTime.Now;//办理 
                            //if (modelT_Bus_AssignedInfo.F_LimitTime < DateTime.Now)
                            //{
                            //    modelT_Bus_AssignedInfo.F_IsOverdue = 1;
                            //}
                            modelT_Bus_AssignedInfo.F_IsSure = 2;//申请退回
                            modelT_Bus_AssignedInfo.F_SureUser = userModel.F_UserCode;
                            modelT_Bus_AssignedInfo.F_SureTime = DateTime.Now;
                            assignBLL.Update(modelT_Bus_AssignedInfo);
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 申请退回了工单";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);

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

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("单位已查收，不能退回");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 审核退回工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AuditRebackWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
             //   string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));

                int state = RequestString.GetInt("state", 0);
                string reason = RequestString.GetFormString("reason");

                int rebackid = RequestString.GetInt("rebackid", 0);

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_Feedback modelT_Bus_Feedback = new BLL.T_Bus_Feedback().GetModel(rebackid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_Feedback != null && modelT_Bus_AssignedInfo != null)
                {
                    //if (modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                    //{
                    //    return Error("操作失败");
                    //}

                    if (modelT_Bus_Feedback.F_Type == 3 && modelT_Bus_Feedback.F_IsAudit == 0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            var rre = "";
                            #region 保存查收信息
                            modelT_Bus_Feedback.F_IsAudit = state;//审核
                            modelT_Bus_Feedback.F_AuditUser = userModel.F_UserCode;
                            modelT_Bus_Feedback.F_AuditTime = DateTime.Now;
                            modelT_Bus_Feedback.F_AuditReason = reason;
                            new BLL.T_Bus_Feedback().Update(modelT_Bus_Feedback);
                            #endregion
                            string strmsg = "同意";
                            if (modelT_Bus_Feedback.F_IsAudit == 1)
                            {

                                #region 插入交办记录
                                Model.T_Bus_AssignedInfo AssignedInfo = new Model.T_Bus_AssignedInfo();
                                AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                AssignedInfo.F_LimitTime = modelT_Bus_AssignedInfo.F_LimitTime;//办理时限
                                AssignedInfo.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;//主办单位id
                                AssignedInfo.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;//协办单位id
                                AssignedInfo.F_AssignedOpinion = modelT_Bus_AssignedInfo.F_AssignedOpinion;//交办意见

                                AssignedInfo.F_State = 0;//0草稿  1正式
                                AssignedInfo.F_CreateUser = modelT_Bus_AssignedInfo.F_CreateUser;
                                AssignedInfo.F_CreateTime = modelT_Bus_AssignedInfo.F_CreateTime;
                                AssignedInfo.F_IsDelete = 0;
                                AssignedInfo.F_IsOverdue = 0;
                                AssignedInfo.F_IsSure = 0;
                                AssignedInfo.F_IsNext = 0;
                                AssignedInfo.F_IsReload = modelT_Bus_AssignedInfo.F_IsReload;

                                assignBLL.Add(AssignedInfo);
                                #endregion

                                #region 保存交办信息

                                modelT_Bus_AssignedInfo.F_IsSure = 3;//退回
                                assignBLL.Update(modelT_Bus_AssignedInfo);
                                #endregion

                                #region 保存工单信息

                                //modelT_Bus_WorkOrder.F_WorkState = 1;//待交办
                                modelT_Bus_WorkOrder.F_MainDeptId = null;
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.submit;//待交办
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                #endregion
                            }
                            else
                            {
                                #region 保存工单信息

                                //modelT_Bus_WorkOrder.F_WorkState = 2;//待查收
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.receive;//待查收
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                #endregion

                                #region 保存交办信息
                                //modelT_Bus_AssignedInfo.F_FeedbackTime = null;//反馈时间
                                modelT_Bus_AssignedInfo.F_IsSure = 0;
                                modelT_Bus_AssignedInfo.F_SureUser = "";
                                modelT_Bus_AssignedInfo.F_SureTime = null;
                                assignBLL.Update(modelT_Bus_AssignedInfo);
                                #endregion

                                strmsg = "拒绝";
                            }

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " " + strmsg + "了工单退回申请";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);

                            //推送消息表
                            msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, modelT_Bus_Feedback.F_CreateUser, userModel.F_UserCode, (int)EnumSmsType.workorder);
                            #endregion
                            if (modelT_Bus_AssignedInfo.F_MainDeptId==304)
                            {
                                rre = new ShangQiuWorkOrderController().AuditRebackToGrdding(workorderid, state.ToString(),reason,userModel.F_UserCode).ToString();
                            }
                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("此审核已经处理");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 申请延时
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult DelayWorkOrder( )
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            if (userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "ZXLD")
            {
             //   string workorderid = RequestString.GetFormString("workorderid");
                //int state = RequestString.GetInt("state", 0);
                //DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime") + " 12:00:00");
                string reason = RequestString.GetFormString("reason");
                string files = RequestString.GetFormString("files");

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                #region 获取办理时间的时分秒
                int h = modelT_Bus_WorkOrder.F_LimitTime.Value.Hour;      //获取当前时间的小时部分
                int m = modelT_Bus_WorkOrder.F_LimitTime.Value.Minute;    //获取当前时间的分钟部分
                int s = modelT_Bus_WorkOrder.F_LimitTime.Value.Second;    //获取当前时间的秒部分
                string newhms = " ";
                newhms += h + ":";
                newhms += m + ":";
                newhms += s;
                #endregion
                DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime") + newhms);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                 
                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null 
                    ) 
                {
                   
                        using (TransactionScope trans = new TransactionScope())
                        {
                       if (userModel.F_RoleCode == "WLDW")
                        {
                            if (modelT_Bus_AssignedInfo.F_IsSure == 1)
                            {
                                if (userModel.F_DeptId > 0)
                                {
                                    var dept = new BLL.T_Sys_Department().GetModel(userModel.F_DeptId);
                                    if (dept != null)
                                    {
                                      
                                        if (dept.F_ExtensionTime!=null )
                                        {
                                            if (((DateTime)dept.F_ExtensionTime).Month == DateTime.Now.Month
                                           && ((DateTime)dept.F_ExtensionTime).Year == DateTime.Now.Year)
                                            {
                                                if (dept.F_DelayTimes < 100)
                                                {
                                                    dept.F_DelayTimes += 1;
                                                    dept.F_ExtensionTime = DateTime.Now;
                                                    bool n = new BLL.T_Sys_Department().Update(dept);
                                                }
                                                else
                                                    return Error("本单位本月申请延时已达三次");
                                            }
                                            else
                                            {
                                                dept.F_DelayTimes = 1;
                                                dept.F_ExtensionTime = DateTime.Now;
                                                bool n = new BLL.T_Sys_Department().Update(dept);
                                            }
                                        }
                                        else
                                        {
                                            dept.F_DelayTimes = 1;
                                            dept.F_ExtensionTime = DateTime.Now;
                                            bool n = new BLL.T_Sys_Department().Update(dept);
                                        }


                                    }
                                }
                            }
                            else
                            {
                                return Error("操作失敗，已查收");
                            }
                        }
                          


                        #region 保存工单信息
                        //modelT_Bus_WorkOrder.F_WorkState = 5;//延时审核中
                          //if (modelT_Bus_WorkOrder .F_IsEnabled ==2)
                          //  {
                          //      if (modelT_Bus_WorkOrder.F_IsEnabled == 2)
                          //      {
                          //          string message = third.DWDelayWorkOrder(modelT_Bus_WorkOrder.F_WorkOrderId,
                          //        reason, "", newlimittime, modelT_Bus_AssignedInfo.F_LimitTime.Value);
                          //          if (message != "")
                          //              return Error(message);
                          //      }
                          //  }
                          // else if (userModel.F_RoleCode != "WLDW")
                          // {
                          //  string message = third.DelayWorkOrder(modelT_Bus_WorkOrder.F_WorkOrderId,
                          //     reason, "", newlimittime, modelT_Bus_AssignedInfo.F_LimitTime.Value);
                          //  if (message != "")
                          //      return Error(message);

                          //  }
                          //  else
                          //  {
                               
                          //  }
                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.auditdelay;//延时审核中
                        workorderBLL.Update(modelT_Bus_WorkOrder);
                        #endregion

                        #region 插入申请延时信息
                        Model.T_Bus_DelayTime delay = new Model.T_Bus_DelayTime();
                            delay.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                            //delay.F_State = state;
                            delay.F_OldTime = modelT_Bus_AssignedInfo.F_LimitTime;
                            delay.F_NewTime = newlimittime;


                            delay.F_Reason = reason;
                            delay.F_State = 1;
                            delay.F_IsAudit = 0;
                            delay.F_IsDelete = 0;
                            delay.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                            delay.F_CreateUser = userModel.F_UserCode;
                            delay.F_CreateTime = DateTime.Now;
                            delay.F_File = files;

                        new BLL.T_Bus_DelayTime().Add(delay);
                      
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 申请了延时处理";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);

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

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

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 审核延时工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AuditDelayWorkOrder()
        {

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int state = RequestString.GetInt("state", 0);
                string reason = RequestString.GetFormString("reason");
               

                int delayid = RequestString.GetInt("delayid", 0);

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                #region 获取办理时间的时分秒
                int h = modelT_Bus_WorkOrder.F_LimitTime.Value.Hour;      //获取当前时间的小时部分
                int m = modelT_Bus_WorkOrder.F_LimitTime.Value.Minute;    //获取当前时间的分钟部分
                int s = modelT_Bus_WorkOrder.F_LimitTime.Value.Second;    //获取当前时间的秒部分
                string newhms = " ";
                newhms += h + ":";
                newhms += m + ":";
                newhms += s;
                #endregion
                DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime") + newhms);
                Model.T_Bus_DelayTime modelT_Bus_DelayTime = new BLL.T_Bus_DelayTime().GetModel(delayid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_DelayTime != null && modelT_Bus_AssignedInfo != null)
                {
                    //if (modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                    //{
                    //    return Error("操作失败");
                    //}

                    if (modelT_Bus_DelayTime.F_IsAudit == 0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 保存工单信息
                            //modelT_Bus_WorkOrder.F_WorkState = 4;//办理中
                        
                            TimeSpan ts = newlimittime.Subtract(modelT_Bus_WorkOrder.F_LimitTime.Value);
                            int tss = int.Parse(Math.Round(ts.TotalHours, 0).ToString());
                            if (modelT_Bus_WorkOrder.F_Scanning!=null )
                            modelT_Bus_WorkOrder.F_Scanning = modelT_Bus_WorkOrder.F_Scanning.Value.AddHours(tss);

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

                            #region 保存审核信息
                            modelT_Bus_DelayTime.F_IsAudit = state;//审核
                            modelT_Bus_DelayTime.F_AuditUser = userModel.F_UserCode;
                            modelT_Bus_DelayTime.F_AuditTime = DateTime.Now;
                            modelT_Bus_DelayTime.F_RefuseReason = reason;
                            modelT_Bus_DelayTime.F_AgreeTime = newlimittime;

                            //if (modelT_Bus_DelayTime.F_IsAudit == 1)
                            //{
                            //    string message = third.DelayWorkOrder(modelT_Bus_WorkOrder.F_WorkOrderId, modelT_Bus_DelayTime.F_Reason,
                            //       modelT_Bus_DelayTime.F_File, modelT_Bus_DelayTime.F_AgreeTime.Value,
                            //       modelT_Bus_DelayTime.F_OldTime.Value);
                            //    if (message != "")
                            //        return Error(message);
                            //}
                            


                            new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime);
                            #endregion
                            string type = "同意"; string des = "";
                            if (modelT_Bus_DelayTime.F_IsAudit == 1)
                            {
                                #region 修改交办记录

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

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

                                    assignItemBLL.Update(xb);
                                }
                                #endregion
                                des = "，原定时间" + modelT_Bus_DelayTime.F_OldTime + "，申请延长到" + modelT_Bus_DelayTime.F_AgreeTime;


                            }
                            
                            else
                            {
                                type = "拒绝";
                            }

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " " + type + "了工单延时申请" + des;
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);

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

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("此审核已经处理");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }
        /// <summary>
        /// 批量审核延时
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult AuditDelayWorkOrderBatch(string ids)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                int state = RequestString.GetInt("state", 0);
                string reason = RequestString.GetFormString("reason");
                //DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime") + " 12:00:00");
                string errids = "";string errids1 = "";
                if (!string.IsNullOrEmpty(ids))
                {
                    string[] strids = ids.Split(',');
                    foreach (string str in strids)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(str);

                            #region 获取办理时间的时分秒
                            int h = modelT_Bus_WorkOrder.F_LimitTime.Value.Hour;      //获取当前时间的小时部分
                            int m = modelT_Bus_WorkOrder.F_LimitTime.Value.Minute;    //获取当前时间的分钟部分
                            int s = modelT_Bus_WorkOrder.F_LimitTime.Value.Second;    //获取当前时间的秒部分
                            string newhms = " ";
                            newhms += h + ":";
                            newhms += m + ":";
                            newhms += s;
                            #endregion
                            DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime") + newhms);
                            Model.T_Bus_DelayTime modelT_Bus_DelayTime = new BLL.T_Bus_DelayTime().GetModelList("   F_WorkOrderId = '" + str + "' and F_State = 1 and F_IsDelete = 0 and F_IsAudit = 0 order by  F_CreateTime desc").FirstOrDefault();
                            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(str);

                            if (modelT_Bus_WorkOrder != null && modelT_Bus_DelayTime != null && modelT_Bus_AssignedInfo != null)
                            {
                                //if (modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                                //{
                                //    errids += str + ",";
                                //    continue;
                                //}

                                if (modelT_Bus_DelayTime.F_IsAudit == 0)
                                {
                                    #region 保存工单信息
                                    TimeSpan ts = newlimittime.Subtract(modelT_Bus_WorkOrder.F_LimitTime.Value);
                                    int tss = int.Parse(Math.Round(ts.TotalHours, 0).ToString());
                                    if (modelT_Bus_WorkOrder.F_Scanning != null)
                                     modelT_Bus_WorkOrder.F_Scanning = modelT_Bus_WorkOrder.F_Scanning.Value.AddHours(tss);

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

                                    #region 保存审核信息
                                    modelT_Bus_DelayTime.F_IsAudit = state;//审核
                                    modelT_Bus_DelayTime.F_AuditUser = userModel.F_UserCode;
                                    modelT_Bus_DelayTime.F_AuditTime = DateTime.Now;
                                    modelT_Bus_DelayTime.F_RefuseReason = reason;
                                    modelT_Bus_DelayTime.F_AgreeTime = newlimittime;
                                    new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime);
                                    #endregion
                                    string type = "同意"; string des = "";
                                    if (modelT_Bus_DelayTime.F_IsAudit == 1)
                                    {
                                        #region 修改交办记录

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

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

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

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

                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " " + type + "了工单延时申请" + des;
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;

                                    operBLL.Add(oper);

                                    //推送消息表
                                    msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, modelT_Bus_DelayTime.F_CreateUser, userModel.F_UserCode, (int)EnumSmsType.workorder);
                                    #endregion
                                }
                                else
                                    errids1 += str + ",";

                            }
                            trans.Complete();
                        }
                    }
                    if (errids1 != "" && errids != "")
                        return Success("操作成功");
                    else
                    {
                        string msg = "";
                        if (errids1 != "")
                            msg += "，工单编号为" + errids1.Trim(',') + "的工单已被其他人审核";
                        if(errids!="")
                            msg += "，工单编号为" + errids1.Trim(',') + "的工单不是交办人本人";
                        return Error("部分工单操作失败"+ msg);
                    }   
                }
                else
                {
                    return Error("参数获取失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }
        /// <summary>
        /// 修改扫描件
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult UpdateFiles()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            //string workorderid = RequestString.GetFormString("workorderid");
            string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
            string files = RequestString.GetFormString("files");
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
            if (modelT_Bus_WorkOrder != null)
            {
               
                modelT_Bus_WorkOrder.F_Files = files;
                //if (modelT_Bus_WorkOrder.IsExport == 1)
                //{
                //    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.closed;
                //}
                Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                //   oper.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                oper.F_Message = userinfo + "修改了扫描件 ";
                oper.F_CreateUser = userModel.F_UserCode;
                oper.F_CreateTime = DateTime.Now;
                oper.F_IsDelete = 0;

                operBLL.Add(oper);
                if (workorderBLL.Update(modelT_Bus_WorkOrder))
                {
                    return Success("修改成功");
                }
                else
                    return Error("修改失败");
            }
            else
                return Error("工单不存在");
        }
        /// <summary>
        /// 批量上传附件
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult AddFiles()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            //string workorderid = RequestString.GetFormString("workorderid");
            string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
            string files = RequestString.GetFormString("files");
            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
            if (modelT_Bus_WorkOrder != null)
            {
                if (string .IsNullOrEmpty (files))
                    return Error("请上传附件");
                if (string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_Files))
                    modelT_Bus_WorkOrder.F_Files = files;
                else
                {
                    modelT_Bus_WorkOrder.F_Files =  files;
                }
                 
                //if(modelT_Bus_WorkOrder .IsExport ==1)
                //{
                //    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.closed;
                //}
                Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
             //   oper.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                oper.F_Message = userinfo + "上传了扫描件 ";
                oper.F_CreateUser = userModel.F_UserCode;
                oper.F_CreateTime = DateTime.Now;
                oper.F_IsDelete = 0;

                operBLL.Add(oper);
                if (workorderBLL.Update(modelT_Bus_WorkOrder))
                {
                    return Success ("上传成功");
                }
                else
                    return Error("上传失败");
            }
            else
                return Error("工单不存在");
        }

        //查看工单所有的扫描件
        [Authority]
        public ActionResult getFiles()
        {
            string workorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("workorderid"));
              

            if (!string.IsNullOrEmpty(workorderid))
            {
                string sql = "select *"
                      + " from T_Bus_WorkOrder a WITH(NOLOCK) where F_WorkOrderId ='" + workorderid + "'"
                     ;
                var dt = DbHelperSQL.Query(sql).Tables[0];
                var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                if (configfj != null)
                {
                    dt = BindFileDataFiles(dt, configfj.F_ParamValue);
                }
                return Success("扫描件详细结果",dt); 
            }
            return Error("没传工单号");
        }

        //获取办理工程中提交的附件
        [Authority]
        public ActionResult getFile()
        {
            string fid = HttpUtility.UrlDecode(RequestString.GetQueryString("fid"));
            if (!string.IsNullOrEmpty(fid))
            {
                string blsql = "select *"
                            + "from T_Bus_Feedback WITH(NOLOCK) where F_Id ='" + fid + "'";
                var dt = DbHelperSQL.Query(blsql).Tables[0];
                var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                if (configfj != null)
                {
                    dt = BindFileData(dt, configfj.F_ParamValue);
                }
                return Success("附件详细结果", dt);
            }
            return Error("没传fid");
        }

        //保存办理工程中新提交的附件
        [Authority]
        public ActionResult saveFile()
        {
           
            string fid = RequestString.GetFormString("fid") ;
            string file = RequestString.GetFormString("file");
            if (!string.IsNullOrEmpty(fid))
             {
                Model.T_Bus_Feedback feedbackmodel = feedbackBLL.GetModel(Convert.ToInt32(fid));
                feedbackmodel.F_File = file;
                feedbackBLL.Update(feedbackmodel);
                return Success("修改附件成功");
            }
            return Error("没传fid");
        }



        /// <summary>
        /// 办理工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult FeedBackWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                string dealman = RequestString.GetFormString("dealman");
                string result = RequestString.GetFormString("result");
                string files = RequestString.GetFormString("files");
                int state = RequestString.GetInt("state", 0);
                int feedbackid = RequestString.GetInt("feedbackid", 0);
                int isproresult = RequestString.GetInt("isproresult", 0);//是否有处理结果:0默认，1是，2否
                string prosituation = RequestString.GetFormString("prosituation");
                string dealcontact = RequestString.GetFormString("dealcontact");
                string connecttime=RequestString.GetFormString("connecttime");
                string connectmode = RequestString.GetFormString("connectmode");
                string replycontent = RequestString.GetFormString("replycontent");
                int isstaisfied= RequestString.GetInt("isstaisfied", 0);
                string duties= RequestString.GetFormString("duties");
                string situation = RequestString.GetFormString("situation");
                string post = RequestString.GetFormString("post");
                string contact = RequestString.GetFormString("contact");
                string liable = RequestString.GetFormString("liable");
                
                int maindeptid = RequestString.GetInt("maindeptid", 0);


                string visituser = RequestString.GetFormString("visituser");//回访人
                int types = RequestString.GetInt("type", 0);//回访方式
                int issatisfie = RequestString.GetInt("issatisfie", 0);//0不满意 1满意2基本满意
                int states = RequestString.GetInt("states", 0);//0保存 1保存并下一步
                int visitid = RequestString.GetInt("visitid", 0);
                string results = RequestString.GetFormString("results");//回访情况
                int nexttype = RequestString.GetInt("nexttype", 2);//1重办 2结案
                int ishf = RequestString.GetInt("ishf", 0);//是否回访0否1是
                string cbreason = RequestString.GetFormString("cbreason");//重办原因
               // string callid = RequestString.GetFormString("callid");
                string guid = RequestString.GetFormString("guid");
                if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "GLY")
                {
                    if (maindeptid<=0)
                    {
                        return Error("请输入办理单位");
                    }
                }
                else
                {
                    maindeptid = userModel.F_DeptId;
                }
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                Model.T_Bus_Feedback modelT_Bus_Feedback = new Model.T_Bus_Feedback();
                Model.T_Bus_VisitResult modelT_Bus_VisitResult = new Model.T_Bus_VisitResult();


                int type = 1;
                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null)
                {
                  //  type = AssignDeptType(modelT_Bus_AssignedInfo, maindeptid);
                    if (type > 0)
                    {
                        //if (modelT_Bus_WorkOrder.F_WorkState == 4)
                        if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealing)
                        {
                            using (TransactionScope trans = new TransactionScope())
                            {
                                if (feedbackid == 0)
                                {
                                    #region 插入反馈记录
                                    modelT_Bus_Feedback.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单编号
                                    modelT_Bus_Feedback.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;//交办id
                                    modelT_Bus_Feedback.F_DealUser = dealman;
                                    modelT_Bus_Feedback.F_Result = result;//反馈内容
                                    modelT_Bus_Feedback.F_ClosingResult = situation;//

                                    #region 20200114新增字段 zhengbingbing
                                    modelT_Bus_Feedback.F_IsProResult = isproresult;//是否有处理结果:0默认，1是，2否
                                    modelT_Bus_Feedback.F_ProSituation = prosituation;//处理情况/方案/进程
                                    modelT_Bus_Feedback.F_IsProtect = modelT_Bus_WorkOrder.F_IsProtect;//是否保密(0:否1:是)
                                    modelT_Bus_Feedback.F_DealUserContact = dealcontact;//承办人联系方式
                                    DateTime contime = DateTime.Now;
                                    if (connecttime != "" && DateTime.TryParse(connecttime, out contime))
                                        modelT_Bus_Feedback.F_ConnectTime = DateTime.Parse(connecttime);//沟通时间
                                    modelT_Bus_Feedback.F_ConnectMode = connectmode;//沟通方式
                                    modelT_Bus_Feedback.F_ReplyContent = replycontent;//答复内容
                                    modelT_Bus_Feedback.F_IsSatisfied = isstaisfied;//是否满意:0未评价，1满意，2基本满意，3不满意
                                    modelT_Bus_Feedback.F_Duties = duties;//职务
                                    modelT_Bus_Feedback.F_Situation = situation;
                                    #endregion
                                    modelT_Bus_Feedback.F_File = files;
                                    modelT_Bus_Feedback.F_IsAudit = 0;
                                    modelT_Bus_Feedback.F_IsDelete = 0;
                                    modelT_Bus_Feedback.F_CreateUser = userModel.F_UserCode;//办理人
                                    modelT_Bus_Feedback.F_CreateTime = DateTime.Now;//办理时间
                                    modelT_Bus_Feedback.F_CreateDeptId = maindeptid;//办理部门
                                    modelT_Bus_Feedback.F_IsFeedEnd = 1;
                                    modelT_Bus_Feedback.F_State = state;
                                    modelT_Bus_Feedback.F_Type = type;

                                    new BLL.T_Bus_Feedback().Add(modelT_Bus_Feedback);
                                    #endregion
                                }
                                else
                                {
                                    #region 修改反馈记录
                                    modelT_Bus_Feedback = new BLL.T_Bus_Feedback().GetModel(feedbackid);
                                    if (modelT_Bus_Feedback != null)
                                    {
                                        modelT_Bus_Feedback.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单编号
                                        modelT_Bus_Feedback.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;//交办id
                                        modelT_Bus_Feedback.F_DealUser = dealman;
                                        modelT_Bus_Feedback.F_Result = result;//反馈内容
                                        modelT_Bus_Feedback.F_ClosingResult = situation; 

                                        modelT_Bus_Feedback.F_File = files;
                                        #region 20200114新增字段 zhengbingbing
                                        modelT_Bus_Feedback.F_IsProResult = isproresult;//是否有处理结果:0默认，1是，2否
                                        modelT_Bus_Feedback.F_ProSituation = prosituation;//处理情况/方案/进程
                                        modelT_Bus_Feedback.F_IsProtect = modelT_Bus_WorkOrder.F_IsProtect;//是否保密(0:否1:是)
                                        modelT_Bus_Feedback.F_DealUserContact = dealcontact;//承办人联系方式
                                        DateTime contime = DateTime.Now;
                                        if (connecttime != "" && DateTime.TryParse(connecttime, out contime))
                                            modelT_Bus_Feedback.F_ConnectTime = DateTime.Parse(connecttime);//沟通时间
                                        modelT_Bus_Feedback.F_ConnectMode = connectmode;//沟通方式
                                        modelT_Bus_Feedback.F_ReplyContent = replycontent;//答复内容
                                        modelT_Bus_Feedback.F_IsSatisfied = isstaisfied;//是否满意:0未评价，1满意，2基本满意，3不满意
                                        modelT_Bus_Feedback.F_Duties = duties;//职务
                                        modelT_Bus_Feedback.F_Situation = situation;
                                        #endregion
                                        modelT_Bus_Feedback.F_CreateUser = userModel.F_UserCode;//办理人
                                        modelT_Bus_Feedback.F_CreateTime = DateTime.Now;//办理时间
                                        modelT_Bus_Feedback.F_CreateDeptId = maindeptid;//办理部门
                                        modelT_Bus_Feedback.F_IsFeedEnd = 1;
                                        modelT_Bus_Feedback.F_State = state;

                                        if (modelT_Bus_AssignedInfo.F_MainDeptId == maindeptid)
                                        {
                                            modelT_Bus_Feedback.F_Type = 1;
                                        }
                                        else if (!string.IsNullOrEmpty(modelT_Bus_AssignedInfo.F_OtherDeptIds) && modelT_Bus_AssignedInfo.F_OtherDeptIds.Split(',').Contains(maindeptid.ToString()))
                                        {
                                            modelT_Bus_Feedback.F_Type = 2;
                                        }

                                        new BLL.T_Bus_Feedback().Update(modelT_Bus_Feedback);
                                    }
                                    #endregion
                                }

                                if (modelT_Bus_Feedback != null && modelT_Bus_Feedback.F_State == 1)
                                {
                                    string typemsg = "办理";
                                    if (type == 1)
                                    {
                                        int iscs = 0;
                                        if (modelT_Bus_AssignedInfo.F_LimitTime < DateTime.Now)
                                        {
                                            iscs = 1;
                                        }

                                        #region 保存工单信息
                                        //modelT_Bus_WorkOrder.F_WorkState = 6;//待回访
                                        modelT_Bus_WorkOrder.F_WorkState =7;//待回访
                                        modelT_Bus_WorkOrder.F_Result = result;

                                        modelT_Bus_WorkOrder.F_DealDeptId = maindeptid;
                                        modelT_Bus_WorkOrder.F_DealUser = userModel.F_UserCode;
                                        modelT_Bus_WorkOrder.F_DealTime = DateTime.Now;
                                        modelT_Bus_WorkOrder.F_IsOverdue = iscs;
                                        modelT_Bus_WorkOrder.F_Post = post;//职务
                                        modelT_Bus_WorkOrder.F_Contact  = contact ;//联系方式
                                        modelT_Bus_WorkOrder.F_Liable  =liable ;
                                        workorderBLL.Update(modelT_Bus_WorkOrder);
                                        #endregion

                                        #region 保存交办信息
                                        modelT_Bus_AssignedInfo.F_FeedbackTime = DateTime.Now;
                                        if (modelT_Bus_AssignedInfo.F_LimitTime < DateTime.Now)
                                        {
                                            modelT_Bus_AssignedInfo.F_IsOverdue = 1;
                                        }

                                        assignBLL.Update(modelT_Bus_AssignedInfo);
                                        #endregion

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

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

                                            new BLL.T_Bus_Feedback().Update(cg);
                                        }
                                        #endregion

                                        #region 删除二级单位未办理信息
                                        var ejlist = new BLL.T_Bus_AssignedInfo_Next().GetModelList(" F_IsDelete=0 and isnull(F_FeedbackTime,'')='' and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'");
                                        foreach (var ej in ejlist)
                                        {
                                            ej.F_IsDelete = 1;
                                            ej.F_DeleteUser = userModel.F_UserCode;
                                            ej.F_DeleteTime = DateTime.Now;

                                            new BLL.T_Bus_AssignedInfo_Next().Update(ej);
                                        }
                                        #endregion

                                        #region 处理协办单位
                                        var xblist = new BLL.T_Bus_AssignedItemInfo().GetModelList(" F_IsDelete=0 and F_State=1 and  ISNULL(F_FeedbackTime, '')='' and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'");
                                        foreach (var xb in xblist)
                                        {
                                            xb.F_State = 2;
                                            xb.F_SureUser = userModel.F_UserCode;
                                            xb.F_SureTime = DateTime.Now;

                                            new BLL.T_Bus_AssignedItemInfo().Update(xb);
                                        }
                                        #endregion

                                        typemsg = "主办";
                                    }
                                    else if (type == 2)
                                    {
                                        #region 保存明细信息
                                        Model.T_Bus_AssignedItemInfo modelT_Bus_AssignedItemInfo = new BLL.T_Bus_AssignedItemInfo().GetModelList(" F_IsDelete=0 and F_State=1 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and F_DeptId='" + maindeptid + "'").FirstOrDefault();
                                        modelT_Bus_AssignedItemInfo.F_FeedbackTime = DateTime.Now;
                                        if (modelT_Bus_AssignedItemInfo.F_LimitTime < DateTime.Now)
                                        {
                                            modelT_Bus_AssignedItemInfo.F_IsOverdue = 1;
                                        }

                                        new BLL.T_Bus_AssignedItemInfo().Update(modelT_Bus_AssignedItemInfo);
                                        #endregion

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

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

                                            new BLL.T_Bus_Feedback().Update(cg);
                                        }
                                        #endregion

                                        typemsg = "协办";
                                    }

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

                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " " + typemsg + "了工单";
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;

                                    operBLL.Add(oper);

                                    //推送消息表
                                    msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, modelT_Bus_WorkOrder.F_CreateUser, userModel.F_UserCode, (int)EnumSmsType.workorder);
                                    #endregion
                                }
                              
                                trans.Complete();
                            }
                            if (ishf==1)
                            {
                                    using (TransactionScope trans = new TransactionScope())
                                    {
                                        #region 回访
                                        if (visitid == 0)
                                        {
                                            #region 新增回访结果记录
                                            modelT_Bus_VisitResult.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                            modelT_Bus_VisitResult.F_AssignedId = 0;
                                            modelT_Bus_VisitResult.F_VisitUser = visituser;
                                            modelT_Bus_VisitResult.F_Type = types;
                                            modelT_Bus_VisitResult.F_IsSatisfie = issatisfie;
                                            modelT_Bus_VisitResult.F_Result = results;
                                            modelT_Bus_VisitResult.F_State = states;
                                         
                                            //modelT_Bus_VisitResult.F_LimitTime = newlimittime;
                                            modelT_Bus_VisitResult.F_IsDelete = 0;
                                            modelT_Bus_VisitResult.F_CreateUser = userModel.F_UserCode;
                                            modelT_Bus_VisitResult.F_CreateTime = DateTime.Now;


                                            if (modelT_Bus_AssignedInfo != null)
                                            {
                                                modelT_Bus_VisitResult.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                                            }

                                            int id = new BLL.T_Bus_VisitResult().Add(modelT_Bus_VisitResult);
                                            modelT_Bus_VisitResult.F_Id = id;
                                            //保存回访记录
                                            new BLL.T_Bus_VisitResultRecords().AddInfo(modelT_Bus_VisitResult, userModel.F_UserCode, guid);
                                            #endregion
                                        }
                                        else
                                        {
                                            #region 修改回访结果记录
                                            modelT_Bus_VisitResult = new BLL.T_Bus_VisitResult().GetModel(visitid);
                                            if (modelT_Bus_VisitResult != null)
                                            {
                                                modelT_Bus_VisitResult.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                                modelT_Bus_VisitResult.F_AssignedId = 0;
                                                modelT_Bus_VisitResult.F_VisitUser = visituser;
                                                modelT_Bus_VisitResult.F_Type = types;
                                                modelT_Bus_VisitResult.F_IsSatisfie = issatisfie;
                                                modelT_Bus_VisitResult.F_Result = results;
                                                modelT_Bus_VisitResult.F_State = states;
                                                //modelT_Bus_VisitResult.F_LimitTime = newlimittime;
                                                modelT_Bus_VisitResult.F_IsDelete = 0;
                                                modelT_Bus_VisitResult.F_CreateUser = userModel.F_UserCode;
                                                modelT_Bus_VisitResult.F_CreateTime = DateTime.Now;


                                                if (modelT_Bus_AssignedInfo != null)
                                                {
                                                    modelT_Bus_VisitResult.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                                                }

                                                int id = new BLL.T_Bus_VisitResult().Add(modelT_Bus_VisitResult);
                                                modelT_Bus_VisitResult.F_Id = id;
                                                //保存回访记录
                                                new BLL.T_Bus_VisitResultRecords().AddInfo(modelT_Bus_VisitResult, userModel.F_UserCode, guid);
                                            }
                                            #endregion
                                        }

                                        if (modelT_Bus_VisitResult != null && modelT_Bus_VisitResult.F_State == 1)
                                        {
                                            #region 保存交办信息
                                            modelT_Bus_AssignedInfo.F_IsSatisfie = issatisfie;
                                            assignBLL.Update(modelT_Bus_AssignedInfo);
                                            #endregion

                                            #region 保存工单信息
                                            //modelT_Bus_WorkOrder.F_WorkState = 7;//已回访
                                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.visit;//已回访
                                            workorderBLL.Update(modelT_Bus_WorkOrder);
                                            #endregion

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

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

                                                new BLL.T_Bus_VisitResult().Update(cg);
                                                //保存回访记录
                                                new BLL.T_Bus_VisitResultRecords().AddInfo(modelT_Bus_VisitResult, userModel.F_UserCode, guid);
                                            }
                                            #endregion
                                            var opt = "回访"; var cbreasons = "";
                                            #region 重办
                                            if (nexttype == 1)
                                            {
                                            #region 保存工单信息
                                            #region 保存工单信息
                                            modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                                            //  modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.resubmit;//待交办
                                            Model.T_Bus_AssignedInfo newmodelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                                            newmodelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                            newmodelT_Bus_AssignedInfo.F_LimitTime = modelT_Bus_AssignedInfo.F_LimitTime;//办理时限
                                            newmodelT_Bus_AssignedInfo.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;//主办单位id
                                            newmodelT_Bus_AssignedInfo.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;//协办单位id
                                            newmodelT_Bus_AssignedInfo.F_AssignedOpinion = cbreason;//交办意见
                                            newmodelT_Bus_AssignedInfo.F_State = 1;
                                            newmodelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                            newmodelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                            newmodelT_Bus_AssignedInfo.F_IsDelete = 0;
                                            newmodelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                            newmodelT_Bus_AssignedInfo.F_IsSure = 0;
                                            newmodelT_Bus_AssignedInfo.F_IsReload = 1;
                                            newmodelT_Bus_AssignedInfo.F_ReloadUser = userModel.F_UserCode;
                                            newmodelT_Bus_AssignedInfo.F_ReloadTime = DateTime.Now;
                                            newmodelT_Bus_AssignedInfo.F_IsNext = 0;
                                            newmodelT_Bus_AssignedInfo.F_Id = assignBLL.Add(newmodelT_Bus_AssignedInfo);

                                            #region 保存工单信息

                                            modelT_Bus_WorkOrder.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;
                                            modelT_Bus_WorkOrder.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;
                                         //   modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                                          //  modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;

                                            int n = Int32.Parse(DbHelperSQL.GetSingle("select count(1) from T_Bus_AssignedInfo WITH(NOLOCK) where F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and  F_State=1 and F_IsSure=1 and F_IsDelete=0 and isnull(F_IsReload,0)>0").ToString());
                                            modelT_Bus_WorkOrder.F_IsReload = n + 1;

                                            modelT_Bus_WorkOrder.F_IsOverdue = 0;
                                            //modelT_Bus_WorkOrder.F_WorkState = 8;//重办中
                                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.reload;//重办中
                                            modelT_Bus_WorkOrder.F_Result = "";
                                            modelT_Bus_WorkOrder.F_DealDeptId = null;
                                            modelT_Bus_WorkOrder.F_DealUser = "";
                                            modelT_Bus_WorkOrder.F_DealTime = null;
                                            workorderBLL.Update(modelT_Bus_WorkOrder);
                                            //   modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.resubmit;//重办待交办
                                            //   workorderBLL.Update(modelT_Bus_WorkOrder);
                                            var users = userBLL.GetModelList(" F_DeptId='" + modelT_Bus_AssignedInfo.F_MainDeptId + "' ");
                                            if (users != null && users.Count > 0)
                                            {
                                                foreach (var u in users)
                                                {
                                                 
                                                    if (!string.IsNullOrEmpty(u.F_Mobile))
                                                    {
                                                        string count = "你有重办工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                                        //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                                        //bool v = new SMSController().AddSmS(1963441, userId, count, mag, u.F_Mobile);

                                                        // string mag = "[\"" + modelT_Bus_WorkOrder.F_WorkOrderId + "\"]";
                                                        //string v = SMSNewController.AddSmS(1, "测试发送", "15639002755", "1132299838815801344", mag, workorderid);
                                                        string v = sendCs(userId, count, u.F_Mobile, modelT_Bus_WorkOrder.F_WorkOrderId);
                                                    }
                                                    if (!string.IsNullOrEmpty(u.F_Telephone))
                                                    {
                                                        var userlist = u.F_Telephone.Split(',');
                                                        if (userlist != null)
                                                        {
                                                            foreach (var it in userlist)
                                                            {
                                                                string count = "你有重办工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                                                //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                                                //bool v = new SMSController().AddSmS(1963441, userId, count, mag, it);

                                                                string v = sendCs(userId, count, it, modelT_Bus_WorkOrder.F_WorkOrderId);
                                                            }

                                                        }

                                                    }



                                                }
                                            }
                                            #endregion
                                            #endregion
                                            opt = "回访并提交重办";
                                                cbreasons = "，重办原因：" + cbreason;
                                            }
                                        #endregion
                                        #endregion
                                        #region 插入操作记录
                                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                                            oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                            oper.F_AssignedId = modelT_Bus_VisitResult.F_AssignedId;
                                            oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                        string satisfie = "不满意";
                                        if (issatisfie == 1)
                                            satisfie = "满意";
                                        else if (issatisfie == 2)
                                            satisfie = "基本满意";
                                            oper.F_Message = userinfo + " " + opt + "了工单,结果：" + satisfie + cbreasons;
                                            oper.F_CreateUser = userModel.F_UserCode;
                                            oper.F_CreateTime = DateTime.Now;
                                            oper.F_IsDelete = 0;

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

                                        #region 自动语音回访
                                        if (issatisfie == 1)//如果满意就进行自动语音回访
                                            {
                                                var configacb = configBll.GetModelList(" F_ParamCode='AutoCallBack' ").FirstOrDefault();
                                                if (configacb != null && configacb.F_ParamValue == "1")//如果为1就是开启了自动语音回访，其他都是关闭
                                                {
                                                    string AutoCallMsg = string.Empty;
                                                    new BLL.T_CTI_Task().AddToAutoVoiceNotice(modelT_Bus_WorkOrder.F_CusPhone, modelT_Bus_WorkOrder.F_WorkOrderId, modelT_Bus_AssignedInfo.F_Id, out AutoCallMsg);
                                                }
                                            }
                                            #endregion
                                        }
                                        #endregion

                                        trans.Complete();
                                    }
                                    return Success("操作成功", modelT_Bus_VisitResult.F_Id);
                            }
                            Task.Run(() =>
                            {
                                third.DwHandWorkorder(modelT_Bus_WorkOrder, userModel);
                            });
                            return Success("操作成功", modelT_Bus_Feedback.F_Id);
                        }
                        else
                        {
                            return Error("已经办理过了");
                        }
                    }
                    else
                    {
                        return Error("权限不足");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
             
               

              
              
            }
            else
            {
                return Error("权限不足");
            }
        }
        #region 网格化对接
        /// <summary>
        /// 对接网格化
        /// 工单查收操作
        /// </summary>
        /// <param name="usercode"></param>
        /// <param name="workorderid"></param>
        /// <returns></returns>
        public string ReceiveWorkOrderByDock(string usercode, string workorderid,string content)
        {
            var returns = "";
            using (TransactionScope trans = new TransactionScope())
            {
                string optmsg = ""; var assid = 0; var msgend = ""; var state = 0; var userinfo = ""; var msgss = ""; var retbool = "false"; var optid = string.Empty;
                Model.T_Sys_UserAccount userModel = userBLL.GetModel(usercode);
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                msgend = "，工单编号：" + workorderid + "，办理详情：" + content;
                if (userModel != null)
                {
                    if (modelT_Bus_WorkOrder == null)
                        msgss = "要办理的工单已不存在";
                    else if (modelT_Bus_AssignedInfo == null)
                    {
                        msgss = "工单无法处理或已被处理";
                    }
                    else
                    {
                        if (modelT_Bus_WorkOrder != null && (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.receive || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.reload) && modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_MainDeptId == userModel.F_DeptId)
                        {
                            if (modelT_Bus_AssignedInfo.F_IsSure == 0)
                            {

                                #region 保存工单信息
                                //modelT_Bus_WorkOrder.F_WorkState = 4;//办理中
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.dealing;//办理中
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                #endregion

                                #region 保存查收信息
                                modelT_Bus_AssignedInfo.F_IsSure = 1;//查收
                                modelT_Bus_AssignedInfo.F_SureUser = userModel.F_UserCode;
                                modelT_Bus_AssignedInfo.F_SureTime = DateTime.Now;
                                assignBLL.Update(modelT_Bus_AssignedInfo);
                                #endregion

                                #region 保存明细信息
                                if (!string.IsNullOrEmpty(modelT_Bus_AssignedInfo.F_OtherDeptIds))
                                {
                                    string[] strids = modelT_Bus_AssignedInfo.F_OtherDeptIds.Split(',');
                                    foreach (string strid in strids)
                                    {
                                        Model.T_Bus_AssignedItemInfo modelT_Bus_AssignedItemInfo = new Model.T_Bus_AssignedItemInfo();
                                        modelT_Bus_AssignedItemInfo.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                                        modelT_Bus_AssignedItemInfo.F_AssignedOpinion = modelT_Bus_AssignedInfo.F_AssignedOpinion;
                                        modelT_Bus_AssignedItemInfo.F_DeptId = Int32.Parse(strid);
                                        modelT_Bus_AssignedItemInfo.F_LimitTime = modelT_Bus_AssignedInfo.F_LimitTime;
                                        modelT_Bus_AssignedItemInfo.F_Remark = modelT_Bus_AssignedInfo.F_Remark;
                                        modelT_Bus_AssignedItemInfo.F_State = 1;
                                        modelT_Bus_AssignedItemInfo.F_Type = 2;
                                        modelT_Bus_AssignedItemInfo.F_WorkOrderId = modelT_Bus_AssignedInfo.F_WorkOrderId;
                                        modelT_Bus_AssignedItemInfo.F_IsSure = 0;
                                        modelT_Bus_AssignedItemInfo.F_CreateTime = DateTime.Now;
                                        modelT_Bus_AssignedItemInfo.F_CreateUser = userModel.F_UserCode;
                                        modelT_Bus_AssignedItemInfo.F_IsDelete = 0;

                                        new BLL.T_Bus_AssignedItemInfo().Add(modelT_Bus_AssignedItemInfo);

                                    }
                                }
                                #endregion
                                retbool = "true";
                                optmsg = " 查收了工单";
                                msgss = optmsg;
                            }
                            else
                                msgss = "工单已被查收";

                            assid = modelT_Bus_AssignedInfo.F_Id;
                            state = modelT_Bus_WorkOrder.F_WorkState.Value;
                        }
                        else
                            msgss = "工单已办理或已被重新指派";
                    }
                    userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                }
                else
                {
                    userinfo = "无法获取工号信息，工号为" + usercode + msgend;
                    msgss = "无法获取工号信息";
                }
                #region 插入操作记录
                Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                oper.F_WorkOrderId = workorderid;
                oper.F_AssignedId = assid;
                oper.F_State = state;
                oper.F_Message = userinfo + " " + msgss + msgend;
                oper.F_CreateUser = usercode;
                oper.F_CreateTime = DateTime.Now;
                oper.F_IsDelete = 0;
                oper.F_Type = 1;

                optid = operBLL.Add(oper).ToString();
                #endregion
                trans.Complete();
                returns = retbool + "|" + optid + "|" + msgss;
            }
        
            return returns;
        }
        /// <summary>
        /// 对接网格化 工单退回操作
        /// </summary>
        /// <returns></returns>
        public string RebackWorkOrderByDock(string usercode,string workorderid,string backreason,string content)
        {
            
            var returns = "";
            using (TransactionScope trans = new TransactionScope())
            {
                string optmsg = ""; var assid = 0; var msgend = ""; var state = 0;
                var userinfo = ""; var msgss = ""; var optid = string.Empty; var retbool = "false";
                Model.T_Sys_UserAccount userModel = userBLL.GetModel(usercode);
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                msgend = "，工单编号：" + workorderid + "，办理详情：" + content;
                if (userModel != null)
                {
                    userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                    if (modelT_Bus_WorkOrder == null)
                        msgss = "要办理的工单已不存在";
                    else if (modelT_Bus_AssignedInfo == null)
                    {
                        msgss = "工单无法处理或已被处理";
                    }
                    else
                    {
                        if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_MainDeptId == userModel.F_DeptId)
                        {
                            if (modelT_Bus_AssignedInfo.F_IsSure == 0)
                            {

                                #region 保存工单信息
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.auditreback;//退回审核中
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                #endregion

                                #region 插入退回申请信息
                                Model.T_Bus_Feedback model_T_Bus_Feedback = new Model.T_Bus_Feedback();
                                model_T_Bus_Feedback.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单编号
                                model_T_Bus_Feedback.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;//交办id
                                model_T_Bus_Feedback.F_Result = backreason;//退回原因
                                model_T_Bus_Feedback.F_IsAudit = 0;
                                model_T_Bus_Feedback.F_IsDelete = 0;
                                model_T_Bus_Feedback.F_CreateUser = userModel.F_UserCode;//退回人
                                model_T_Bus_Feedback.F_CreateTime = DateTime.Now;//退回时间
                                model_T_Bus_Feedback.F_CreateDeptId = userModel.F_DeptId;//退回部门
                                model_T_Bus_Feedback.F_IsFeedEnd = 1;
                                model_T_Bus_Feedback.F_State = 1;
                                model_T_Bus_Feedback.F_Type = 3;

                                new BLL.T_Bus_Feedback().Add(model_T_Bus_Feedback);
                                #endregion

                                #region 保存交办信息
                                modelT_Bus_AssignedInfo.F_IsSure = 2;//申请退回
                                modelT_Bus_AssignedInfo.F_SureUser = userModel.F_UserCode;
                                modelT_Bus_AssignedInfo.F_SureTime = DateTime.Now;
                                assignBLL.Update(modelT_Bus_AssignedInfo);
                                #endregion

                                #region 推送消息
                                retbool = "true";
                                optmsg = " 申请退回了工单";

                                //推送消息表
                                msg.AddInternalMessagesInfo("工单消息", userinfo + optmsg + "，工单编号：" + workorderid, modelT_Bus_AssignedInfo.F_CreateUser, userModel.F_UserCode, (int)EnumSmsType.workorder);
                                #endregion
                                msgss = optmsg;
                            }
                            else
                                msgss = "工单已被查收，不能退回";
                            assid = modelT_Bus_AssignedInfo.F_Id;
                            state = modelT_Bus_WorkOrder.F_WorkState.Value;
                        }
                        else
                            msgss = "工单已办理或已被重新指派";
                    }
                }
                else
                {
                    userinfo = "无法获取工号信息，工号为" + usercode + msgend;
                    msgss = "无法获取工号信息";
                }
                #region 插入操作记录
                Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                oper.F_WorkOrderId = workorderid;
                oper.F_AssignedId = assid;
                oper.F_State = state;
                oper.F_Message = userinfo+" " + msgss + msgend;
                oper.F_CreateUser = usercode;
                oper.F_CreateTime = DateTime.Now;
                oper.F_IsDelete = 0;
                oper.F_Type = 1;

                optid = operBLL.Add(oper).ToString();
                #endregion
                trans.Complete();

                returns = retbool + "|" + optid + "|" + msgss;
            }

            return returns;
        }
        /// <summary>
        /// 对接网格化办理
        /// </summary>
        /// <param name="usercode">工号</param>
        /// <param name="workorderid">工单编号</param>
        /// <param name="dealman">承办人人</param>
        /// <param name="result">反馈内容</param>
        /// <param name="files">附件</param>
        /// <param name="prosituation">处理情况/方案/进程</param>
        /// <param name="dealcontact">承办人联系方式</param>
        /// <param name="connecttime">沟通时间</param>
        /// <param name="connectmode">沟通方式</param>
        /// <param name="replycontent">答复内容</param>
        /// <param name="duties">职务</param>
        /// <param name="situation">处理情况</param>
        /// <param name="state">0保存，1保存并办理</param>
        /// <param name="feedbackid"></param>
        /// <param name="isproresult">是否有处理结果:0默认，1是，2否</param>
        /// <param name="isstaisfied">是否满意:0未评价，1满意，2基本满意，3不满意</param>
        /// <returns></returns>
        public string FeedBackWorkOrderBYDock(string usercode,string workorderid,string dealman,string result,string files,string prosituation, string dealcontact, string connecttime, string connectmode, string replycontent, string duties, string situation,int state=0, int feedbackid=0, int isproresult=0, int isstaisfied=0)
        {
            var returns = "";
            using (TransactionScope trans = new TransactionScope())
            {
                string optmsg = ""; var assid = 0; var msgend = ""; var wostate = 0; var userinfo = ""; string backid = string.Empty; var msgss = ""; var retbool = "false";
                Model.T_Sys_UserAccount userModel = userBLL.GetModel(usercode);
                if (userModel != null)
                {
                    userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")"; 
                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                    Model.T_Bus_Feedback modelT_Bus_Feedback = new Model.T_Bus_Feedback();
                    msgend = "，工单编号：" + workorderid;
                    int type = 0; var resmsg = ""; string typemsg = "办理";
                    if (modelT_Bus_WorkOrder == null)
                        msgss = "要办理的工单已不存在";
                    else if (modelT_Bus_AssignedInfo == null)
                    {
                        msgss = "工单无法处理";
                    }
                    else
                    {
                        type = AssignDeptType(modelT_Bus_AssignedInfo, userModel.F_DeptId);
                        if (type > 0)
                        {
                            #region 办理结果合成
                            result = "";
                            #region 获取部门
                            var deptname = "";
                            if (modelT_Bus_WorkOrder.F_MainDeptId != null)
                            {
                                var deptmodel = new BLL.T_Sys_Department().GetModel(modelT_Bus_WorkOrder.F_MainDeptId.Value);
                                if (deptmodel != null)
                                    deptname = deptmodel.F_DeptName;
                            }
                            #endregion
                            #region 获取来源
                            var sourcename = "";
                            if (modelT_Bus_WorkOrder.F_InfoSource != null)
                            {
                                var dicmodel = new BLL.T_Sys_DictionaryValue().GetModel(modelT_Bus_WorkOrder.F_InfoSource.Value);
                                if (dicmodel != null)
                                    sourcename = dicmodel.F_Value;
                            }
                            #endregion
                            var startstr = modelT_Bus_WorkOrder.F_CreateTime + " " + deptname + "部门接到" + sourcename + "来源工单（编号：" + modelT_Bus_WorkOrder.F_WorkOrderId + "）反映" + modelT_Bus_WorkOrder.F_ComTitle + "问题，";
                            var bljg = ""; var endstr = "";
                            if (isproresult == 1)
                            {
                                bljg = "已办理";
                                if (modelT_Bus_WorkOrder.F_IsProtect == 0)
                                {
                                    var isStaisfiedRadioData = "未评价";
                                    if (isstaisfied == 1)
                                    {
                                        isStaisfiedRadioData = "满意";
                                    }
                                    else if (isstaisfied == 2)
                                    {
                                        isStaisfiedRadioData = "基本满意";
                                    }
                                    else if (isstaisfied == 3)
                                    {
                                        isStaisfiedRadioData = "不满意";
                                    }
                                    endstr = "; " + dealman + "用" + connectmode + "方式在" + connecttime + "对反映人进行了回复，反映人对结果表示" + isStaisfiedRadioData;
                                }
                            }
                            else if (isproresult == 2)
                            {
                                bljg = "未办理";
                                endstr = "; 处理方案/进程：" + prosituation;
                            }
                            result = startstr + "经落实，具体情况回复如下：" + situation + " 办理结果：" + bljg + " 承办人：" + dealman + " 职务：" + duties + " 联系电话：" + dealcontact + endstr;
                            #endregion
                            if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealing)
                            {
                                #region 处理办理
                                if (feedbackid == 0)
                                {
                                    #region 插入反馈记录
                                    modelT_Bus_Feedback.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单编号
                                    modelT_Bus_Feedback.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;//交办id
                                    modelT_Bus_Feedback.F_DealUser = dealman;
                                    modelT_Bus_Feedback.F_Result = result;//反馈内容
                                    #region 20200114新增字段 zhengbingbing
                                    modelT_Bus_Feedback.F_IsProResult = isproresult;//是否有处理结果:0默认，1是，2否
                                    modelT_Bus_Feedback.F_ProSituation = prosituation;//处理情况/方案/进程
                                    modelT_Bus_Feedback.F_IsProtect = modelT_Bus_WorkOrder.F_IsProtect;//是否保密(0:否1:是)
                                    modelT_Bus_Feedback.F_DealUserContact = dealcontact;//承办人联系方式
                                    DateTime contime = DateTime.Now;
                                    if (connecttime != "" && DateTime.TryParse(connecttime, out contime))
                                        modelT_Bus_Feedback.F_ConnectTime = DateTime.Parse(connecttime);//沟通时间
                                    modelT_Bus_Feedback.F_ConnectMode = connectmode;//沟通方式
                                    modelT_Bus_Feedback.F_ReplyContent = replycontent;//答复内容
                                    modelT_Bus_Feedback.F_IsSatisfied = isstaisfied;//是否满意:0未评价，1满意，2基本满意，3不满意
                                    modelT_Bus_Feedback.F_Duties = duties;//职务
                                    modelT_Bus_Feedback.F_Situation = situation;
                                    #endregion
                                    modelT_Bus_Feedback.F_File = files;
                                    modelT_Bus_Feedback.F_IsAudit = 0;
                                    modelT_Bus_Feedback.F_IsDelete = 0;
                                    modelT_Bus_Feedback.F_CreateUser = userModel.F_UserCode;//办理人
                                    modelT_Bus_Feedback.F_CreateTime = DateTime.Now;//办理时间
                                    modelT_Bus_Feedback.F_CreateDeptId = userModel.F_DeptId;//办理部门
                                    modelT_Bus_Feedback.F_IsFeedEnd = 1;
                                    modelT_Bus_Feedback.F_State = state;
                                    modelT_Bus_Feedback.F_Type = type;
                                    modelT_Bus_Feedback.F_Id = new BLL.T_Bus_Feedback().Add(modelT_Bus_Feedback);
                                    #endregion
                                }
                                else
                                {
                                    #region 修改反馈记录
                                    modelT_Bus_Feedback = new BLL.T_Bus_Feedback().GetModel(feedbackid);
                                    if (modelT_Bus_Feedback != null)
                                    {
                                        modelT_Bus_Feedback.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单编号
                                        modelT_Bus_Feedback.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;//交办id
                                        modelT_Bus_Feedback.F_DealUser = dealman;
                                        modelT_Bus_Feedback.F_Result = result;//反馈内容
                                        modelT_Bus_Feedback.F_File = files;
                                        #region 20200114新增字段 zhengbingbing
                                        modelT_Bus_Feedback.F_IsProResult = isproresult;//是否有处理结果:0默认，1是，2否
                                        modelT_Bus_Feedback.F_ProSituation = prosituation;//处理情况/方案/进程
                                        modelT_Bus_Feedback.F_IsProtect = modelT_Bus_WorkOrder.F_IsProtect;//是否保密(0:否1:是)
                                        modelT_Bus_Feedback.F_DealUserContact = dealcontact;//承办人联系方式
                                        DateTime contime = DateTime.Now;
                                        if (connecttime != "" && DateTime.TryParse(connecttime, out contime))
                                            modelT_Bus_Feedback.F_ConnectTime = DateTime.Parse(connecttime);//沟通时间
                                        modelT_Bus_Feedback.F_ConnectMode = connectmode;//沟通方式
                                        modelT_Bus_Feedback.F_ReplyContent = replycontent;//答复内容
                                        modelT_Bus_Feedback.F_IsSatisfied = isstaisfied;//是否满意:0未评价，1满意，2基本满意，3不满意
                                        modelT_Bus_Feedback.F_Duties = duties;//职务
                                        modelT_Bus_Feedback.F_Situation = situation;
                                        #endregion
                                        modelT_Bus_Feedback.F_CreateUser = userModel.F_UserCode;//办理人
                                        modelT_Bus_Feedback.F_CreateTime = DateTime.Now;//办理时间
                                        modelT_Bus_Feedback.F_CreateDeptId = userModel.F_DeptId;//办理部门
                                        modelT_Bus_Feedback.F_IsFeedEnd = 1;
                                        modelT_Bus_Feedback.F_State = state;

                                        if (modelT_Bus_AssignedInfo.F_MainDeptId == userModel.F_DeptId)
                                        {
                                            modelT_Bus_Feedback.F_Type = 1;
                                        }
                                        else if (!string.IsNullOrEmpty(modelT_Bus_AssignedInfo.F_OtherDeptIds) && modelT_Bus_AssignedInfo.F_OtherDeptIds.Split(',').Contains(userModel.F_DeptId.ToString()))
                                        {
                                            modelT_Bus_Feedback.F_Type = 2;
                                        }

                                        new BLL.T_Bus_Feedback().Update(modelT_Bus_Feedback);
                                    }
                                    #endregion
                                }
                                if (modelT_Bus_Feedback != null && modelT_Bus_Feedback.F_State == 1)
                                {
                                    if (type == 1)
                                    {
                                        int iscs = 0;
                                        if (modelT_Bus_AssignedInfo.F_LimitTime < DateTime.Now)
                                        {
                                            iscs = 1;
                                        }

                                        #region 保存工单信息
                                        //modelT_Bus_WorkOrder.F_WorkState = 6;//待回访
                                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.dealed;//待回访
                                        modelT_Bus_WorkOrder.F_Result = result;
                                        modelT_Bus_WorkOrder.F_DealDeptId = userModel.F_DeptId;
                                        modelT_Bus_WorkOrder.F_DealUser = userModel.F_UserCode;
                                        modelT_Bus_WorkOrder.F_DealTime = DateTime.Now;
                                        modelT_Bus_WorkOrder.F_IsOverdue = iscs;
                                        workorderBLL.Update(modelT_Bus_WorkOrder);
                                        #endregion

                                        #region 保存交办信息
                                        modelT_Bus_AssignedInfo.F_FeedbackTime = DateTime.Now;
                                        if (modelT_Bus_AssignedInfo.F_LimitTime < DateTime.Now)
                                        {
                                            modelT_Bus_AssignedInfo.F_IsOverdue = 1;
                                        }

                                        assignBLL.Update(modelT_Bus_AssignedInfo);
                                        #endregion

                                        #region 删除草稿信息
                                        var cglist = new BLL.T_Bus_Feedback().GetModelList(" F_IsDelete=0 and F_State=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and F_CreateDeptId='" + userModel.F_DeptId + "'");

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

                                            new BLL.T_Bus_Feedback().Update(cg);
                                        }
                                        #endregion

                                        #region 删除二级单位未办理信息
                                        var ejlist = new BLL.T_Bus_AssignedInfo_Next().GetModelList(" F_IsDelete=0 and isnull(F_FeedbackTime,'')='' and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'");
                                        foreach (var ej in ejlist)
                                        {
                                            ej.F_IsDelete = 1;
                                            ej.F_DeleteUser = userModel.F_UserCode;
                                            ej.F_DeleteTime = DateTime.Now;

                                            new BLL.T_Bus_AssignedInfo_Next().Update(ej);
                                        }
                                        #endregion

                                        #region 处理协办单位
                                        var xblist = new BLL.T_Bus_AssignedItemInfo().GetModelList(" F_IsDelete=0 and F_State=1 and  ISNULL(F_FeedbackTime, '')='' and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'");
                                        foreach (var xb in xblist)
                                        {
                                            xb.F_State = 2;
                                            xb.F_SureUser = userModel.F_UserCode;
                                            xb.F_SureTime = DateTime.Now;

                                            new BLL.T_Bus_AssignedItemInfo().Update(xb);
                                        }
                                        #endregion

                                        typemsg = "主办";
                                    }
                                    else if (type == 2)
                                    {
                                        #region 保存明细信息
                                        Model.T_Bus_AssignedItemInfo modelT_Bus_AssignedItemInfo = new BLL.T_Bus_AssignedItemInfo().GetModelList(" F_IsDelete=0 and F_State=1 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and F_DeptId='" + userModel.F_DeptId + "'").FirstOrDefault();
                                        modelT_Bus_AssignedItemInfo.F_FeedbackTime = DateTime.Now;
                                        if (modelT_Bus_AssignedItemInfo.F_LimitTime < DateTime.Now)
                                        {
                                            modelT_Bus_AssignedItemInfo.F_IsOverdue = 1;
                                        }

                                        new BLL.T_Bus_AssignedItemInfo().Update(modelT_Bus_AssignedItemInfo);
                                        #endregion

                                        #region 删除草稿信息
                                        var cglist = new BLL.T_Bus_Feedback().GetModelList(" F_IsDelete=0 and F_State=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and F_CreateDeptId='" + userModel.F_DeptId + "'");

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

                                            new BLL.T_Bus_Feedback().Update(cg);
                                        }
                                        #endregion

                                        typemsg = "协办";
                                    }

                                    var msgs = userinfo + " " + resmsg + " " + typemsg + "了工单";
                                    //推送消息表
                                    msg.AddInternalMessagesInfo("工单消息", msgs + "，工单编号：" + workorderid, modelT_Bus_WorkOrder.F_CreateUser, userModel.F_UserCode, (int)EnumSmsType.workorder);
                                }
                                #endregion
                                retbool = "true";
                            }
                            else
                                msgss = "工单已办理";
                            backid = modelT_Bus_Feedback.F_Id.ToString();
                        }
                        else
                            msgss = "工单已办理或已被重新指派";
                        assid = modelT_Bus_AssignedInfo.F_Id;
                        wostate = modelT_Bus_WorkOrder.F_WorkState.Value;
                    }
                    msgend = resmsg + " " + typemsg + "了工单";
                }
                else
                {
                    userinfo = "无法获取工号信息，工号为" + usercode + msgend;
                    msgss = "无法获取工号信息";
                }
                #region 插入操作记录
                Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                oper.F_WorkOrderId = workorderid;
                oper.F_AssignedId = assid;
                oper.F_State = wostate;
                oper.F_Message = userinfo + msgend;
                oper.F_CreateUser = usercode;
                oper.F_CreateTime = DateTime.Now;
                oper.F_IsDelete = 0;
                oper.F_Type = 1;
                oper.F_File = files;
                operBLL.Add(oper);

                #endregion
                trans.Complete();
                returns = retbool + "|" + backid + "|" + msgss;
            }
            return returns;
        }
        /// <summary>
        /// 对接网格化，记录办理过程
        /// </summary>
        /// <param name="usercode"></param>
        /// <param name="workorderid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public string DealProcessWorkOrderByDock(string usercode,string workorderid,string content)
        {
            var returns = "";
            using (TransactionScope trans = new TransactionScope())
            {
                var assid = 0; var msgend = ""; var state = 0;var userinfo = "";var msgss = ""; var optid = string.Empty; var retbool = "false";
                Model.T_Sys_UserAccount userModel = userBLL.GetModel(usercode);
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                msgend = "，工单编号：" + workorderid + "，办理内容为：" + content;
                if (userModel != null)
                {
                    if (modelT_Bus_WorkOrder == null)
                        msgss = "要办理的工单已不存在";
                    else if (modelT_Bus_AssignedInfo == null)
                    {
                        msgss = "工单无法处理或已被处理";
                    }
                    else
                    {
                        if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealing && modelT_Bus_AssignedInfo.F_IsSure == 1 && modelT_Bus_AssignedInfo.F_MainDeptId == userModel.F_DeptId)
                        {
                            msgss = "办理工单";
                            retbool = "true";
                            assid = modelT_Bus_AssignedInfo.F_Id;
                            state = modelT_Bus_WorkOrder.F_WorkState.Value;
                        }
                        else
                        {
                            msgss = "工单无法处理";
                        }
                    }
                    userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                }
                else
                {
                    userinfo = "无法获取工号信息，工号为" + usercode + msgend;
                    msgss = "无法获取工号信息";
                }
                #region 插入操作记录
                Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                oper.F_WorkOrderId = workorderid;
                oper.F_AssignedId = assid;
                oper.F_State = state;
                oper.F_Message = userinfo + msgend;
                oper.F_CreateUser = usercode;
                oper.F_CreateTime = DateTime.Now;
                oper.F_IsDelete = 0;
                oper.F_Type = 1;

                optid = operBLL.Add(oper).ToString();
                #endregion
                trans.Complete();
                returns = retbool + "|" + optid + "|" + msgss;
            }
            return returns;
        }
        #endregion
        /// <summary>
        /// 派工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult SplitWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int maindeptid = RequestString.GetInt("maindeptid", 0);
                string otherdeptids = RequestString.GetFormString("otherdeptids");
                DateTime limittime = DateTime.Parse(RequestString.GetFormString("limittime") + " 23:59:59");
                string assignedopinion = RequestString.GetFormString("assignedopinion");
                string files = RequestString.GetFormString("files");
                int state = RequestString.GetInt("state", 0);
                int nextid = RequestString.GetInt("nextid", 0);

                if (limittime < DateTime.Now)
                {
                    return Error("办理时限不能小于当前时间");
                }

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                Model.T_Bus_AssignedInfo_Next modelT_Bus_AssignedInfo_Next = new Model.T_Bus_AssignedInfo_Next();
                var deptinfo = new BLL.T_Sys_Department().GetModel(maindeptid);
                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null && deptinfo != null)
                {
                    int type = AssignDeptType(modelT_Bus_AssignedInfo, userModel.F_DeptId);
                    //if ((type == 1 && modelT_Bus_WorkOrder.F_WorkState == 4) || userModel.F_RoleCode == "GLY")
                    if ((type == 1 && modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealing) || (userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG"))
                    {
                        if (modelT_Bus_AssignedInfo.F_IsNext == null || modelT_Bus_AssignedInfo.F_IsNext.Value == 0)
                        {
                            using (TransactionScope trans = new TransactionScope())
                            {
                                if (nextid == 0)
                                {
                                    #region 插入派单记录

                                    modelT_Bus_AssignedInfo_Next.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                    modelT_Bus_AssignedInfo_Next.F_LimitTime = limittime;//办理时限
                                    modelT_Bus_AssignedInfo_Next.F_MainDeptId = maindeptid;//主办单位id
                                    modelT_Bus_AssignedInfo_Next.F_OtherDeptIds = otherdeptids;//协办单位id
                                    modelT_Bus_AssignedInfo_Next.F_AssignedOpinion = assignedopinion;//交办意见

                                    modelT_Bus_AssignedInfo_Next.F_State = state;//0草稿  1正式
                                    modelT_Bus_AssignedInfo_Next.F_CreateUser = userModel.F_UserCode;
                                    modelT_Bus_AssignedInfo_Next.F_CreateTime = DateTime.Now;
                                    modelT_Bus_AssignedInfo_Next.F_IsDelete = 0;
                                    modelT_Bus_AssignedInfo_Next.F_IsOverdue = 0;
                                    modelT_Bus_AssignedInfo_Next.F_IsSure = 0;
                                    modelT_Bus_AssignedInfo_Next.F_IsReload = 0;
                                    modelT_Bus_AssignedInfo_Next.F_Id = new BLL.T_Bus_AssignedInfo_Next().Add(modelT_Bus_AssignedInfo_Next);
                                    #endregion
                                }
                                else
                                {
                                    #region 修改派单记录
                                    modelT_Bus_AssignedInfo_Next = new BLL.T_Bus_AssignedInfo_Next().GetModel(nextid);
                                    if (modelT_Bus_AssignedInfo_Next != null)
                                    {
                                        modelT_Bus_AssignedInfo_Next.F_LimitTime = limittime;//办理时限
                                        modelT_Bus_AssignedInfo_Next.F_MainDeptId = maindeptid;//主办单位id
                                        modelT_Bus_AssignedInfo_Next.F_OtherDeptIds = otherdeptids;//协办单位id
                                        modelT_Bus_AssignedInfo_Next.F_AssignedOpinion = assignedopinion;//交办意见

                                        modelT_Bus_AssignedInfo_Next.F_State = state;//0草稿  1正式
                                        modelT_Bus_AssignedInfo_Next.F_CreateUser = userModel.F_UserCode;
                                        modelT_Bus_AssignedInfo_Next.F_CreateTime = DateTime.Now;
                                        new BLL.T_Bus_AssignedInfo_Next().Update(modelT_Bus_AssignedInfo_Next);
                                    }
                                    #endregion
                                }

                                if (modelT_Bus_AssignedInfo_Next != null && modelT_Bus_AssignedInfo_Next.F_State == 1)
                                {
                                    #region 保存交办信息
                                    modelT_Bus_AssignedInfo.F_IsNext = 1;
                                    modelT_Bus_AssignedInfo.F_NextUser = userModel.F_UserCode;
                                    modelT_Bus_AssignedInfo.F_NextTime = DateTime.Now;
                                    new BLL.T_Bus_AssignedInfo().Update(modelT_Bus_AssignedInfo);
                                    #endregion
                                    #region 保存工单信息
                                    modelT_Bus_WorkOrder.F_MainDeptID3 = maindeptid.ToString();
                                    workorderBLL.Update(modelT_Bus_WorkOrder);
                                    #endregion

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

                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " 派单给单位：" + deptinfo.F_DeptName;
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;

                                    operBLL.Add(oper);

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

                                trans.Complete();
                            }

                            return Success("操作成功", modelT_Bus_AssignedInfo_Next.F_Id);
                        }
                        else
                        {
                            return Error("已经派过单了");
                        }
                    }
                    else
                    {
                        return Error("操作失败");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 撤回工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult WithdrawWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                Model.T_Bus_AssignedInfo_Next modelT_Bus_AssignedInfo_Next = new BLL.T_Bus_AssignedInfo_Next().GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo_Next != null && modelT_Bus_AssignedInfo.F_MainDeptId == userModel.F_DeptId)
                {

                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存撤单信息
                        modelT_Bus_AssignedInfo_Next.F_IsDelete = 1;
                        modelT_Bus_AssignedInfo_Next.F_DeleteUser = userModel.F_UserCode;
                        modelT_Bus_AssignedInfo_Next.F_DeleteTime = DateTime.Now;
                        new BLL.T_Bus_AssignedInfo_Next().Update(modelT_Bus_AssignedInfo_Next);
                        #endregion

                        #region 删除处理信息
                        var cglist = new BLL.T_Bus_Feedback_Next().GetModelList(" F_IsDelete=0 and F_AssignedId='" + modelT_Bus_AssignedInfo_Next.F_Id + "'");

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

                            new BLL.T_Bus_Feedback_Next().Update(cg);
                        }
                        #endregion

                        #region 保存交办信息
                        modelT_Bus_AssignedInfo.F_IsNext = 0;
                        new BLL.T_Bus_AssignedInfo().Update(modelT_Bus_AssignedInfo);
                        #endregion
                        #region 保存工单信息
                        modelT_Bus_WorkOrder.F_MainDeptID3 = null;
                        workorderBLL.Update(modelT_Bus_WorkOrder);
                        #endregion

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

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        oper.F_Message = userinfo + " 撤回了工单";
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);
                        #endregion

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

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 签收工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult SignWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "EJWLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                Model.T_Bus_AssignedInfo_Next modelT_Bus_AssignedInfo_Next = new BLL.T_Bus_AssignedInfo_Next().GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo_Next != null && modelT_Bus_AssignedInfo_Next.F_MainDeptId == userModel.F_DeptId) 
                {
                    if (modelT_Bus_AssignedInfo_Next.F_IsSure == 0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 保存签收信息
                            modelT_Bus_AssignedInfo_Next.F_IsSure = 1;//签收
                            modelT_Bus_AssignedInfo_Next.F_SureUser = userModel.F_UserCode;
                            modelT_Bus_AssignedInfo_Next.F_SureTime = DateTime.Now;
                            new BLL.T_Bus_AssignedInfo_Next().Update(modelT_Bus_AssignedInfo_Next);
                            #endregion

                            #region 保存交办信息
                            modelT_Bus_AssignedInfo.F_IsNext = 2;
                            new BLL.T_Bus_AssignedInfo().Update(modelT_Bus_AssignedInfo);
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 签收了工单";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);
                            #endregion

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("单位已签收，不能再次签收");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 拒收工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult RefuseWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "EJWLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                string reason = RequestString.GetFormString("reason");

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                Model.T_Bus_AssignedInfo_Next modelT_Bus_AssignedInfo_Next = new BLL.T_Bus_AssignedInfo_Next().GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo_Next != null && modelT_Bus_AssignedInfo_Next.F_MainDeptId == userModel.F_DeptId) 
                {
                    if (modelT_Bus_AssignedInfo_Next.F_IsSure == 0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 保存签收信息
                            modelT_Bus_AssignedInfo_Next.F_IsSure = 3;//签收
                            modelT_Bus_AssignedInfo_Next.F_SureUser = userModel.F_UserCode;
                            modelT_Bus_AssignedInfo_Next.F_SureTime = DateTime.Now;
                            new BLL.T_Bus_AssignedInfo_Next().Update(modelT_Bus_AssignedInfo_Next);
                            #endregion

                            #region 保存交办信息
                            modelT_Bus_AssignedInfo.F_IsNext = 0;
                            new BLL.T_Bus_AssignedInfo().Update(modelT_Bus_AssignedInfo);
                            #endregion
                            #region 保存工单信息
                            modelT_Bus_WorkOrder.F_MainDeptID3 = null;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 拒收了工单，原因：" + reason;
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);
                            #endregion

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("单位已签收，不能再次签收");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 新处理工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult DealWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "EJWLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                string dealman = RequestString.GetFormString("dealman");
                string result = RequestString.GetFormString("result");
                string files = RequestString.GetFormString("files");
                int state = RequestString.GetInt("state", 0);
                int dealid = RequestString.GetInt("dealid", 0);
                int isproresult = RequestString.GetInt("isproresult", 0);//是否有处理结果:0默认，1是，2否
                string prosituation = RequestString.GetFormString("prosituation");
                string dealcontact = RequestString.GetFormString("dealcontact");
                string connecttime = RequestString.GetFormString("connecttime");
                string connectmode = RequestString.GetFormString("connectmode");
                string replycontent = RequestString.GetFormString("replycontent");
                int isstaisfied = RequestString.GetInt("isstaisfied", 0);
                string duties = RequestString.GetFormString("duties");//职务
                string situation = RequestString.GetFormString("situation");
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                Model.T_Bus_AssignedInfo_Next modelT_Bus_AssignedInfo_Next = new BLL.T_Bus_AssignedInfo_Next().GetNewModelByWorkOrderID(workorderid);
                Model.T_Bus_Feedback_Next modelT_Bus_Feedback_Next = new Model.T_Bus_Feedback_Next();

                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo_Next != null && modelT_Bus_AssignedInfo_Next.F_MainDeptId == userModel.F_DeptId 
                    && modelT_Bus_AssignedInfo_Next.F_IsSure == 1)
                {
                    //if (modelT_Bus_WorkOrder.F_WorkState == 4 || modelT_Bus_WorkOrder.F_WorkState == 5)
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealing || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.auditdelay)
                    {
                        if (modelT_Bus_AssignedInfo.F_IsNext == 2)
                        {
                            using (TransactionScope trans = new TransactionScope())
                            {
                                if (dealid == 0)
                                {
                                    #region 插入反馈记录

                                    modelT_Bus_Feedback_Next.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单编号
                                    modelT_Bus_Feedback_Next.F_AssignedId = modelT_Bus_AssignedInfo_Next.F_Id;//交办id
                                    modelT_Bus_Feedback_Next.F_DealUser = dealman;
                                    modelT_Bus_Feedback_Next.F_Result = result;//反馈内容
                                    #region 20200114新增字段 zhengbingbing
                                    modelT_Bus_Feedback_Next.F_IsProResult = isproresult;//是否有处理结果:0默认，1是，2否
                                    modelT_Bus_Feedback_Next.F_ProSituation = prosituation;//处理情况/方案/进程
                                    modelT_Bus_Feedback_Next.F_IsProtect = modelT_Bus_WorkOrder.F_IsProtect;//是否保密(0:否1:是)
                                    modelT_Bus_Feedback_Next.F_DealUserContact = dealcontact;//承办人联系方式
                                    DateTime contime = DateTime.Now;
                                    if (connecttime != "" && DateTime.TryParse(connecttime, out contime))
                                        modelT_Bus_Feedback_Next.F_ConnectTime = DateTime.Parse(connecttime);//沟通时间
                                    modelT_Bus_Feedback_Next.F_ConnectMode = connectmode;//沟通方式
                                    modelT_Bus_Feedback_Next.F_ReplyContent = replycontent;//答复内容
                                    modelT_Bus_Feedback_Next.F_IsSatisfied = isstaisfied;//是否满意:0未评价，1满意，2基本满意，3不满意
                                    modelT_Bus_Feedback_Next.F_Duties = duties;//职务
                                    modelT_Bus_Feedback_Next.F_Situation = situation;
                                    #endregion
                                    modelT_Bus_Feedback_Next.F_File = files;
                                    modelT_Bus_Feedback_Next.F_IsAudit = 0;
                                    modelT_Bus_Feedback_Next.F_IsDelete = 0;
                                    modelT_Bus_Feedback_Next.F_CreateUser = userModel.F_UserCode;//办理人
                                    modelT_Bus_Feedback_Next.F_CreateTime = DateTime.Now;//办理时间
                                    modelT_Bus_Feedback_Next.F_CreateDeptId = userModel.F_DeptId;//办理部门
                                    modelT_Bus_Feedback_Next.F_IsFeedEnd = 1;
                                    modelT_Bus_Feedback_Next.F_State = state;
                                    modelT_Bus_Feedback_Next.F_Type = 1;

                                    new BLL.T_Bus_Feedback_Next().Add(modelT_Bus_Feedback_Next);
                                    #endregion
                                }
                                else
                                {
                                    #region 修改反馈记录
                                    modelT_Bus_Feedback_Next = new BLL.T_Bus_Feedback_Next().GetModel(dealid);
                                    if (modelT_Bus_Feedback_Next != null)
                                    {
                                        modelT_Bus_Feedback_Next.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单编号
                                        modelT_Bus_Feedback_Next.F_AssignedId = modelT_Bus_AssignedInfo_Next.F_Id;//交办id
                                        modelT_Bus_Feedback_Next.F_DealUser = dealman;
                                        modelT_Bus_Feedback_Next.F_Result = result;//反馈内容
                                        modelT_Bus_Feedback_Next.F_File = files;
                                        #region 20200114新增字段 zhengbingbing
                                        modelT_Bus_Feedback_Next.F_IsProResult = isproresult;//是否有处理结果:0默认，1是，2否
                                        modelT_Bus_Feedback_Next.F_ProSituation = prosituation;//处理情况/方案/进程
                                        modelT_Bus_Feedback_Next.F_IsProtect = modelT_Bus_WorkOrder.F_IsProtect;//是否保密(0:否1:是)
                                        modelT_Bus_Feedback_Next.F_DealUserContact = dealcontact;//承办人联系方式
                                        DateTime contime = DateTime.Now;
                                        if (connecttime != "" && DateTime.TryParse(connecttime, out contime))
                                            modelT_Bus_Feedback_Next.F_ConnectTime = DateTime.Parse(connecttime);//沟通时间
                                        modelT_Bus_Feedback_Next.F_ConnectMode = connectmode;//沟通方式
                                        modelT_Bus_Feedback_Next.F_ReplyContent = replycontent;//答复内容
                                        modelT_Bus_Feedback_Next.F_IsSatisfied = isstaisfied;//是否满意:0未评价，1满意，2基本满意，3不满意
                                        modelT_Bus_Feedback_Next.F_Duties = duties;//职务
                                        modelT_Bus_Feedback_Next.F_Situation = situation;
                                        #endregion
                                        modelT_Bus_Feedback_Next.F_CreateUser = userModel.F_UserCode;//办理人
                                        modelT_Bus_Feedback_Next.F_CreateTime = DateTime.Now;//办理时间
                                        modelT_Bus_Feedback_Next.F_CreateDeptId = userModel.F_DeptId;//办理部门
                                        modelT_Bus_Feedback_Next.F_IsFeedEnd = 1;
                                        modelT_Bus_Feedback_Next.F_State = state;

                                        new BLL.T_Bus_Feedback_Next().Update(modelT_Bus_Feedback_Next);
                                    }
                                    #endregion
                                }

                                if (modelT_Bus_Feedback_Next != null && modelT_Bus_Feedback_Next.F_State == 1)
                                {
                                    #region 保存交办信息
                                    modelT_Bus_AssignedInfo.F_IsNext = 3;
                                    new BLL.T_Bus_AssignedInfo().Update(modelT_Bus_AssignedInfo);
                                    #endregion

                                    #region 保存派单信息
                                    modelT_Bus_AssignedInfo_Next.F_FeedbackTime = DateTime.Now;
                                    if (modelT_Bus_AssignedInfo_Next.F_LimitTime < DateTime.Now)
                                    {
                                        modelT_Bus_AssignedInfo_Next.F_IsOverdue = 1;
                                    }

                                    new BLL.T_Bus_AssignedInfo_Next().Update(modelT_Bus_AssignedInfo_Next);
                                    #endregion

                                    #region 删除草稿信息
                                    var cglist = new BLL.T_Bus_Feedback_Next().GetModelList(" F_IsDelete=0 and F_State=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and F_CreateDeptId='" + userModel.F_DeptId + "'");

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

                                        new BLL.T_Bus_Feedback_Next().Update(cg);
                                    }
                                    #endregion

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

                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " 办理了工单";
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;

                                    operBLL.Add(oper);

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

                                trans.Complete();
                            }

                            return Success("操作成功", modelT_Bus_AssignedInfo_Next.F_Id);
                        }
                        else
                        {
                            return Error("已经办理过了");
                        }
                    }
                    else
                    {
                        return Error("已经办理过了");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 审核派单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AuditSplitWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int state = RequestString.GetInt("state", 0);
                string reason = RequestString.GetFormString("reason");
                int backid = RequestString.GetInt("backid", 0);
                string files = RequestString.GetFormString("files");

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                Model.T_Bus_Feedback_Next modelT_Bus_Feedback_Next = new BLL.T_Bus_Feedback_Next().GetModel(backid);
                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null && modelT_Bus_Feedback_Next != null)
                {
                    if (modelT_Bus_Feedback_Next.F_IsAudit.Value == 0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            modelT_Bus_Feedback_Next.F_IsAudit = state;
                            modelT_Bus_Feedback_Next.F_AuditUser = userModel.F_UserCode;
                            modelT_Bus_Feedback_Next.F_AuditTime = DateTime.Now;
                            modelT_Bus_Feedback_Next.F_AuditReason = reason;
                            new BLL.T_Bus_Feedback_Next().Update(modelT_Bus_Feedback_Next);

                            string strmsg = "";

                            if (state == 1)
                            {
                                strmsg = "同意";

                                #region 插入反馈记录
                                Model.T_Bus_Feedback modelT_Bus_Feedback = new Model.T_Bus_Feedback();
                                modelT_Bus_Feedback.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单编号
                                modelT_Bus_Feedback.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;//交办id
                                modelT_Bus_Feedback.F_DealUser = modelT_Bus_Feedback_Next.F_DealUser;
                                modelT_Bus_Feedback.F_Result = modelT_Bus_Feedback_Next.F_Result;//反馈内容
                                #region 20200114新增字段 zhengbingbing
                                modelT_Bus_Feedback.F_IsProResult = modelT_Bus_Feedback_Next.F_IsProResult;//是否有处理结果:0默认，1是，2否
                                modelT_Bus_Feedback.F_ProSituation = modelT_Bus_Feedback_Next.F_ProSituation;//处理情况/方案/进程
                                modelT_Bus_Feedback.F_IsProtect = modelT_Bus_Feedback_Next.F_IsProtect;//是否保密(0:否1:是)
                                modelT_Bus_Feedback.F_DealUserContact = modelT_Bus_Feedback_Next.F_DealUserContact;//承办人联系方式
                                modelT_Bus_Feedback.F_ConnectTime = modelT_Bus_Feedback_Next.F_ConnectTime;//沟通时间
                                modelT_Bus_Feedback.F_ConnectMode = modelT_Bus_Feedback_Next.F_ConnectMode;//沟通方式
                                modelT_Bus_Feedback.F_ReplyContent = modelT_Bus_Feedback_Next.F_ReplyContent;//答复内容
                                modelT_Bus_Feedback.F_IsSatisfied = modelT_Bus_Feedback_Next.F_IsSatisfied;//是否满意:0未评价，1满意，2基本满意，3不满意
                                #endregion
                                modelT_Bus_Feedback.F_File = modelT_Bus_Feedback_Next.F_File;
                                modelT_Bus_Feedback.F_IsAudit = 0;
                                modelT_Bus_Feedback.F_IsDelete = 0;
                                modelT_Bus_Feedback.F_CreateUser = userModel.F_UserCode;//办理人
                                modelT_Bus_Feedback.F_CreateTime = DateTime.Now;//办理时间
                                modelT_Bus_Feedback.F_CreateDeptId = userModel.F_DeptId;//办理部门
                                modelT_Bus_Feedback.F_IsFeedEnd = 1;
                                modelT_Bus_Feedback.F_State = state;
                                modelT_Bus_Feedback.F_Type = 1;

                                new BLL.T_Bus_Feedback().Add(modelT_Bus_Feedback);
                                #endregion


                                if (modelT_Bus_AssignedInfo.F_LimitTime < DateTime.Now)
                                {
                                    modelT_Bus_AssignedInfo.F_IsOverdue = 1;
                                    modelT_Bus_WorkOrder.F_IsOverdue = 1;
                                }

                                #region 保存工单信息
                                //modelT_Bus_WorkOrder.F_WorkState = 6;//待回访
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.dealed;//待回访
                                modelT_Bus_WorkOrder.F_Result = modelT_Bus_Feedback_Next.F_Result;
                                modelT_Bus_WorkOrder.F_DealDeptId = modelT_Bus_Feedback_Next.F_CreateDeptId;
                                modelT_Bus_WorkOrder.F_DealUser = modelT_Bus_Feedback_Next.F_CreateUser;
                                modelT_Bus_WorkOrder.F_DealTime = DateTime.Now;
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                #endregion

                                #region 保存交办信息
                                modelT_Bus_AssignedInfo.F_FeedbackTime = DateTime.Now;

                                assignBLL.Update(modelT_Bus_AssignedInfo);
                                #endregion

                                #region 删除草稿信息
                                var cglist = new BLL.T_Bus_Feedback().GetModelList(" F_IsDelete=0 and F_State=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and F_CreateDeptId='" + userModel.F_DeptId + "'");

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

                                    new BLL.T_Bus_Feedback().Update(cg);
                                }
                                #endregion

                                #region 处理协办单位
                                var xblist = new BLL.T_Bus_AssignedItemInfo().GetModelList(" F_IsDelete=0 and F_State=1 and  ISNULL(F_FeedbackTime, '')='' and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "'");
                                foreach (var xb in xblist)
                                {
                                    xb.F_State = 2;
                                    xb.F_SureUser = userModel.F_UserCode;
                                    xb.F_SureTime = DateTime.Now;

                                    new BLL.T_Bus_AssignedItemInfo().Update(xb);
                                }
                                #endregion

                            }
                            else if (state == 2)
                            {
                                strmsg = "拒绝";

                                Model.T_Bus_AssignedInfo_Next modelT_Bus_AssignedInfo_Next1 = new BLL.T_Bus_AssignedInfo_Next().GetModel(modelT_Bus_Feedback_Next.F_AssignedId.Value);
                                modelT_Bus_AssignedInfo_Next1.F_FeedbackTime = null;
                                new BLL.T_Bus_AssignedInfo_Next().Update(modelT_Bus_AssignedInfo_Next1);

                                modelT_Bus_AssignedInfo.F_IsNext = 2;
                                assignBLL.Update(modelT_Bus_AssignedInfo);

                                //#region 插入派单记录
                                //Model.T_Bus_AssignedInfo_Next modelT_Bus_AssignedInfo_Next1 = new BLL.T_Bus_AssignedInfo_Next().GetModel(modelT_Bus_Feedback_Next.F_AssignedId.Value);
                                //Model.T_Bus_AssignedInfo_Next modelT_Bus_AssignedInfo_Next = new Model.T_Bus_AssignedInfo_Next();
                                //modelT_Bus_AssignedInfo_Next.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                //modelT_Bus_AssignedInfo_Next.F_LimitTime = modelT_Bus_AssignedInfo_Next1.F_LimitTime;//办理时限
                                //modelT_Bus_AssignedInfo_Next.F_MainDeptId = modelT_Bus_AssignedInfo_Next1.F_MainDeptId;//主办单位id
                                //modelT_Bus_AssignedInfo_Next.F_OtherDeptIds = modelT_Bus_AssignedInfo_Next1.F_OtherDeptIds;//协办单位id
                                //modelT_Bus_AssignedInfo_Next.F_AssignedOpinion = reason;//交办意见

                                //modelT_Bus_AssignedInfo_Next.F_State = state;//0草稿  1正式
                                //modelT_Bus_AssignedInfo_Next.F_CreateUser = userModel.F_UserCode;
                                //modelT_Bus_AssignedInfo_Next.F_CreateTime = DateTime.Now;
                                //modelT_Bus_AssignedInfo_Next.F_IsDelete = 0;
                                //modelT_Bus_AssignedInfo_Next.F_IsOverdue = 0;
                                //modelT_Bus_AssignedInfo_Next.F_IsSure = 0;
                                //modelT_Bus_AssignedInfo_Next.F_IsReload = 0;
                                //modelT_Bus_AssignedInfo_Next.F_Id = new BLL.T_Bus_AssignedInfo_Next().Add(modelT_Bus_AssignedInfo_Next);
                                //#endregion
                            }

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " " + strmsg + "了此处理";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);

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

                            trans.Complete();
                        }

                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("已经审核过了");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 回访工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult VisitWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            //if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "ZXBZ" || userModel.F_RoleCode == "GLY")
            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZJZY" || userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                string visituser = RequestString.GetFormString("visituser");//回访人
                int type = RequestString.GetInt("type", 0);//回访方式
                int issatisfie = RequestString.GetInt("issatisfie", 0);//0不满意 1满意
                                                                       //DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime"));//不满意，重办的办理时限
                int state = RequestString.GetInt("state", 0);//0保存 1保存并下一步
                int visitid = RequestString.GetInt("visitid", 0);
                string result = RequestString.GetFormString("result");//回访情况
                int nexttype = RequestString.GetInt("nexttype", 0);//1重办 2结案
                //string overseeopinion = RequestString.GetFormString("overseeopinion");//督办意见
                //string finalopinion = RequestString.GetFormString("finalopinion");//结案意见
                string cbreason = RequestString.GetFormString("cbreason");//重办原因
                string callid = RequestString.GetFormString("callid");
                string guid = RequestString.GetFormString("guid");

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                Model.T_Bus_VisitResult modelT_Bus_VisitResult = new Model.T_Bus_VisitResult();

                if (modelT_Bus_WorkOrder != null)
                {
                    //if (modelT_Bus_WorkOrder.F_WorkState == 6)
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealed)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 回访
                            if (visitid == 0)
                            {
                                #region 新增回访结果记录
                                modelT_Bus_VisitResult.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                modelT_Bus_VisitResult.F_AssignedId = 0;
                                modelT_Bus_VisitResult.F_VisitUser = visituser;
                                modelT_Bus_VisitResult.F_Type = type;
                                modelT_Bus_VisitResult.F_IsSatisfie = issatisfie;
                                modelT_Bus_VisitResult.F_Result = result;
                                modelT_Bus_VisitResult.F_State = state;
                                if (!string.IsNullOrEmpty(callid))
                                {
                                    var rd = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
                                    if (rd != null)
                                    {
                                        modelT_Bus_VisitResult.F_CallRecordId = rd.CallRecordsId;
                                    }
                                }
                                //modelT_Bus_VisitResult.F_LimitTime = newlimittime;
                                modelT_Bus_VisitResult.F_IsDelete = 0;
                                modelT_Bus_VisitResult.F_CreateUser = userModel.F_UserCode;
                                modelT_Bus_VisitResult.F_CreateTime = DateTime.Now;


                                if (modelT_Bus_AssignedInfo != null)
                                {
                                    modelT_Bus_VisitResult.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                                }

                                int id = new BLL.T_Bus_VisitResult().Add(modelT_Bus_VisitResult);
                                modelT_Bus_VisitResult.F_Id = id;
                                //保存回访记录
                                new BLL.T_Bus_VisitResultRecords().AddInfo(modelT_Bus_VisitResult, userModel.F_UserCode, guid);
                                #endregion
                            }
                            else
                            {
                                #region 修改回访结果记录
                                modelT_Bus_VisitResult = new BLL.T_Bus_VisitResult().GetModel(visitid);
                                if (modelT_Bus_VisitResult != null)
                                {
                                    modelT_Bus_VisitResult.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                    modelT_Bus_VisitResult.F_AssignedId = 0;
                                    modelT_Bus_VisitResult.F_VisitUser = visituser;
                                    modelT_Bus_VisitResult.F_Type = type;
                                    modelT_Bus_VisitResult.F_IsSatisfie = issatisfie;
                                    modelT_Bus_VisitResult.F_Result = result;
                                    modelT_Bus_VisitResult.F_State = state;
                                    if (!string.IsNullOrEmpty(callid))
                                    {
                                        var rd = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
                                        if (rd != null)
                                        {
                                            modelT_Bus_VisitResult.F_CallRecordId = rd.CallRecordsId;
                                        }
                                    }
                                    //modelT_Bus_VisitResult.F_LimitTime = newlimittime;
                                    modelT_Bus_VisitResult.F_IsDelete = 0;
                                    modelT_Bus_VisitResult.F_CreateUser = userModel.F_UserCode;
                                    modelT_Bus_VisitResult.F_CreateTime = DateTime.Now;


                                    if (modelT_Bus_AssignedInfo != null)
                                    {
                                        modelT_Bus_VisitResult.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                                    }

                                    int id = new BLL.T_Bus_VisitResult().Add(modelT_Bus_VisitResult);
                                    modelT_Bus_VisitResult.F_Id = id;
                                    //保存回访记录
                                    new BLL.T_Bus_VisitResultRecords().AddInfo(modelT_Bus_VisitResult, userModel.F_UserCode, guid);
                                }
                                #endregion
                            }

                            if (modelT_Bus_VisitResult != null && modelT_Bus_VisitResult.F_State == 1)
                            {
                                #region 保存交办信息
                                modelT_Bus_AssignedInfo.F_IsSatisfie = issatisfie;
                                assignBLL.Update(modelT_Bus_AssignedInfo);
                                #endregion

                                #region 保存工单信息
                                //modelT_Bus_WorkOrder.F_WorkState = 7;//已回访
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.visit;//已回访
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                #endregion

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

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

                                    new BLL.T_Bus_VisitResult().Update(cg);
                                    //保存回访记录
                                    new BLL.T_Bus_VisitResultRecords().AddInfo(modelT_Bus_VisitResult, userModel.F_UserCode, guid);
                                }
                                #endregion
                                var opt = "回访"; var cbreasons = "";
                                #region 重办
                                if (nexttype == 1)
                                {
                                    #region 保存工单信息
                                   // modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.resubmit;//重办待交办
                                        Model.T_Bus_AssignedInfo newmodelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                                        newmodelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                        newmodelT_Bus_AssignedInfo.F_LimitTime = modelT_Bus_AssignedInfo.F_LimitTime ;//办理时限
                                        newmodelT_Bus_AssignedInfo.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId ;//主办单位id
                                        newmodelT_Bus_AssignedInfo.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds ;//协办单位id
                                        newmodelT_Bus_AssignedInfo.F_AssignedOpinion = cbreason;//交办意见
                                        newmodelT_Bus_AssignedInfo.F_State = 1;
                                        newmodelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                        newmodelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                        newmodelT_Bus_AssignedInfo.F_IsDelete = 0;
                                        newmodelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                        newmodelT_Bus_AssignedInfo.F_IsSure = 0;
                                        newmodelT_Bus_AssignedInfo.F_IsReload = 1;
                                        newmodelT_Bus_AssignedInfo.F_ReloadUser = userModel.F_UserCode;
                                        newmodelT_Bus_AssignedInfo.F_ReloadTime = DateTime.Now;
                                        newmodelT_Bus_AssignedInfo.F_IsNext = 0;
                                        newmodelT_Bus_AssignedInfo.F_Id = assignBLL.Add(newmodelT_Bus_AssignedInfo);

                                        #region 保存工单信息

                                        modelT_Bus_WorkOrder.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;
                                        modelT_Bus_WorkOrder.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;
                                     //   modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                                       // modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;

                                        int n = Int32.Parse(DbHelperSQL.GetSingle("select count(1) from T_Bus_AssignedInfo WITH(NOLOCK) where F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and  F_State=1 and F_IsSure=1 and F_IsDelete=0 and isnull(F_IsReload,0)>0").ToString());
                                        modelT_Bus_WorkOrder.F_IsReload = n + 1;
                                       
                                        modelT_Bus_WorkOrder.F_IsOverdue = 0;
                                        //modelT_Bus_WorkOrder.F_WorkState = 8;//重办中
                                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.reload;//重办中
                                        modelT_Bus_WorkOrder.F_Result = "";
                                        modelT_Bus_WorkOrder.F_DealDeptId = null;
                                        modelT_Bus_WorkOrder.F_DealUser = "";
                                        modelT_Bus_WorkOrder.F_DealTime = null;
                                        workorderBLL.Update(modelT_Bus_WorkOrder);
                                    #endregion
                                    #region 插入操作记录




                                    #region 20191021调整为多个主办单位时调整
                                    //var deptinfo = new BLL.T_Sys_Department().GetModel(modelT_Bus_AssignedInfo.F_MainDeptId.Value);

                                    #endregion


                                    var users = userBLL.GetModelList(" F_DeptId='" + modelT_Bus_AssignedInfo.F_MainDeptId + "' ");
                                    if (users != null && users.Count > 0)
                                    {
                                        foreach (var u in users)
                                        {

                                            if (!string.IsNullOrEmpty(u.F_Mobile))
                                            {
                                                string count = "你有重办工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                                //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                                //bool v = new SMSController().AddSmS(1963441, userId, count, mag, u.F_Mobile);

                                                string v = sendCs(userId, count, u.F_Mobile, modelT_Bus_WorkOrder.F_WorkOrderId);
                                            }
                                            if (!string.IsNullOrEmpty(u.F_Telephone))
                                            {
                                                var userlist = u.F_Telephone.Split(',');
                                                if (userlist != null)
                                                {
                                                    foreach (var it in userlist)
                                                    {
                                                        string count = "你有重办工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                                        //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                                        //bool v = new SMSController().AddSmS(1963441, userId, count, mag, it);

                                                        string v = sendCs(userId, count, it, modelT_Bus_WorkOrder.F_WorkOrderId);
                                                    }

                                                }

                                            }



                                        }
                                    }

                                    #endregion



                                    workorderBLL.Update(modelT_Bus_WorkOrder);
                                    #endregion
                                    opt = "回访并提交重办";
                                    cbreasons = "，重办原因："+ cbreason;
                                }
                                #endregion

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

                                string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                string satisfie = "不满意";
                                if (issatisfie == 1)
                                    satisfie = "满意";
                                else if (issatisfie == 2)
                                    satisfie = "基本满意";
                                oper.F_Message = userinfo+" " + opt + "了工单,结果：" + satisfie + cbreasons;
                                oper.F_CreateUser = userModel.F_UserCode;
                                oper.F_CreateTime = DateTime.Now;
                                oper.F_IsDelete = 0;

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

                                #region 自动语音回访
                                if (issatisfie == 1)//如果满意就进行自动语音回访
                                {
                                    var configacb = configBll.GetModelList(" F_ParamCode='AutoCallBack' ").FirstOrDefault();
                                    if (configacb != null && configacb.F_ParamValue == "1")//如果为1就是开启了自动语音回访，其他都是关闭
                                    {
                                        string AutoCallMsg = string.Empty;
                                        new BLL.T_CTI_Task().AddToAutoVoiceNotice(modelT_Bus_WorkOrder.F_CusPhone, modelT_Bus_WorkOrder.F_WorkOrderId, modelT_Bus_AssignedInfo.F_Id, out AutoCallMsg);
                                    }
                                }
                                #endregion
                            }
                            #endregion
                            
                            trans.Complete();
                        }
                        return Success("操作成功", modelT_Bus_VisitResult.F_Id);
                    }
                    else
                    {
                        return Error("已经回访过了");
                    }
                }
                else
                {
                    return Error("操作失败");
                }

            }
            else
            {
                return Error("权限不足");
            }
        }

        #region 20200311 zhengbingbing 增加履职界定操作
        /// <summary>
        /// 履职
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult PerformWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {//承办单位和管理员
             //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int state = RequestString.GetInt("state", 0);//0保存 1保存并下一步
                int perid = RequestString.GetInt("perid", 0);
                string file = RequestString.GetFormString("file");
                string result = RequestString.GetFormString("result");
                string guid = RequestString.GetFormString("guid");

                string visitids = RequestString.GetFormString("visitids");
                if (string.IsNullOrWhiteSpace(visitids))
                    return Error("请选择你要履职的回访记录");

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                List<Model.T_Bus_VisitResult> listT_Bus_VisitResult = new BLL.T_Bus_VisitResult().GetModelList("F_Id in ("+ visitids + ")");
                Model.T_Bus_PerformDuties modelT_Bus_PerformDuties = new Model.T_Bus_PerformDuties();

                if (modelT_Bus_WorkOrder != null)
                {
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.visit|| modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.resubmit || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.reload || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.rejload || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)
                    {//已回访，重办待交办，重办中，重办驳回，已结案
                        using (TransactionScope trans = new TransactionScope())
                        {
                            var assids = ""; //读取对应的交办记录
                            #region 读取对应的交办id
                            foreach (var item in listT_Bus_VisitResult)
                            {
                                if (item.F_AssignedId != null && item.F_AssignedId != 0)
                                    assids = item.F_AssignedId + ",";
                            }
                            assids = assids.Trim(',');
                            #endregion
                            #region 履职
                            if (perid == 0)
                            {
                                #region 新增履职记录
                                modelT_Bus_PerformDuties.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                modelT_Bus_PerformDuties.F_AssignedId = assids;
                                modelT_Bus_PerformDuties.F_VisitId = visitids;
                                modelT_Bus_PerformDuties.F_File = file;
                                modelT_Bus_PerformDuties.F_State = state;
                                modelT_Bus_PerformDuties.F_Result = result;
                                modelT_Bus_PerformDuties.F_IsAudit = 0;
                                modelT_Bus_PerformDuties.F_IsDelete = 0;
                                modelT_Bus_PerformDuties.F_CreateDeptId = userModel.F_DeptId;
                                modelT_Bus_PerformDuties.F_CreateTime = DateTime.Now;
                                modelT_Bus_PerformDuties.F_CreateUser = userModel.F_UserCode;
                                
                                int id=new BLL.T_Bus_PerformDuties().Add(modelT_Bus_PerformDuties);
                                modelT_Bus_PerformDuties.F_Id = id;
                                //保存回访记录
                                new BLL.T_Bus_PerformDutiesRecords().AddInfo(modelT_Bus_PerformDuties, userModel.F_UserCode, guid);
                                #endregion
                            }
                            else
                            {
                                #region 修改履职记录
                                modelT_Bus_PerformDuties = new BLL.T_Bus_PerformDuties().GetModel(perid);
                                if (modelT_Bus_PerformDuties != null)
                                {
                                    modelT_Bus_PerformDuties.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                    modelT_Bus_PerformDuties.F_AssignedId = assids;
                                    modelT_Bus_PerformDuties.F_VisitId = visitids;
                                    modelT_Bus_PerformDuties.F_File = file;
                                    modelT_Bus_PerformDuties.F_State = state;
                                    modelT_Bus_PerformDuties.F_Result = result;
                                    modelT_Bus_PerformDuties.F_IsAudit = 0;
                                    modelT_Bus_PerformDuties.F_IsDelete = 0;
                                    modelT_Bus_PerformDuties.F_CreateDeptId = userModel.F_DeptId;
                                    modelT_Bus_PerformDuties.F_CreateTime = DateTime.Now;
                                    modelT_Bus_PerformDuties.F_CreateUser = userModel.F_UserCode;
                                    int id = new BLL.T_Bus_PerformDuties().Add(modelT_Bus_PerformDuties);
                                    modelT_Bus_PerformDuties.F_Id = id;
                                    //保存回访记录
                                    new BLL.T_Bus_PerformDutiesRecords().AddInfo(modelT_Bus_PerformDuties, userModel.F_UserCode, guid);
                                }
                                #endregion
                            }

                            if (modelT_Bus_PerformDuties != null && modelT_Bus_PerformDuties.F_State == 1)
                            {
                                #region 保存交办信息
                                foreach (var item in assids.Split(','))
                                {
                                    var model = assignBLL.GetModel(int.Parse(item));
                                    if (model != null)
                                    {
                                        model.F_IsPerform = 1;
                                        assignBLL.Update(model);
                                    }
                                }
                                #endregion
                                #region
                                foreach (var item in listT_Bus_VisitResult)
                                {
                                    item.F_IsPerform = 1;
                                    new BLL.T_Bus_VisitResult().Update(item);
                                }
                                #endregion

                                #region 删除草稿信息
                                var cglist = new BLL.T_Bus_PerformDuties().GetModelList(" F_IsDelete=0 and F_State=0 and F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and F_CreateUser='" + userModel.F_UserCode + "' ");

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

                                    new BLL.T_Bus_PerformDuties().Update(cg);
                                    new BLL.T_Bus_PerformDutiesRecords().AddInfo(cg, userModel.F_UserCode, guid);
                                }
                                #endregion
                                var opt = "履职界定";
                                #region 插入操作记录
                                Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                                oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                                string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                oper.F_Message = userinfo + " 对工单提交 " + opt + " 操作";
                                oper.F_File = modelT_Bus_PerformDuties.F_File;
                                oper.F_CreateUser = userModel.F_UserCode;
                                oper.F_CreateTime = DateTime.Now;
                                oper.F_IsDelete = 0;
                                foreach (var item in assids.Split(','))
                                {
                                    oper.F_AssignedId = int.Parse(item);
                                    operBLL.Add(oper);

                                    //推送消息表 履职界定消息目前推送给工号8666 
                                    msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, "8666", userModel.F_UserCode, (int)EnumSmsType.workorder);
                                }
                                #endregion
                            }
                            #endregion
                            trans.Complete();
                        }
                        return Success("操作成功", modelT_Bus_PerformDuties.F_Id);
                    }
                    else
                    {
                        return Error("此状态下不能进行履职操作");
                    }
                }
                else
                {
                    return Error("操作失败");
                }

            }
            else
            {
                return Error("权限不足");
            }
        }
        /// <summary>
        /// 履职界定审核
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult DefinitionWorkOrder() {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int state = RequestString.GetInt("state", 0);
                string reason = RequestString.GetFormString("reason");
                int perid = RequestString.GetInt("perid", 0);
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_PerformDuties modelT_Bus_PerformDuties = new BLL.T_Bus_PerformDuties().GetModel(perid);
                if (modelT_Bus_WorkOrder != null && modelT_Bus_PerformDuties != null)
                {
                    if (modelT_Bus_PerformDuties.F_IsAudit.Value == 0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 保存履职界定信息
                            modelT_Bus_PerformDuties.F_IsAudit = state;
                            modelT_Bus_PerformDuties.F_AuditUser = userModel.F_UserCode;
                            modelT_Bus_PerformDuties.F_AuditTime = DateTime.Now;
                            modelT_Bus_PerformDuties.F_AuditReason = reason;
                            new BLL.T_Bus_PerformDuties().Update(modelT_Bus_PerformDuties);
                            #endregion
                            string strmsg = ""; var isperform = 1; int IsSatisfie = 0;
                            #region
                            if (state == 1)
                            {
                                strmsg = "同意";
                                isperform = 2;
                                IsSatisfie = 1;
                            }
                            else if (state == 2)
                            {
                                strmsg = "拒绝";
                                isperform = 3;
                            }
                            #endregion

                            #region 交办记录处理
                            foreach (var item in modelT_Bus_PerformDuties.F_AssignedId.Split(','))
                            {
                                var model = assignBLL.GetModel(int.Parse(item));
                                if (model != null)
                                {
                                    model.F_IsPerform = isperform;
                                    if (state == 1)//同意此履职界定则修改回访结果为满意
                                        model.F_IsSatisfie = IsSatisfie;
                                    assignBLL.Update(model);

                                }
                            }
                            #endregion
                            #region 回访记录处理
                            foreach (var item in modelT_Bus_PerformDuties.F_VisitId.Split(','))
                            {
                                var model = new BLL.T_Bus_VisitResult().GetModel(int.Parse(item));
                                if (model != null)
                                {
                                    model.F_IsPerform = isperform;
                                    if (state == 1)//同意此履职界定则修改回访结果为满意
                                        model.F_IsSatisfie = IsSatisfie;
                                    new BLL.T_Bus_VisitResult().Update(model);

                                }
                            }
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " " + strmsg + "了此处理";
                            if (!string.IsNullOrWhiteSpace(reason))
                                oper.F_Message = oper.F_Message + "，理由为："+ reason;
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            foreach (var item in modelT_Bus_PerformDuties.F_AssignedId.Split(','))
                            {
                                oper.F_AssignedId = int.Parse(item);
                                operBLL.Add(oper);

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

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                        return Error("已经审核过了");
                }
                else
                    return Error("操作失败");
            }
            else
                return Error("权限不足");
        }

        #endregion

        /// <summary>
        /// 督办或监察工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult RemindWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            //string workorderid = RequestString.GetFormString("workorderid");
            string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
            int type = RequestString.GetInt("type", 0);//1督办 2监察
            int state = RequestString.GetInt("state", 0);//0待办 1已办 2退回
            string overseeopinion = RequestString.GetFormString("overseeopinion");//督办意见
            string files = RequestString.GetFormString("files");

            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
            if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null)
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    #region 插入督办记录
                    Model.T_Bus_RemindRecord modelT_Bus_RemindRecord = new Model.T_Bus_RemindRecord();
                    if (type == 1 && state > 0)
                    {
                        modelT_Bus_RemindRecord = new BLL.T_Bus_RemindRecord().GetModelList(" F_State=0 and F_IsDelete=0 and F_Type =1 order by F_CreateTime desc").FirstOrDefault();
                        if(modelT_Bus_RemindRecord!=null)
                        {
                            modelT_Bus_RemindRecord.F_Content = overseeopinion;
                            modelT_Bus_RemindRecord.F_State = state;
                            new BLL.T_Bus_RemindRecord().Update(modelT_Bus_RemindRecord);
                        }
                    }
                    else
                    {
                        modelT_Bus_RemindRecord.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                        modelT_Bus_RemindRecord.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                        modelT_Bus_RemindRecord.F_Type = type;
                        modelT_Bus_RemindRecord.F_DeptId = modelT_Bus_AssignedInfo.F_MainDeptId;
                        modelT_Bus_RemindRecord.F_Content = overseeopinion;
                        modelT_Bus_RemindRecord.F_File = files;
                        modelT_Bus_RemindRecord.F_State = state;//0待办 1已办 2退回
                        modelT_Bus_RemindRecord.F_IsDelete = 0;
                        modelT_Bus_RemindRecord.F_CreateUser = userModel.F_UserCode;
                        modelT_Bus_RemindRecord.F_CreateTime = DateTime.Now;

                        new BLL.T_Bus_RemindRecord().Add(modelT_Bus_RemindRecord);
                    }
                    #endregion

                    #region 插入操作记录
                    string typename = "督办";
                    if (type == 2) { typename = "监察"; }
                    if (type == 1 && state==0) { typename = "提交督办"; }
                    if (type == 1 && state == 1) { typename = "督办"; }
                    if (type == 1 && state == 2) { typename = "退回督办"; }
                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                    oper.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                    oper.F_Message = userinfo + " " + typename + "了工单";
                    oper.F_CreateUser = userModel.F_UserCode;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;

                    operBLL.Add(oper);
                    #endregion

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

        /// <summary>
        /// 重办工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult ReloadWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            //if (userModel.F_RoleCode == "ZJZY" || userModel.F_RoleCode == "GLY")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                string overseeopinion = RequestString.GetFormString("overseeopinion");//督办意见
                DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime") + " 23:59:59");//不满意，重办的办理时限

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                if (modelT_Bus_WorkOrder != null)
                {
                    if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                    {
                        return Error("操作失败");
                    }
                    //if (modelT_Bus_WorkOrder.F_WorkState == 7)
                    //if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.visit)
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.resubmit)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 插入督办记录
                            Model.T_Bus_RemindRecord modelT_Bus_RemindRecord = new Model.T_Bus_RemindRecord();
                            modelT_Bus_RemindRecord.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                            modelT_Bus_RemindRecord.F_AssignedId = 0;
                            modelT_Bus_RemindRecord.F_Type = 1;
                            if (modelT_Bus_AssignedInfo != null)//转办后重办
                            {
                                #region 插入交办记录
                                int n = Int32.Parse(DbHelperSQL.GetSingle("select count(1) from T_Bus_AssignedInfo WITH(NOLOCK) where F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and  F_State=1 and F_IsSure=1 and F_IsDelete=0 and isnull(F_IsReload,0)>0").ToString());

                                modelT_Bus_WorkOrder.F_IsReload = n + 1;
                                modelT_Bus_WorkOrder.F_LimitTime = newlimittime;
                                modelT_Bus_WorkOrder.F_Scanning = newlimittime.AddDays(3);
                                modelT_Bus_WorkOrder.F_IsOverdue = 0;

                                Model.T_Bus_AssignedInfo AssignedInfo = new Model.T_Bus_AssignedInfo();
                                AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                AssignedInfo.F_LimitTime = newlimittime;//办理时限
                                AssignedInfo.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;//主办单位id
                                AssignedInfo.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;//协办单位id
                                AssignedInfo.F_AssignedOpinion = modelT_Bus_AssignedInfo.F_AssignedOpinion;//交办意见

                                AssignedInfo.F_State = 1;//0草稿  1正式
                                AssignedInfo.F_CreateUser = modelT_Bus_AssignedInfo.F_CreateUser;
                                AssignedInfo.F_CreateTime = modelT_Bus_AssignedInfo.F_CreateTime;
                                AssignedInfo.F_IsDelete = 0;
                                AssignedInfo.F_IsOverdue = 0;
                                AssignedInfo.F_IsSure = 0;
                                AssignedInfo.F_IsReload = n + 1;
                                AssignedInfo.F_ReloadUser = userModel.F_UserCode;
                                AssignedInfo.F_ReloadTime = DateTime.Now;

                                assignBLL.Add(AssignedInfo);
                                #endregion

                                modelT_Bus_RemindRecord.F_AssignedId = AssignedInfo.F_Id;
                                modelT_Bus_RemindRecord.F_DeptId = AssignedInfo.F_MainDeptId;
                            }
                            else if (modelT_Bus_WorkOrder.F_IsResult == 1)//直办后重办
                            {
                                var cruser = userBLL.GetModel(modelT_Bus_WorkOrder.F_CreateUser);
                                if (cruser != null)
                                {
                                    modelT_Bus_RemindRecord.F_DeptId = cruser.F_DeptId;
                                }
                            }

                            modelT_Bus_RemindRecord.F_Content = overseeopinion;
                            modelT_Bus_RemindRecord.F_State = 1;
                            modelT_Bus_RemindRecord.F_IsDelete = 0;
                            modelT_Bus_RemindRecord.F_CreateUser = userModel.F_UserCode;
                            modelT_Bus_RemindRecord.F_CreateTime = DateTime.Now;

                            new BLL.T_Bus_RemindRecord().Add(modelT_Bus_RemindRecord);
                            #endregion

                            #region 保存工单信息
                            //modelT_Bus_WorkOrder.F_WorkState = 8;//重办中
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.reload;//重办中
                            modelT_Bus_WorkOrder.F_Result = "";
                            modelT_Bus_WorkOrder.F_DealDeptId = null;
                            modelT_Bus_WorkOrder.F_DealUser = "";
                            modelT_Bus_WorkOrder.F_DealTime = null;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

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

                            string deptname = "";
                            #region 20191021调整为多个主办单位时调整
                            var deptinfo = new BLL.T_Sys_Department().GetModel(modelT_Bus_AssignedInfo.F_MainDeptId.Value);
                            if (deptinfo != null) { deptname = deptinfo.F_DeptName; }
                            #endregion
                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 重办并督办了工单,交办单位：" + deptname;
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);

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

                            foreach (var u in users)
                            {
                                msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.workorder);
                            }
                            #endregion

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("已经处理过了");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }
        /// <summary>
        /// 退回原单位重办
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult SubReloadWorkOrder( string reason)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            string str = HttpUtility.UrlDecode(RequestString.GetFormString("ids"));
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZJZY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                 
                     
                        using (TransactionScope trans = new TransactionScope())
                        {
                            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(str);
                            if (modelT_Bus_WorkOrder != null)
                            {
                                if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.visit || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.rejload
                                    || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.closed
                                    || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)
                                {
                                    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(modelT_Bus_WorkOrder.F_WorkOrderId  );
                                    #region 保存工单信息
                                    modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                                    //  modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.resubmit;//待交办
                                    Model.T_Bus_AssignedInfo newmodelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                                    newmodelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                    newmodelT_Bus_AssignedInfo.F_LimitTime = modelT_Bus_AssignedInfo.F_LimitTime;//办理时限
                                    newmodelT_Bus_AssignedInfo.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;//主办单位id
                                    newmodelT_Bus_AssignedInfo.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;//协办单位id
                                    newmodelT_Bus_AssignedInfo.F_AssignedOpinion = reason;//交办意见
                                    newmodelT_Bus_AssignedInfo.F_State = 1;
                                    newmodelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                    newmodelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                    newmodelT_Bus_AssignedInfo.F_IsDelete = 0;
                                    newmodelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                    newmodelT_Bus_AssignedInfo.F_IsSure = 0;
                                    newmodelT_Bus_AssignedInfo.F_IsReload = 1;
                                    newmodelT_Bus_AssignedInfo.F_ReloadUser = userModel.F_UserCode;
                                    newmodelT_Bus_AssignedInfo.F_ReloadTime = DateTime.Now;
                                    newmodelT_Bus_AssignedInfo.F_IsNext = 0;
                                    newmodelT_Bus_AssignedInfo.F_Id = assignBLL.Add(newmodelT_Bus_AssignedInfo);

                                    #region 保存工单信息

                                    modelT_Bus_WorkOrder.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;
                                    modelT_Bus_WorkOrder.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;
                                 //   modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                                 //   modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;

                                    int n = Int32.Parse(DbHelperSQL.GetSingle("select count(1) from T_Bus_AssignedInfo WITH(NOLOCK) where F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and  F_State=1 and F_IsSure=1 and F_IsDelete=0 and isnull(F_IsReload,0)>0").ToString());
                                    modelT_Bus_WorkOrder.F_IsReload = n + 1;

                                    modelT_Bus_WorkOrder.F_IsOverdue = 0;
                                    //modelT_Bus_WorkOrder.F_WorkState = 8;//重办中
                                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.reload;//重办中
                                    modelT_Bus_WorkOrder.F_Result = "";
                                    modelT_Bus_WorkOrder.F_DealDeptId = null;
                                    modelT_Bus_WorkOrder.F_DealUser = "";
                                    modelT_Bus_WorkOrder.F_DealTime = null;
                                    workorderBLL.Update(modelT_Bus_WorkOrder);

                                    #region 改为未查收
                                    modelT_Bus_AssignedInfo.F_IsSure = 0;
                                    assignBLL.Update(modelT_Bus_AssignedInfo); 
                                    #endregion

                                    var users = userBLL.GetModelList(" F_DeptId='" + modelT_Bus_AssignedInfo.F_MainDeptId + "' ");
                                     

                                    if (users != null && users.Count > 0)
                                    {
                                        foreach (var u in users)
                                        {

                                            if (!string.IsNullOrEmpty(u.F_Mobile))
                                            {
                                                string count = "你有重办工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                                //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                                //bool v = new SMSController().AddSmS(1963441, userId, count, mag, u.F_Mobile);

                                                  string v = sendCs(userId, count, u.F_Mobile, modelT_Bus_WorkOrder.F_WorkOrderId);
                                             }
                                            if (!string.IsNullOrEmpty(u.F_Telephone))
                                            {
                                                var userlist = u.F_Telephone.Split(',');
                                                if (userlist != null)
                                                {
                                                    foreach (var it in userlist)
                                                    {
                                                        string count = "你有重办工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                                        //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                                        //bool v = new SMSController().AddSmS(1963441, userId, count, mag, it);

                                                string v = sendCs(userId, count, it, modelT_Bus_WorkOrder.F_WorkOrderId);
                                            }

                                                }

                                            }
                                        }
                                    }
                                    #region 重办待交办时-主办单位清空 zhengbingbing 20191016
                                    //  modelT_Bus_WorkOrder.F_MainDeptId = null;
                                    //  modelT_Bus_WorkOrder.F_OtherDeptIds = "";
                                    //  modelT_Bus_WorkOrder.F_DealDeptId = null;
                                    #endregion
                                    // workorderBLL.Update(modelT_Bus_WorkOrder);
                                    #endregion
                                    #endregion
                                    #region 插入操作记录
                                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                                    oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " 退回重办了工单，重办原因：" + reason;
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;

                                    operBLL.Add(oper);
                                    
                                    #endregion
                                }

                            }
                            trans.Complete();
                        }
                    
                    return Success("操作成功");
                
            }
            else
            {
                return Error("权限不足");
            }
        }
        /// <summary>
        /// 重办提交工单 提交后为重办待交办
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult SubReloadWorkOrder1(string[] ids, string reason)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZJZY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                if (ids != null && ids.Length > 0)
                {
                    foreach (string str in ids)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(str);
                           var roadworkid = modelT_Bus_WorkOrder.F_WorkOrderId;
                            if (modelT_Bus_WorkOrder != null)
                            {
                                if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.visit || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.rejload
                                    || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.closed
                                    || modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)
                                {
                                    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(modelT_Bus_WorkOrder.F_WorkOrderId);
                                    #region 保存工单信息
                                    //modelT_Bus_WorkOrder.F_SubmitTime = DateTime.Now;
                                    //modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.resubmit;//待交办
                                    //Model.T_Bus_AssignedInfo newmodelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                                    //newmodelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                    //newmodelT_Bus_AssignedInfo.F_LimitTime = modelT_Bus_AssignedInfo.F_LimitTime;//办理时限
                                    //newmodelT_Bus_AssignedInfo.F_MainDeptId = null;// modelT_Bus_AssignedInfo.F_MainDeptId;//主办单位id
                                    //newmodelT_Bus_AssignedInfo.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;//协办单位id
                                    //newmodelT_Bus_AssignedInfo.F_AssignedOpinion = reason;//交办意见
                                    //newmodelT_Bus_AssignedInfo.F_State = 0;
                                    //newmodelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                    //newmodelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                    //newmodelT_Bus_AssignedInfo.F_IsDelete = 0;
                                    //newmodelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                    //newmodelT_Bus_AssignedInfo.F_IsSure = 0;
                                    //newmodelT_Bus_AssignedInfo.F_IsReload = 1;
                                    //newmodelT_Bus_AssignedInfo.F_ReloadUser = userModel.F_UserCode;
                                    //newmodelT_Bus_AssignedInfo.F_ReloadTime = DateTime.Now;
                                    //newmodelT_Bus_AssignedInfo.F_IsNext = 0;
                                    //newmodelT_Bus_AssignedInfo.F_Id = assignBLL.Add(newmodelT_Bus_AssignedInfo);

                                    #region 保存工单信息

                                    //modelT_Bus_WorkOrder.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;
                                    //modelT_Bus_WorkOrder.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;
                                    ////   modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                                    ////   modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;

                                    //int n = Int32.Parse(DbHelperSQL.GetSingle("select count(1) from T_Bus_AssignedInfo WITH(NOLOCK) where F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and  F_State=1 and F_IsSure=1 and F_IsDelete=0 and isnull(F_IsReload,0)>0").ToString());
                                    //modelT_Bus_WorkOrder.F_IsReload = n + 1;

                                    //modelT_Bus_WorkOrder.F_IsOverdue = 0;
                                    ////modelT_Bus_WorkOrder.F_WorkState = 8;//重办中
                                    //modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.resubmit;//重办待交办
                                    //modelT_Bus_WorkOrder.F_Result = "";
                                    //modelT_Bus_WorkOrder.F_DealDeptId = null;
                                    //modelT_Bus_WorkOrder.F_DealUser = "";
                                    //modelT_Bus_WorkOrder.F_DealTime = null;

                                    //modelT_Bus_WorkOrder.F_MainDeptId = null;
                                    //modelT_Bus_WorkOrder.F_OtherDeptIds = "";
                                    //modelT_Bus_WorkOrder.F_DealDeptId = null;
                                    //workorderBLL.Update(modelT_Bus_WorkOrder);
                                    modelT_Bus_WorkOrder.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;
                                    modelT_Bus_WorkOrder.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;
                                    //   modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                                    //   modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;

                                    int n = Int32.Parse(DbHelperSQL.GetSingle("select count(1) from T_Bus_AssignedInfo WITH(NOLOCK) where F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and  F_State=1 and F_IsSure=1 and F_IsDelete=0 and isnull(F_IsReload,0)>0").ToString());
                                    modelT_Bus_WorkOrder.F_IsReload = n + 1;

                                    modelT_Bus_WorkOrder.F_IsOverdue = 0;
                                    //modelT_Bus_WorkOrder.F_WorkState = 8;//重办中
                                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.resubmit;//重办待交办
                                    modelT_Bus_WorkOrder.F_Result = "";
                                    modelT_Bus_WorkOrder.F_DealDeptId = null;
                                    modelT_Bus_WorkOrder.F_DealUser = "";
                                    modelT_Bus_WorkOrder.F_DealTime = null;

                                    modelT_Bus_WorkOrder.F_MainDeptId = null;
                                    modelT_Bus_WorkOrder.F_OtherDeptIds = "";
                                    modelT_Bus_WorkOrder.F_DealDeptId = null;
                                    modelT_Bus_WorkOrder.F_WorkOrderId = workorderBLL.GetNewWorkOrderID(modelT_Bus_WorkOrder.F_CreateUser);
                                    if (modelT_Bus_WorkOrder.F_InfoConBigType!=null&& modelT_Bus_WorkOrder.F_InfoConBigType>0)
                                    {
                                        var information = DbHelperSQL.GetSingle("select dbo.GetDictionaryNames('" + modelT_Bus_WorkOrder.F_InfoConBigType + "')");
                                        if (information != null && information.ToString() == "敏感")
                                        {
                                            modelT_Bus_WorkOrder.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId + "-敏感";
                                        }
                                    }
                                    modelT_Bus_WorkOrder.F_MainWorkOrderId =  roadworkid;
                                    modelT_Bus_WorkOrder.F_Files = "";

                                    workorderBLL.Add(modelT_Bus_WorkOrder);
                                    #region 重办待交办时-主办单位清空 zhengbingbing 20191016
                                    //modelT_Bus_WorkOrder.F_MainDeptId = null;
                                    //modelT_Bus_WorkOrder.F_OtherDeptIds = "";
                                    //modelT_Bus_WorkOrder.F_DealDeptId = null;
                                    #endregion
                                    // workorderBLL.Update(modelT_Bus_WorkOrder);
                                    #endregion
                                    #endregion
                                    #region 插入操作记录
                                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                                    oper.F_WorkOrderId = roadworkid;
                                    oper.F_State = modelT_Bus_WorkOrder.F_WorkState;

                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " 提交了重办待交办工单,编号"+ modelT_Bus_WorkOrder.F_WorkOrderId + "，重办待交办原因：" + reason;
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;

                                    operBLL.Add(oper);

                                    #endregion
                                }

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


        /// <summary>
        /// 驳回重办，驳回后状态为重办驳回状态
        /// 调度员可驳回
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult RejReloadWorkOrder(string id,string reason)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                if (!string.IsNullOrEmpty(id))
                {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(id.Trim());
                        if (modelT_Bus_WorkOrder != null)
                        {
                            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetModelList(" F_WorkOrderId='"+modelT_Bus_WorkOrder.F_WorkOrderId+ "' order by F_CreateTime desc ").FirstOrDefault();
                            if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.resubmit)
                            {
                                #region 保存工单信息
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.rejload;//重办驳回

                                if (modelT_Bus_AssignedInfo != null)
                                {
                                    Model.T_Bus_Feedback modelT_Bus_Feedback = feedbackBLL.GetModelList(" F_AssignedId=" + modelT_Bus_AssignedInfo.F_Id + " and F_IsFeedEnd=1 and   F_State=1  order by F_CreateTime desc").FirstOrDefault();
                                    #region 重办驳回时-恢复主办单位 zhengbingbing 20191017
                                    modelT_Bus_WorkOrder.F_MainDeptId = modelT_Bus_AssignedInfo.F_MainDeptId;
                                    modelT_Bus_WorkOrder.F_OtherDeptIds = modelT_Bus_AssignedInfo.F_OtherDeptIds;
                                    modelT_Bus_WorkOrder.F_DealDeptId = modelT_Bus_Feedback.F_CreateDeptId;
                                    modelT_Bus_WorkOrder.F_DealUser = modelT_Bus_Feedback.F_CreateUser;
                                    modelT_Bus_WorkOrder.F_DealTime = modelT_Bus_Feedback.F_CreateTime;
                                    #endregion
                                }
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                #endregion

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

                                string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                oper.F_Message = userinfo + " 驳回重办工单，驳回原因：" + reason;
                                oper.F_CreateUser = userModel.F_UserCode;
                                oper.F_CreateTime = DateTime.Now;
                                oper.F_IsDelete = 0;

                                operBLL.Add(oper);

                                #endregion
                            }

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

        /// <summary>
        /// 重办工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult NewReloadWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            //if (userModel.F_RoleCode == "ZJZY" || userModel.F_RoleCode == "GLY")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                string maindeptid = RequestString.GetFormString("maindeptid");
                string otherdeptids = RequestString.GetFormString("otherdeptids");
                DateTime limittime = DateTime.Parse(RequestString.GetFormString("limittime"));
                string assignedopinion = RequestString.GetFormString("assignedopinion");
                Model.T_Bus_WorkOrder modeT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                var deptlist = new BLL.T_Sys_Department().GetModelList("F_DeptId in (" + maindeptid + ")");
                if (modelT_Bus_WorkOrder != null)
                {
                    //if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                    //{
                    //    return Error("操作失败");
                    //}

                    if (!string.IsNullOrEmpty(otherdeptids))
                    {
                        if (otherdeptids.Split(',').Contains(maindeptid.ToString()))
                        {
                            return Error("主办单位不能出现在协办单位");
                        }
                    }
                    if (limittime < DateTime.Now)
                    {
                        return Error("办理时限不能小于当前时间");
                    }

                    //if (modelT_Bus_WorkOrder.F_WorkState == 7)
                    //if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.visit)
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.resubmit)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            if (deptlist.Count == 1)
                            {
                                Model.T_Bus_AssignedInfo newmodelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                                newmodelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                newmodelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                newmodelT_Bus_AssignedInfo.F_MainDeptId = deptlist[0].F_DeptId ;//主办单位id
                                newmodelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                                newmodelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见

                                newmodelT_Bus_AssignedInfo.F_State = 1;
                                newmodelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                newmodelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                newmodelT_Bus_AssignedInfo.F_IsDelete = 0;
                                newmodelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                newmodelT_Bus_AssignedInfo.F_IsSure = 0;
                                newmodelT_Bus_AssignedInfo.F_IsReload = 1;
                                newmodelT_Bus_AssignedInfo.F_ReloadUser = userModel.F_UserCode;
                                newmodelT_Bus_AssignedInfo.F_ReloadTime = DateTime.Now;
                                newmodelT_Bus_AssignedInfo.F_IsNext = 0;
                                newmodelT_Bus_AssignedInfo.F_Id = assignBLL.Add(newmodelT_Bus_AssignedInfo);

                                #region 保存工单信息

                                modelT_Bus_WorkOrder.F_MainDeptId = deptlist[0].F_DeptId;
                                modelT_Bus_WorkOrder.F_OtherDeptIds = otherdeptids;
                                // modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                                // modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;

                                int n = Int32.Parse(DbHelperSQL.GetSingle("select count(1) from T_Bus_AssignedInfo WITH(NOLOCK) where F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and  F_State=1 and F_IsSure=1 and F_IsDelete=0 and isnull(F_IsReload,0)>0").ToString());
                                modelT_Bus_WorkOrder.F_IsReload = n + 1;
                                modelT_Bus_WorkOrder.F_LimitTime = limittime;
                                modelT_Bus_WorkOrder.F_Scanning = limittime.AddDays(3);
                                modelT_Bus_WorkOrder.F_IsOverdue = 0;
                                //modelT_Bus_WorkOrder.F_WorkState = 8;//重办中
                                modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.reload;//重办中
                                modelT_Bus_WorkOrder.F_Result = "";
                                modelT_Bus_WorkOrder.F_DealDeptId = null;
                                modelT_Bus_WorkOrder.F_DealUser = "";
                                modelT_Bus_WorkOrder.F_DealTime = null;
                                workorderBLL.Update(modelT_Bus_WorkOrder);
                                #endregion

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

                                string deptname = "";
                                #region 20191021调整为多个主办单位时调整
                                //var deptinfo = new BLL.T_Sys_Department().GetModel(modelT_Bus_AssignedInfo.F_MainDeptId.Value);
                                var deptinfo = new BLL.T_Sys_Department().GetModel(deptlist[0].F_DeptId);
                                if (deptinfo != null) { deptname = deptinfo.F_DeptName; }
                                #endregion

                                string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                oper.F_Message = userinfo + " 重办了工单，主办单位：" + deptname;
                                if (!string.IsNullOrEmpty(otherdeptids))
                                {
                                    string sql = "select dbo.GetDeptNames('" + otherdeptids + "')";
                                    oper.F_Message += "，协办单位：" + DbHelperSQL.GetSingle(sql);
                                }

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

                                operBLL.Add(oper);

                                //推送消息表
                                var users = userBLL.GetModelList(" F_DeptId='" + deptinfo.F_DeptId + "' ");
                                foreach (var u in users)
                                {
                                    //【巩义市市长热线办公室】发送：编号为：******的重办工单，请及时处理。
                                    if (!string.IsNullOrEmpty(u.F_Mobile))
                                    {
                                        string count = "你有重办工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                        //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                        //bool m = new SMSController().AddSmS(1963441, userId, count, mag, u.F_Mobile);

                                        string v = sendCs(userId, count, u.F_Mobile, modelT_Bus_WorkOrder.F_WorkOrderId);
                                    }
                                    if (!string.IsNullOrEmpty(u.F_Telephone))
                                    {
                                        var userlist = u.F_Telephone.Split(',');
                                        if (userlist != null)
                                        {
                                            string count = "你有重办工单，工单号" + modelT_Bus_WorkOrder.F_WorkOrderId + ",请及时查收。";
                                            //string[] mag = { modelT_Bus_WorkOrder.F_WorkOrderId };
                                            //bool m = new SMSController().AddSmSGroup(1963441, userId, count, mag, userlist, u.F_Telephone);

                                            foreach (string item in userlist)
                                            {
                                                string v = sendCs(userId, count, item, modelT_Bus_WorkOrder.F_WorkOrderId);
                                            }

                                           
                                        }

                                    }
                                }
                                #endregion
                            }
                            else
                            {
                                #region 多单位
                                string newids = ""; string errdeptid = ""; string deptname = "";
                                foreach (var deptmasinfo in deptlist)
                                {
                                    deptname += deptmasinfo.F_DeptName + ",";
                                }
                                foreach (var deptinfo in deptlist)
                                {
                                    //deptname += deptinfo.F_DeptName + ",";
                                    #region 新增工单
                                   var  modelT_Bus_WorkOrder1 = modelT_Bus_WorkOrder;
                                    modelT_Bus_WorkOrder1.F_WorkOrderId = workorderBLL.GetNewWorkOrderID(modelT_Bus_WorkOrder.F_CreateUser);
                                    if (modelT_Bus_WorkOrder1.F_InfoConBigType != null && modelT_Bus_WorkOrder1.F_InfoConBigType > 0)
                                    {
                                        var information = DbHelperSQL.GetSingle("select dbo.GetDictionaryNames('" + modelT_Bus_WorkOrder1.F_InfoConBigType + "')");
                                        if (information != null && information.ToString() == "敏感")
                                        {
                                            modelT_Bus_WorkOrder1.F_WorkOrderId = modelT_Bus_WorkOrder1.F_WorkOrderId + "-敏感";
                                        }
                                    }
                                    Model.T_Bus_AssignedInfo newmodelT_Bus_AssignedInfo = new Model.T_Bus_AssignedInfo();
                                    newmodelT_Bus_AssignedInfo.F_WorkOrderId = modelT_Bus_WorkOrder1.F_WorkOrderId;
                                    newmodelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                                    newmodelT_Bus_AssignedInfo.F_MainDeptId = deptinfo.F_DeptId;//主办单位id
                                    newmodelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                                    newmodelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见

                                    newmodelT_Bus_AssignedInfo.F_State = 1;
                                    newmodelT_Bus_AssignedInfo.F_CreateUser = userModel.F_UserCode;
                                    newmodelT_Bus_AssignedInfo.F_CreateTime = DateTime.Now;
                                    newmodelT_Bus_AssignedInfo.F_IsDelete = 0;
                                    newmodelT_Bus_AssignedInfo.F_IsOverdue = 0;
                                    newmodelT_Bus_AssignedInfo.F_IsSure = 0;
                                    newmodelT_Bus_AssignedInfo.F_IsReload = 1;
                                    newmodelT_Bus_AssignedInfo.F_ReloadUser = userModel.F_UserCode;
                                    newmodelT_Bus_AssignedInfo.F_ReloadTime = DateTime.Now;
                                    newmodelT_Bus_AssignedInfo.F_IsNext = 0;
                                    newmodelT_Bus_AssignedInfo.F_Id = assignBLL.Add(newmodelT_Bus_AssignedInfo);

                                    #endregion
                                    #region 保存工单信息

                                    modelT_Bus_WorkOrder1.F_MainDeptId = deptinfo.F_DeptId;
                                    modelT_Bus_WorkOrder1.F_OtherDeptIds = otherdeptids;
                                    // modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                                    // modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;

                                    int n = Int32.Parse(DbHelperSQL.GetSingle("select count(1) from T_Bus_AssignedInfo WITH(NOLOCK) where F_WorkOrderId='" + modelT_Bus_WorkOrder.F_WorkOrderId + "' and  F_State=1 and F_IsSure=1 and F_IsDelete=0 and isnull(F_IsReload,0)>0").ToString());
                                    modelT_Bus_WorkOrder1.F_IsReload = n + 1;
                                    modelT_Bus_WorkOrder1.F_LimitTime = limittime;
                                    modelT_Bus_WorkOrder1.F_Scanning = limittime.AddDays(3);
                                    modelT_Bus_WorkOrder1.F_IsOverdue = 0;
                                    //modelT_Bus_WorkOrder.F_WorkState = 8;//重办中
                                    modelT_Bus_WorkOrder1.F_WorkState = (int)EnumWorkState.reload;//重办中
                                    modelT_Bus_WorkOrder1.F_Result = "";
                                    modelT_Bus_WorkOrder1.F_DealDeptId = null;
                                    modelT_Bus_WorkOrder1.F_DealUser = "";
                                    modelT_Bus_WorkOrder1.F_DealTime = null;
                                    workorderBLL.Add (modelT_Bus_WorkOrder1);
                                    #endregion

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

                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " 重办了工单，主办单位：" + deptname;
                                    if (!string.IsNullOrEmpty(otherdeptids))
                                    {
                                        string sql = "select dbo.GetDeptNames('" + otherdeptids + "')";
                                        oper.F_Message += "，协办单位：" + DbHelperSQL.GetSingle(sql);
                                    }

                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;
                                    newids += "," + modelT_Bus_WorkOrder1.F_WorkOrderId;
                                    operBLL.Add(oper);

                                    //推送消息表
                                    var users = userBLL.GetModelList(" F_DeptId='" + deptinfo.F_DeptId + "' ");
                                    foreach (var u in users)
                                    {
                                        //【巩义市市长热线办公室】发送：编号为：******的重办工单，请及时处理。
                                        if (!string.IsNullOrEmpty(u.F_Mobile))
                                        {
                                            string count = "你有重办工单，工单号" + modelT_Bus_WorkOrder1.F_WorkOrderId + ",请及时查收。";
                                            //string[] mag = { modelT_Bus_WorkOrder1.F_WorkOrderId };
                                            //bool m = new SMSController().AddSmS(1963441, userId, count, mag, u.F_Mobile);

                                            string v = sendCs(userId, count, u.F_Mobile, modelT_Bus_WorkOrder1.F_WorkOrderId);
                                        }
                                        if (!string.IsNullOrEmpty(u.F_Telephone))
                                        {
                                            var userlist = u.F_Telephone.Split(',');
                                            if (userlist != null)
                                            {
                                                string count = "你有重办工单，工单号" + modelT_Bus_WorkOrder1.F_WorkOrderId + ",请及时查收。";
                                                //string[] mag = { modelT_Bus_WorkOrder1.F_WorkOrderId };
                                                //bool m = new SMSController().AddSmSGroup(1963441, userId, count, mag, userlist, u.F_Telephone);

                                                string v = sendCs(userId, count, u.F_Telephone, modelT_Bus_WorkOrder1.F_WorkOrderId);
                                            }

                                        }
                                    }
                                    #endregion
                                }
                                newids = newids.TrimStart(',');
                                var ids = newids.Split(',');
                                if (ids!=null && ids.Length >0)
                                {
                                    foreach (var it in ids)
                                    {
                                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                                        oper.F_WorkOrderId = it;
                                        oper.F_State = modelT_Bus_WorkOrder.F_WorkState;
                                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                        oper.F_Message = userinfo + " 重办交办多单位，生成新工单:" + newids;
                                        oper.F_CreateUser = userModel.F_UserCode;
                                        oper.F_CreateTime = DateTime.Now;
                                        oper.F_IsDelete = 0;
                                        operBLL.Add(oper);
                                    }
                                }
                                if (ids != null && ids.Length > 0)
                                {
                                     #region 主工单新增部门记录
                                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                                    oper.F_WorkOrderId = workorderid;
                                    oper.F_State = modeT_Bus_WorkOrder.F_WorkState;
                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " 重办交办了工单，主办单位:" + deptname;
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;
                                    operBLL.Add(oper);
                                    #endregion

                                    #region 新增工单记录
                                    oper.F_WorkOrderId = workorderid;
                                    oper.F_State = modeT_Bus_WorkOrder.F_WorkState;
                                    oper.F_Message = userinfo + " 重办交办多单位，生成新工单:" + newids;
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;
                                    operBLL.Add(oper); 
                                    #endregion
                                }
                                modeT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;
                            //    modeT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.closed;// 14;
                            // modeT_Bus_WorkOrder.IsExport = 1;
                                workorderBLL.Update(modeT_Bus_WorkOrder);
                                #endregion
                            }
                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("已经处理过了");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 结案工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult FinishWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            
            //if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY")
            if (userModel.F_RoleCode == "ZJZY"|| userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG"|| userModel.F_RoleCode == "ZXHWY")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                string finalopinion = RequestString.GetFormString("finalopinion");//结案意见
                int issatisfie = RequestString.GetInt("issatisfie", 0);//0不满意 1满意
                int isnotice = RequestString.GetInt("isnotice", 0);//0不通告 1通告
                string deptids = RequestString.GetFormString("deptids");//通告单位
                string noticereson = RequestString.GetFormString("noticereson");//通告原因

                //2020-3-4添加通告选项
                int noticeid = RequestString.GetInt("noticeid", 0);//通告选项id
                string noticeinfo = RequestString.GetFormString("noticeinfo");//通告内容

                int isstandard = RequestString.GetInt("isstandard", 0);//是否规范，0是，1否
                string standardids = RequestString.GetFormString("standardids");//不规范项，记录多项ID（1,2,3）

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                if (modelT_Bus_WorkOrder != null)
                {
                    //if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                    //{
                    //    return Error("操作失败");
                    //}

                    //if (modelT_Bus_WorkOrder.F_WorkState == 7)
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.visit || modelT_Bus_WorkOrder.F_WorkState==(int)EnumWorkState.rejload)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 修改工单记录
                            //modelT_Bus_WorkOrder.F_WorkState = 9;
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;
                            modelT_Bus_WorkOrder.F_IsSatisfie = issatisfie;
                            modelT_Bus_WorkOrder.F_IsClosed = 1;
                            modelT_Bus_WorkOrder.F_CloseUser = userModel.F_UserCode;
                            modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;
                            modelT_Bus_WorkOrder.F_FinalOpinion = finalopinion;
                            modelT_Bus_WorkOrder.F_IsStandard = isstandard;
                            modelT_Bus_WorkOrder.F_StandardIDS = standardids;
                            if (isnotice == 1)
                            {

                                Model.T_Bus_NoticeCriticism modelT_Bus_NoticeCriticism = new Model.T_Bus_NoticeCriticism();
                                modelT_Bus_NoticeCriticism.F_DeptIds = deptids;
                                modelT_Bus_NoticeCriticism.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                                modelT_Bus_NoticeCriticism.F_Content = noticereson;
                                modelT_Bus_NoticeCriticism.F_State = 1;
                                modelT_Bus_NoticeCriticism.F_IsDelete = 0;
                                modelT_Bus_NoticeCriticism.F_CreateTime = DateTime.Now;
                                modelT_Bus_NoticeCriticism.F_CreateUser = userModel.F_UserCode;
                                modelT_Bus_NoticeCriticism.F_NoticeID = noticeid;
                                modelT_Bus_NoticeCriticism.F_NoticeInfo = noticeinfo;
                                new BLL.T_Bus_NoticeCriticism().Add(modelT_Bus_NoticeCriticism);

                                modelT_Bus_AssignedInfo.F_IsNotice = 1;
                                modelT_Bus_AssignedInfo.F_NoticeUser = userModel.F_UserCode;
                                modelT_Bus_AssignedInfo.F_NoticeTime = DateTime.Now;
                                

                                modelT_Bus_WorkOrder.F_IsNotice = 1;
                                modelT_Bus_WorkOrder.F_NoticeDeptIds = deptids;
                            }

                            modelT_Bus_AssignedInfo.F_IsStandard = isstandard;
                            modelT_Bus_AssignedInfo.F_StandardIDS = standardids;

                            assignBLL.Update(modelT_Bus_AssignedInfo);
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 结案了工单，结果：" + (issatisfie == 1 ? "满意" : "不满意");
                            if (isnotice == 1)
                            {
                                string sql = "select dbo.GetDeptNames('" + deptids + "')";
                                oper.F_Message = oper.F_Message + ",并通告了交办单位：" + DbHelperSQL.GetSingle(sql);
                            }
                            if (isstandard == 1)
                            {
                                var sqlstand = "select dbo.GetDictionaryNames('" + standardids + "')";
                                var sts= DbHelperSQL.GetSingle(sqlstand);
                                oper.F_Message = oper.F_Message + "；办理结果出现不规范"+ sts + "情况，请及时查看";
                            }
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);

                            //调用科大讯飞
                            if (modelT_Bus_WorkOrder.F_InfoSource == 7)
                            {
                                Model.T_Bus_Feedback tbf = new BLL.T_Bus_Feedback().GetNewModelByWorkOrderID(oper.F_WorkOrderId);
                                if (tbf != null)
                                {
                                    string deptname = string.Empty;
                                    var deptinfo = new BLL.T_Sys_Department().GetModel(tbf.F_CreateDeptId.Value);
                                    if (deptinfo != null) { deptname = deptinfo.F_DeptName; }
                                    ShangQiuWorkOrderController sqwo = new ShangQiuWorkOrderController();
                                    bool bl = sqwo.SaveReplyInfo(oper.F_WorkOrderId, tbf.F_DealUser, deptname, tbf.F_Result, "3", modelT_Bus_WorkOrder.F_InfoType.Value.ToString());
                                    if (bl)
                                    {
                                        Success("调用成功,工单号：" + oper.F_WorkOrderId);
                                    }
                                    else
                                    {
                                        Error("调用失败,工单号：" + oper.F_WorkOrderId);
                                    }
                                }
                            }
                            #endregion

                            trans.Complete();
                        }

                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("已经处理过了");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 结案工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult ForceFinishWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG" || userModel.F_RoleCode == "ZXHWY")
            //if (userModel.F_RoleCode == "ZJZY" || userModel.F_RoleCode == "GLY")
            {
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                //  string workorderid = RequestString.GetFormString("workorderid");
                string result = RequestString.GetFormString("result");//处理结果
                string finalopinion = RequestString.GetFormString("finalopinion");//结案意见
                int issatisfie = RequestString.GetInt("issatisfie", 0);//0不满意 1满意
                int isnotice = RequestString.GetInt("isnotice", 0);//0不通告 1通告
                string deptids = RequestString.GetFormString("deptids");//通告单位
                string noticereson = RequestString.GetFormString("noticereson");//通告其他原因

                //2020-3-4添加通告选项
                int noticeid = RequestString.GetInt("noticeid", 0);//通告选项id
                string noticeinfo = RequestString.GetFormString("noticeinfo");//通告内容

                int isstandard = RequestString.GetInt("isstandard", 0);//是否规范，0是，1否
                string standardids= RequestString.GetFormString("standardids");//不规范项，记录多项ID（1,2,3）

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null)
                {
                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "DDZG"
                        && userModel.F_RoleCode != "ZXLD")
                    {
                        if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                        {
                            return Error("操作失败");
                        }
                    }
                   

                    using (TransactionScope trans = new TransactionScope())
                    {      
                        #region 修改工单记录
                        modelT_Bus_WorkOrder.F_Result = result;
                        //modelT_Bus_WorkOrder.F_WorkState = 9;
                        modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;
                        modelT_Bus_WorkOrder.F_IsSatisfie = issatisfie;
                        modelT_Bus_WorkOrder.F_IsClosed = 1;
                        modelT_Bus_WorkOrder.F_CloseUser = userModel.F_UserCode;
                        modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;
                        modelT_Bus_WorkOrder.F_FinalOpinion = finalopinion;
                        modelT_Bus_WorkOrder.F_IsStandard = isstandard;
                        modelT_Bus_WorkOrder.F_StandardIDS = standardids;

                        if (isnotice == 1)
                        {
                            Model.T_Bus_NoticeCriticism modelT_Bus_NoticeCriticism = new Model.T_Bus_NoticeCriticism();
                            modelT_Bus_NoticeCriticism.F_DeptIds = deptids;
                            modelT_Bus_NoticeCriticism.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                            modelT_Bus_NoticeCriticism.F_Content = noticereson;
                            modelT_Bus_NoticeCriticism.F_State = 1;
                            modelT_Bus_NoticeCriticism.F_IsDelete = 0;
                            modelT_Bus_NoticeCriticism.F_CreateTime = DateTime.Now;
                            modelT_Bus_NoticeCriticism.F_CreateUser = userModel.F_UserCode;
                            modelT_Bus_NoticeCriticism.F_NoticeID = noticeid;
                            modelT_Bus_NoticeCriticism.F_NoticeInfo = noticeinfo;
                            new BLL.T_Bus_NoticeCriticism().Add(modelT_Bus_NoticeCriticism);

                            modelT_Bus_WorkOrder.F_IsNotice = 1;
                            modelT_Bus_WorkOrder.F_NoticeDeptIds = deptids;

                            if (modelT_Bus_AssignedInfo != null)
                            {
                                modelT_Bus_AssignedInfo.F_IsNotice = 1;
                                modelT_Bus_AssignedInfo.F_NoticeUser = userModel.F_UserCode;
                                modelT_Bus_AssignedInfo.F_NoticeTime = DateTime.Now;
                                
                            }
                        }
                        if (modelT_Bus_AssignedInfo!=null )
                        {
                            modelT_Bus_AssignedInfo.F_IsStandard = isstandard;
                            modelT_Bus_AssignedInfo.F_StandardIDS = standardids;

                            assignBLL.Update(modelT_Bus_AssignedInfo);
                        }
                      
                        workorderBLL.Update(modelT_Bus_WorkOrder);
                        #endregion

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

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        oper.F_Message = userinfo + " 强制结案了工单" ;
                        if (isnotice == 1)
                        {
                            string sql = "select dbo.GetDeptNames('" + deptids + "')";
                            oper.F_Message = oper.F_Message + ",并通告了交办单位：" + DbHelperSQL.GetSingle(sql);
                        }
                        if(isstandard==1)
                        {
                            oper.F_Message = oper.F_Message + ",办理结果出现不规范情况，请及时查看";
                        }
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);

                        //调用科大讯飞
                        //if (modelT_Bus_WorkOrder.F_InfoSource == 7 && modelT_Bus_WorkOrder.F_WorkState == 9)
                        //if (modelT_Bus_WorkOrder.F_InfoSource == 7 && modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.finish)
                        //{
                        //    ShangQiuWorkOrderController sqwo = new ShangQiuWorkOrderController();
                        //    bool bl = sqwo.SaveReplyInfo(oper.F_WorkOrderId, userModel.F_UserCode, userModel.depname, modelT_Bus_WorkOrder.F_Result, "3", modelT_Bus_WorkOrder.F_InfoType.Value.ToString());
                        //    if (bl)
                        //    {
                        //        Success("调用成功,工单号：" + oper.F_WorkOrderId);
                        //    }
                        //    else
                        //    {
                        //        Error("调用失败,工单号：" + oper.F_WorkOrderId);
                        //    }
                        //}
                        #endregion

                        trans.Complete();
                    }

                    return Success("操作成功");
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 删除工单
        /// </summary>
        /// <returns></returns>
        public ActionResult DelWorkOrder(string[] ids)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXHWY" || userModel.F_RoleCode == "ZXBZ" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG"||
                userModel.F_UserCode =="001" || userModel.F_RoleCode == "ZXLD")
            {

                //StringBuilder sb = new StringBuilder();
                foreach (var item in ids)
                {
                    //sb.Append("'" + item + "',");
                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(item);
                    if (modelT_Bus_WorkOrder != null)//0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {


                            #region 修改工单记录
                            //modelT_Bus_WorkOrder.F_IsDelete = 1;
                            //modelT_Bus_WorkOrder.F_DeleteUser= userModel.F_UserCode;
                            //modelT_Bus_WorkOrder.F_DeleteTime = DateTime.Now;

                           //办理过程
                           var Operation = new BLL.T_Bus_Operation().GetModelList($"F_WorkOrderId='{modelT_Bus_WorkOrder.F_WorkOrderId }'");
                           foreach (var cg in Operation)
                            {
                                //cg.F_IsDelete = 1;
                                //cg.F_DeleteTime = DateTime.Now;
                                new BLL.T_Bus_Operation().Delete(cg.F_Id);
                            }

                            //办理过程
                            var AssignedInfo = new BLL.T_Bus_AssignedInfo ().GetModelList($"F_WorkOrderId='{modelT_Bus_WorkOrder.F_WorkOrderId }'");
                            foreach (var cg in AssignedInfo)
                            {
                                //cg.F_IsDelete = 1;
                                //cg.F_DeleteUser = userModel.F_UserCode;
                                //cg.F_DeleteTime = DateTime.Now;
                                new BLL.T_Bus_AssignedInfo().Delete(cg.F_Id);
                            }
                            var AssignedInfo_Next = new BLL.T_Bus_AssignedInfo_Next  ().GetModelList($"F_WorkOrderId='{modelT_Bus_WorkOrder.F_WorkOrderId }'");
                            foreach (var cg in AssignedInfo_Next)
                            {
                                //cg.F_IsDelete = 1;
                                //cg.F_DeleteUser = userModel.F_UserCode;
                                //cg.F_DeleteTime = DateTime.Now;
                                new BLL.T_Bus_AssignedInfo_Next().Delete(cg.F_Id);
                            }
                            var Bus_Feedback = new BLL.T_Bus_Feedback ().GetModelList($"F_WorkOrderId='{modelT_Bus_WorkOrder.F_WorkOrderId }'");
                            foreach (var cg in Bus_Feedback)
                            {
                                //cg.F_IsDelete = 1;
                                //cg.F_DeleteUser = userModel.F_UserCode;
                                //cg.F_DeleteTime = DateTime.Now;
                                new BLL.T_Bus_Feedback().Delete(cg.F_Id);
                            }
                            var Bus_Feedback_Next = new BLL.T_Bus_Feedback_Next().GetModelList($"F_WorkOrderId='{modelT_Bus_WorkOrder.F_WorkOrderId }'");
                            foreach (var cg in Bus_Feedback_Next)
                            {
                                //cg.F_IsDelete = 1;
                                //cg.F_DeleteUser = userModel.F_UserCode;
                                //cg.F_DeleteTime = DateTime.Now;
                                new BLL.T_Bus_Feedback_Next().Delete(cg.F_Id);
                            }
                            var Bus_DelayTime = new BLL.T_Bus_DelayTime ().GetModelList($"F_WorkOrderId='{modelT_Bus_WorkOrder.F_WorkOrderId }'");
                            foreach (var cg in Bus_DelayTime)
                            {
                                //cg.F_IsDelete = 1;
                                //cg.F_DeleteUser = userModel.F_UserCode;
                                //cg.F_DeleteTime = DateTime.Now;
                                new BLL.T_Bus_DelayTime().Delete(cg.F_Id);
                            }

                            //var str = modelT_Bus_WorkOrder.F_WorkOrderId.Split('】');
                            //if (str != null && str.Length > 0)
                            //    modelT_Bus_WorkOrder.F_WorkOrderId = $"【{str[1]}-作废-{DateTime.Now.ToString("yyyyMMdd")}】";

                            string shuzi = modelT_Bus_WorkOrder.F_WorkOrderId;

                            string[] yearstr = shuzi.Split('】');
                            string shuziyear = Regex.Replace(yearstr[0], "[^0-9]", "");
                            int yearid = int.Parse(shuziyear);

                            string[] strs = shuzi.Split('第');            
             
             
                            string shuzires = Regex.Replace(strs[1], "[^0-9]", "");

                            int shuziid = int.Parse(shuzires);

                            if (shuzi.Contains("频"))
                            {
                                DbHelperSQL.ExecuteSql(" delete from T_Bus_WorkOrderPFHelper where F_id='" + shuziid + "' and F_CreateTime like '%" + yearid + "%'");
                            }
                            else {
                                DbHelperSQL.ExecuteSql(" delete from T_Bus_WorkOrderHelper where F_id='" + shuziid + "' and F_CreateTime like '%" + yearid + "%'");

                            }




                            workorderBLL.Delete(modelT_Bus_WorkOrder.F_Id);
                            #endregion

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

                            //string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            //oper.F_Message = userinfo + " 删除了工单";
                            //oper.F_CreateUser = userModel.F_UserCode;
                            //oper.F_CreateTime = DateTime.Now;
                            //oper.F_IsDelete = 0;

                            //operBLL.Add(oper);
                            //#endregion


                    

                            trans.Complete();
                        }

                        if (!string.IsNullOrEmpty(modelT_Bus_WorkOrder.F_MainWorkOrderId))
                        {
                            var modelT_Bus_WorkOrderlist = workorderBLL.GetModelList(" F_MainWorkOrderId='" + modelT_Bus_WorkOrder.F_MainWorkOrderId + "' and F_IsDelete=0  ");


                            if (modelT_Bus_WorkOrderlist.Count == 0)
                            {

                                Model.T_Bus_WorkOrder mainmodelT_Bus_WorkOrder = workorderBLL.GetModel(modelT_Bus_WorkOrder.F_MainWorkOrderId);


                                #region 修改工单记录
                                //mainmodelT_Bus_WorkOrder.F_IsDelete = 1;
                                //mainmodelT_Bus_WorkOrder.F_DeleteUser = userModel.F_UserCode;
                                //mainmodelT_Bus_WorkOrder.F_DeleteTime = DateTime.Now;

                                //办理过程
                                var Operation = new BLL.T_Bus_Operation().GetModelList($"F_WorkOrderId='{mainmodelT_Bus_WorkOrder.F_WorkOrderId }'");
                                foreach (var cg in Operation)
                                {
                                    //cg.F_IsDelete = 1;
                                    //cg.F_DeleteTime = DateTime.Now;
                                    new BLL.T_Bus_Operation().Delete(cg.F_Id);
                                }

                                //办理过程
                                var AssignedInfo = new BLL.T_Bus_AssignedInfo().GetModelList($"F_WorkOrderId='{mainmodelT_Bus_WorkOrder.F_WorkOrderId }'");
                                foreach (var cg in AssignedInfo)
                                {
                                    //cg.F_IsDelete = 1;
                                    //cg.F_DeleteUser = userModel.F_UserCode;
                                    //cg.F_DeleteTime = DateTime.Now;
                                    new BLL.T_Bus_AssignedInfo().Delete(cg.F_Id);
                                }
                                var AssignedInfo_Next = new BLL.T_Bus_AssignedInfo_Next().GetModelList($"F_WorkOrderId='{mainmodelT_Bus_WorkOrder.F_WorkOrderId }'");
                                foreach (var cg in AssignedInfo_Next)
                                {
                                    //cg.F_IsDelete = 1;
                                    //cg.F_DeleteUser = userModel.F_UserCode;
                                    //cg.F_DeleteTime = DateTime.Now;
                                    new BLL.T_Bus_AssignedInfo_Next().Delete(cg.F_Id);
                                }
                                var Bus_Feedback = new BLL.T_Bus_Feedback().GetModelList($"F_WorkOrderId='{mainmodelT_Bus_WorkOrder.F_WorkOrderId }'");
                                foreach (var cg in Bus_Feedback)
                                {
                                    //cg.F_IsDelete = 1;
                                    //cg.F_DeleteUser = userModel.F_UserCode;
                                    //cg.F_DeleteTime = DateTime.Now;
                                    new BLL.T_Bus_Feedback().Delete(cg.F_Id);
                                }
                                var Bus_Feedback_Next = new BLL.T_Bus_Feedback_Next().GetModelList($"F_WorkOrderId='{mainmodelT_Bus_WorkOrder.F_WorkOrderId }'");
                                foreach (var cg in Bus_Feedback_Next)
                                {
                                    //cg.F_IsDelete = 1;
                                    //cg.F_DeleteUser = userModel.F_UserCode;
                                    //cg.F_DeleteTime = DateTime.Now;
                                    new BLL.T_Bus_Feedback_Next().Delete(cg.F_Id);
                                }
                                var Bus_DelayTime = new BLL.T_Bus_DelayTime().GetModelList($"F_WorkOrderId='{mainmodelT_Bus_WorkOrder.F_WorkOrderId }'");
                                foreach (var cg in Bus_DelayTime)
                                {
                                    //cg.F_IsDelete = 1;
                                    //cg.F_DeleteUser = userModel.F_UserCode;
                                    //cg.F_DeleteTime = DateTime.Now;
                                    new BLL.T_Bus_DelayTime().Delete(cg.F_Id);
                                }

                                //var str = mainmodelT_Bus_WorkOrder.F_WorkOrderId.Split('】');
                                //if (str != null && str.Length > 0)
                                //    mainmodelT_Bus_WorkOrder.F_WorkOrderId = $"【{str[1]}-作废-{DateTime.Now.ToString("yyyyMMdd")}】";
                                workorderBLL.Delete(mainmodelT_Bus_WorkOrder.F_Id);
                                #endregion

                                //#region 插入操作记录
                                //Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                                //oper.F_WorkOrderId = mainmodelT_Bus_WorkOrder.F_WorkOrderId;
                                //oper.F_State = mainmodelT_Bus_WorkOrder.F_WorkState;

                                //string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                //oper.F_Message = userinfo + " 删除了工单";
                                //oper.F_CreateUser = userModel.F_UserCode;
                                //oper.F_CreateTime = DateTime.Now;
                                //oper.F_IsDelete = 0;

                                //operBLL.Add(oper);
                                //#endregion


                            }

                        }
                    }



                }

                return Success("删除成功");
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 转媒体工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult ReleaseWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int isrelease = RequestString.GetInt("isrelease", -1);
                if (isrelease != -1)
                {
                    Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                    if (modelT_Bus_WorkOrder != null)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 修改工单记录
                            modelT_Bus_WorkOrder.F_IsRelease = isrelease;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " " + (isrelease == 1 ? "转媒体了" : "收回了转媒体") + "工单";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);
                            #endregion

                            trans.Complete();
                        }

                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("操作失败");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }
        /// <summary>
        /// 申请扫描件延时
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult DelayScanning()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "WLDW" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");

                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                //int state = RequestString.GetInt("state", 0);
                DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime") + " 23:59:59");
                string reason = RequestString.GetFormString("reason");
                string files = RequestString.GetFormString("files");

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_MainDeptId == userModel.F_DeptId)
                {
                    if (modelT_Bus_AssignedInfo.F_IsSure == 1)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            if (userModel.F_RoleCode == "WLDW")
                            {
                                if (userModel.F_DeptId > 0)
                                {
                                    var dept = new BLL.T_Sys_Department().GetModel(userModel.F_DeptId);
                                    if (dept != null)
                                    {

                                        if (dept.F_SMExtensionTime != null)
                                        {
                                            if (((DateTime)dept.F_SMExtensionTime).Month == DateTime.Now.Month
                                           && ((DateTime)dept.F_SMExtensionTime).Year == DateTime.Now.Year)
                                            {
                                                if (dept.F_SMDelayTimes < 4)
                                                {
                                                    dept.F_SMDelayTimes += 1;
                                                    dept.F_SMExtensionTime = DateTime.Now;
                                                    bool n = new BLL.T_Sys_Department().Update(dept);
                                                }
                                                else
                                                    return Error("本单位本月扫描件申请延时已达四次");
                                            }
                                            else
                                            {
                                                dept.F_SMDelayTimes = 1;
                                                dept.F_SMExtensionTime = DateTime.Now;
                                                bool n = new BLL.T_Sys_Department().Update(dept);
                                            }
                                        }
                                        else
                                        {
                                            dept.F_SMDelayTimes = 1;
                                            dept.F_SMExtensionTime = DateTime.Now;
                                            bool n = new BLL.T_Sys_Department().Update(dept);
                                        }


                                    }
                                }
                            }
                            #region 保存工单信息
                            //modelT_Bus_WorkOrder.F_WorkState = 5;//延时审核中
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.auditdelay;//延时审核中
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

                            #region 插入申请延时信息
                            Model.T_Bus_DelayTime delay = new Model.T_Bus_DelayTime();
                            delay.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                            //delay.F_State = state;
                            delay.F_OldTime = modelT_Bus_AssignedInfo.F_LimitTime;
                            delay.F_NewTime = newlimittime;


                            delay.F_Reason = reason;
                            delay.F_State = 2;
                            delay.F_IsAudit = 0;
                            delay.F_IsDelete = 0;
                            delay.F_AssignedId = modelT_Bus_AssignedInfo.F_Id;
                            delay.F_CreateUser = userModel.F_UserCode;
                            delay.F_CreateTime = DateTime.Now;
                            delay.F_File = files;

                            new BLL.T_Bus_DelayTime().Add(delay);
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 申请了延时处理";
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);

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

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("操作失敗，已查收");
                    }

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 审核延时工单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AuditDelayScanning()
        {

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int state = RequestString.GetInt("state", 0);
                string reason = RequestString.GetFormString("reason");
                DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime") + " 23:59:59");

                int delayid = RequestString.GetInt("delayid", 0);

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                Model.T_Bus_DelayTime modelT_Bus_DelayTime = new BLL.T_Bus_DelayTime().GetModel(delayid);
                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);

                if (modelT_Bus_WorkOrder != null && modelT_Bus_DelayTime != null && modelT_Bus_AssignedInfo != null)
                {
                    //if (modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                    //{
                    //    return Error("操作失败");
                    //}

                    if (modelT_Bus_DelayTime.F_IsAudit == 0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 保存工单信息
                            //modelT_Bus_WorkOrder.F_WorkState = 4;//办理中
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.dealing;//办理中
                            if (modelT_Bus_DelayTime.F_State ==2)
                            modelT_Bus_WorkOrder.F_Scanning  = newlimittime;
                            else
                                modelT_Bus_WorkOrder.F_LimitTime  = newlimittime;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

                            #region 保存审核信息
                            modelT_Bus_DelayTime.F_IsAudit = state;//审核
                            modelT_Bus_DelayTime.F_AuditUser = userModel.F_UserCode;
                            modelT_Bus_DelayTime.F_AuditTime = DateTime.Now;
                            modelT_Bus_DelayTime.F_RefuseReason = reason;
                            modelT_Bus_DelayTime.F_AgreeTime = newlimittime;
                            new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime);
                            #endregion
                            string type = "同意"; string des = "";
                            if (modelT_Bus_DelayTime.F_IsAudit == 1)
                            {
                                #region 修改交办记录

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

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

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

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " " + type + "了工单延时申请" + des;
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);

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

                            trans.Complete();
                        }
                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("此审核已经处理");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }
        /// <summary>
        /// 批量审核延时
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult AuditDelayScanningBatch(string ids)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                int state = RequestString.GetInt("state", 0);
                string reason = RequestString.GetFormString("reason");
                DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime") + " 23:59:59");
                string errids = ""; string errids1 = "";
                if (!string.IsNullOrEmpty(ids))
                {
                    string[] strids = ids.Split(',');
                    foreach (string str in strids)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(str);
                            Model.T_Bus_DelayTime modelT_Bus_DelayTime = new BLL.T_Bus_DelayTime().GetModelList("   F_WorkOrderId = '" + str + "' and F_State = 1 and F_IsDelete = 0 and F_IsAudit = 0 order by  F_CreateTime desc").FirstOrDefault();
                            Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(str);

                            if (modelT_Bus_WorkOrder != null && modelT_Bus_DelayTime != null && modelT_Bus_AssignedInfo != null)
                            {
                                //if (modelT_Bus_AssignedInfo.F_CreateUser != userModel.F_UserCode)
                                //{
                                //    errids += str + ",";
                                //    continue;
                                //}

                                if (modelT_Bus_DelayTime.F_IsAudit == 0)
                                {
                                    #region 保存工单信息
                                    modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.dealing;//办理中
                                    if (modelT_Bus_DelayTime.F_State == 2)
                                        modelT_Bus_WorkOrder.F_Scanning = newlimittime;
                                    else
                                        modelT_Bus_WorkOrder.F_LimitTime = newlimittime;
                                    workorderBLL.Update(modelT_Bus_WorkOrder);
                                    #endregion

                                    #region 保存审核信息
                                    modelT_Bus_DelayTime.F_IsAudit = state;//审核
                                    modelT_Bus_DelayTime.F_AuditUser = userModel.F_UserCode;
                                    modelT_Bus_DelayTime.F_AuditTime = DateTime.Now;
                                    modelT_Bus_DelayTime.F_RefuseReason = reason;
                                    modelT_Bus_DelayTime.F_AgreeTime = newlimittime;
                                    new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime);
                                    #endregion
                                    string type = "同意"; string des = "";
                                    if (modelT_Bus_DelayTime.F_IsAudit == 1)
                                    {
                                        #region 修改交办记录

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

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

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

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

                                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                                    oper.F_Message = userinfo + " " + type + "了工单延时申请" + des;
                                    oper.F_CreateUser = userModel.F_UserCode;
                                    oper.F_CreateTime = DateTime.Now;
                                    oper.F_IsDelete = 0;

                                    operBLL.Add(oper);

                                    //推送消息表
                                    msg.AddInternalMessagesInfo("工单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, modelT_Bus_DelayTime.F_CreateUser, userModel.F_UserCode, (int)EnumSmsType.workorder);
                                    #endregion
                                }
                                else
                                    errids1 += str + ",";

                            }
                            trans.Complete();
                        }
                    }
                    if (errids1 != "" && errids != "")
                        return Success("操作成功");
                    else
                    {
                        string msg = "";
                        if (errids1 != "")
                            msg += "，工单编号为" + errids1.Trim(',') + "的工单已被其他人审核";
                        if (errids != "")
                            msg += "，工单编号为" + errids1.Trim(',') + "的工单不是交办人本人";
                        return Error("部分工单操作失败" + msg);
                    }
                }
                else
                {
                    return Error("参数获取失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }
        ///// <summary>
        ///// 通告和撤销通告
        ///// </summary>
        ///// <returns></returns>
        //[Authority]
        //public ActionResult NoticeWorkOrder()
        //{
        //    int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

        //    if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" ||userModel.F_RoleCode == "ZXLDGLY" || userModel.F_RoleCode == "GLY")
        //    {
        //        int assignid = RequestString.GetInt("id", 0);
        //        int isnotice = RequestString.GetInt("isnotice", -1);
        //        Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetModel(assignid);
        //        if (modelT_Bus_AssignedInfo != null)
        //        {
        //            if (isnotice == 0 && modelT_Bus_AssignedInfo.F_IsNotice == 1)
        //            {
        //                using (TransactionScope trans = new TransactionScope())
        //                {
        //                    #region 修改交办记录
        //                    modelT_Bus_AssignedInfo.F_IsNotice = 0;
        //                    assignBLL.Update(modelT_Bus_AssignedInfo);
        //                    #endregion

        //                    #region 插入操作记录
        //                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
        //                    oper.F_WorkOrderId = modelT_Bus_AssignedInfo.F_WorkOrderId;

        //                    var deptinfo = new BLL.T_Sys_Department().GetModel(modelT_Bus_AssignedInfo.F_MainDeptId.Value);
        //                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
        //                    oper.F_Message = userinfo + " 撤销了通告交办单位：" + (deptinfo != null ? deptinfo.F_DeptName : "");
        //                    oper.F_CreateUser = userModel.F_UserCode;
        //                    oper.F_CreateTime = DateTime.Now;
        //                    oper.F_IsDelete = 0;

        //                    operBLL.Add(oper);
        //                    #endregion

        //                    trans.Complete();
        //                }

        //                return Success("操作成功");
        //            }
        //            else if (isnotice == 1 && modelT_Bus_AssignedInfo.F_IsNotice == 0)
        //            {
        //                using (TransactionScope trans = new TransactionScope())
        //                {
        //                    #region 修改交办记录
        //                    modelT_Bus_AssignedInfo.F_IsNotice = 1;
        //                    assignBLL.Update(modelT_Bus_AssignedInfo);
        //                    #endregion

        //                    #region 插入操作记录
        //                    Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
        //                    oper.F_WorkOrderId = modelT_Bus_AssignedInfo.F_WorkOrderId;

        //                    var deptinfo = new BLL.T_Sys_Department().GetModel(modelT_Bus_AssignedInfo.F_MainDeptId.Value);
        //                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
        //                    oper.F_Message = userinfo + " 通告了交办单位：" + (deptinfo != null ? deptinfo.F_DeptName : "");
        //                    oper.F_CreateUser = userModel.F_UserCode;
        //                    oper.F_CreateTime = DateTime.Now;
        //                    oper.F_IsDelete = 0;

        //                    operBLL.Add(oper);
        //                    #endregion

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

        /// <summary>
        /// 通告和撤销通告
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult NoticeWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                int isnotice = RequestString.GetInt("isnotice", -1);
                string deptids = RequestString.GetFormString("deptids");//通告单位
                string noticereson = RequestString.GetFormString("noticereson");//通告原因
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                if (modelT_Bus_WorkOrder != null)
                {
                    if (isnotice == 0 && modelT_Bus_WorkOrder.F_IsNotice == 1)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 修改工单记录
                            modelT_Bus_WorkOrder.F_IsNotice = 0;
                            modelT_Bus_WorkOrder.F_NoticeDeptIds = "";
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

                            #region 修改通告记录
                            Model.T_Bus_NoticeCriticism modelT_Bus_NoticeCriticism = new BLL.T_Bus_NoticeCriticism().GetModelList(" F_WorkOrderId='" + workorderid + "' and F_IsDelete=0 ").FirstOrDefault();
                            modelT_Bus_NoticeCriticism.F_IsDelete = 1;
                            modelT_Bus_NoticeCriticism.F_DeleteTime = DateTime.Now;
                            modelT_Bus_NoticeCriticism.F_DeleteUser = userModel.F_UserCode;
                            new BLL.T_Bus_NoticeCriticism().Update(modelT_Bus_NoticeCriticism);
                            #endregion

                            #region 插入操作记录
                            Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                            oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;

                            string sql = "select dbo.GetDeptNames('" + modelT_Bus_NoticeCriticism.F_DeptIds + "')";
                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 撤销了通告交办单位：" + DbHelperSQL.GetSingle(sql).ToString();
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);
                            #endregion

                            trans.Complete();
                        }

                        return Success("操作成功");
                    }
                    else if (isnotice == 1 && modelT_Bus_WorkOrder.F_IsNotice == 0)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            #region 修改工单记录
                            modelT_Bus_WorkOrder.F_IsNotice = 1;
                            modelT_Bus_WorkOrder.F_NoticeDeptIds = deptids;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

                            #region 新增通告记录
                            Model.T_Bus_NoticeCriticism modelT_Bus_NoticeCriticism = new Model.T_Bus_NoticeCriticism();
                            modelT_Bus_NoticeCriticism.F_DeptIds = deptids;
                            modelT_Bus_NoticeCriticism.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                            modelT_Bus_NoticeCriticism.F_Content = noticereson;
                            modelT_Bus_NoticeCriticism.F_State = 1;
                            modelT_Bus_NoticeCriticism.F_IsDelete = 0;
                            modelT_Bus_NoticeCriticism.F_CreateTime = DateTime.Now;
                            modelT_Bus_NoticeCriticism.F_CreateUser = userModel.F_UserCode;
                            new BLL.T_Bus_NoticeCriticism().Add(modelT_Bus_NoticeCriticism);
                            #endregion

                            #region 插入操作记录
                            Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                            oper.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;

                            string sql = "select dbo.GetDeptNames('" + deptids + "')";
                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 通告了交办单位：" + DbHelperSQL.GetSingle(sql).ToString();
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);
                            #endregion

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

        /// <summary>
        /// 市民催单
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult AdditionalWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

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

                    #region 插入附加记录
                    //批示记录
                    Model.T_Bus_Additional model_T_Bus_Additional = new Model.T_Bus_Additional();
                    model_T_Bus_Additional.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;//工单流水号
                    model_T_Bus_Additional.F_Title = title;
                    model_T_Bus_Additional.F_Content = content;
                    if (!string.IsNullOrEmpty(callid))
                    {
                        model_T_Bus_Additional.F_CallId = callid;
                        var rd = new BLL.T_Call_CallRecords().GetModelByCallId(callid);
                        if (rd != null)
                        {
                            model_T_Bus_Additional.F_CallRecordId = rd.CallRecordsId;
                        }
                    }

                    model_T_Bus_Additional.F_File = files;//附件
                    model_T_Bus_Additional.F_CreateUser = userModel.F_UserCode;//呈批人
                    model_T_Bus_Additional.F_CreateTime = DateTime.Now;//呈批时间
                    model_T_Bus_Additional.F_IsDelete = 0;
                    model_T_Bus_Additional.F_State = 1;//审批状态（0:未处理，1:通过）
                    new BLL.T_Bus_Additional().Add(model_T_Bus_Additional);
                    #endregion

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

                    string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                    oper.F_Message = userinfo + " 接到市民催单，内容：" + content;
                    oper.F_CreateUser = userModel.F_UserCode;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;

                    operBLL.Add(oper);
                    #endregion
                    #region 根据状态不同给出提醒
                    var sqlusers = " F_DeleteFlag=0 ";
                    #region 获取被提醒人
                    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetNewModelByWorkOrderID(workorderid);
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.neworder)
                        sqlusers += " and F_UserCode='"+ modelT_Bus_WorkOrder.F_CreateUser + "'";//"新工单"向添加人提醒
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit)
                        sqlusers += " and F_RoleId in (select F_RoleId from T_Sys_RoleInfo WITH(NOLOCK) where F_RoleCode='ZXLD')";//"待交办"向所有调度提醒
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.receive)
                    {
                        if (modelT_Bus_AssignedInfo != null && modelT_Bus_AssignedInfo.F_MainDeptId != null)
                            sqlusers += " and F_DeptId='" + modelT_Bus_AssignedInfo.F_MainDeptId + "' ";//"待查收"向被指派单位的所有人提醒
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.auditreback)
                    {
                        if (modelT_Bus_AssignedInfo != null )
                            sqlusers += " and F_UserCode='" + modelT_Bus_AssignedInfo.F_CreateUser + "' ";//"退回审核中"向指派人提醒
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealing)
                    {
                        if (modelT_Bus_AssignedInfo != null && !string.IsNullOrEmpty(modelT_Bus_AssignedInfo.F_SureUser))
                            sqlusers += " and F_UserCode='" + modelT_Bus_AssignedInfo.F_SureUser + "' ";//"办理中"向查收人提醒
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.auditdelay)
                    {
                        if (modelT_Bus_AssignedInfo != null)
                            sqlusers += " and F_UserCode='" + modelT_Bus_AssignedInfo.F_CreateUser + "' ";//"延时审核中"
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.dealed)
                    {
                        sqlusers += " and F_RoleId in (select F_RoleId from T_Sys_RoleInfo WITH(NOLOCK) where F_RoleCode='ZJZY')";//"已办理"向所有质检提醒
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.visit)
                    {
                        sqlusers += " and F_RoleId in (select F_RoleId from T_Sys_RoleInfo WITH(NOLOCK) where F_RoleCode='ZJZY')";//"已回访"向所有质检提醒
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.reload)
                    {
                        if (modelT_Bus_AssignedInfo != null)
                            sqlusers += " and F_UserCode='" + modelT_Bus_AssignedInfo.F_CreateUser + "' ";//"重办中"向指派人提醒
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.audit)
                    {
                        sqlusers += " and F_RoleId in (select F_RoleId from T_Sys_RoleInfo WITH(NOLOCK) where F_RoleCode='ZXBZ')";//"待审核"向坐席班长提醒
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.resubmit)
                    {
                        if (modelT_Bus_AssignedInfo != null)
                            sqlusers += " and F_UserCode='" + modelT_Bus_AssignedInfo.F_CreateUser + "' ";//"重办待交办"向指派人提醒
                    }
                    if (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.rejload)
                    {
                        sqlusers += " and F_RoleId in (select F_RoleId from T_Sys_RoleInfo WITH(NOLOCK) where F_RoleCode='ZJZY')";//"重办驳回"向所有质检提醒
                    }
                    #endregion
                    var userlists = userBLL.GetModelList(sqlusers);
                    //推送消息表
                    foreach (var u in userlists)
                    {
                        msg.AddInternalMessagesInfo("催单消息", oper.F_Message + "，工单编号：" + oper.F_WorkOrderId, u.F_UserCode, userModel.F_UserCode, (int)EnumSmsType.additional);
                    }
                    #endregion
                    trans.Complete();
                }
                return Success("操作成功");
            }
            else
            {
                return Error("操作失败");
            }
        }
        #endregion

        #region 语音附件其他
        /// <summary>
        /// 验证当前单位是否交办单位
        /// </summary>
        /// <param name="modelT_Bus_AssignedInfo"></param>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public int AssignDeptType(Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo, int deptid)
        {
            int type = 0;
            if (modelT_Bus_AssignedInfo.F_MainDeptId == deptid)
            {
                type = 1;//主办
            }
            else if (!string.IsNullOrEmpty(modelT_Bus_AssignedInfo.F_OtherDeptIds) && modelT_Bus_AssignedInfo.F_OtherDeptIds.Split(',').Contains(deptid.ToString()))
            {
                type = 2;//协办
            }
            return type;
        }

        /// <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(" CallRecordsId='" + cid + "' ").FirstOrDefault();
            if (luyin != null)
            {
                if (!string.IsNullOrEmpty(luyin.FilePath))
                {
                    var ym = prefix;
                    ym = ym.Substring(0, ym.Length - 1);
                    string lujing = luyin.FilePath.Substring(luyin.FilePath.IndexOf(':') + 1).Replace('\\', '/');
                    path = ym + lujing;

                    //if (!CommonHelper.FileIsExist(path))
                    //{
                    //    path = lujing;
                    //}
                }
            }
            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 WITH(NOLOCK) where F_FileId in (" + ids + ") order by F_AddTime desc").Tables[0];

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

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

            dt.Columns.Add("Files", typeof(object));
            dt.Columns.Add("HCFiles", typeof(object));
            foreach (DataRow dr in dt.Rows)
            {

                if (dr["F_Files"] != null && dr["F_Files"].ToString() != "")
                {
                    dr["Files"] = GetFileData(dr["F_Files"].ToString(), prefix);
                }
                    
                if (dr["F_HCFiles"] != null && dr["F_HCFiles"].ToString() != "")
                {
                        dr["HCFiles"] = GetFileData(dr["F_HCFiles"].ToString(), prefix);
                 }
              
            }
            return dt;
        }
        #endregion

        #region 修改工单 by admin

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetInfoByAdmin(int id, int type)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string sql = "select * from ";
                string table = string.Empty;
                switch (type)
                {
                    case 1: table = "T_Bus_AssignedInfo"; break;//交办信息
                    case 2: table = "T_Bus_DelayTime"; break;//延时信息
                    case 3: table = "T_Bus_Feedback"; break;//办理信息
                    case 4: table = "T_Bus_RemindRecord"; break;//督办
                    case 5: table = "T_Bus_SubmitSuper"; break;//1领导批示 2市长指示 3回退
                    case 6: table = "T_Bus_VisitResult"; break;//回访
                }

                string sql = "select * from " + table + "  WITH(NOLOCK) where F_IsDelete=0 and F_Id=" + id;
                var dt = DbHelperSQL.Query(sql).Tables[0];
                return Success("操作成功", dt);
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 修改工单信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult EditWorkOrderByAdmin()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //string workorderid = RequestString.GetFormString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));

                int source = RequestString.GetInt("source", 0);

                string cusname = RequestString.GetFormString("cusname");
                string cussex = RequestString.GetFormString("cussex");
                string cusphone = RequestString.GetFormString("cusphone");
                string cusaddress = RequestString.GetFormString("cusaddress");
                string email = RequestString.GetFormString("email");
                string zipcode = RequestString.GetFormString("zipcode");
                string conname = RequestString.GetFormString("conname");
                string conphone = RequestString.GetFormString("conphone");

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

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

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

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

                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                if (modelT_Bus_WorkOrder != null)
                {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存工单信息

                        modelT_Bus_WorkOrder.F_InfoSource = source;//信息来源

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

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

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

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

                        workorderBLL.Update(modelT_Bus_WorkOrder);
                        #endregion

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

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        oper.F_Message = userinfo + " 修改了工单基本信息";
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);
                        #endregion

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

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Success("权限不足");
            }
        }

        /// <summary>
        /// 修改批示信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult EditSuperInfoByAdmin()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                //int type = RequestString.GetInt("type", 0);//1领导批示 2市长指示
                string superuser = RequestString.GetFormString("superuser");
                string superopinion = RequestString.GetFormString("superopinion");
                string files = RequestString.GetFormString("files");
                int id = RequestString.GetInt("id", 0);

                Model.T_Bus_SubmitSuper model_T_Bus_SubmitSuper = new BLL.T_Bus_SubmitSuper().GetModel(id);
                if (model_T_Bus_SubmitSuper != null)
                {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存批示信息

                        //model_T_Bus_SubmitSuper.F_Type = type;//1领导批示 2市长指示
                        model_T_Bus_SubmitSuper.F_BatchReason = superuser;//批示人
                        model_T_Bus_SubmitSuper.F_SuperOpinion = superopinion;//批示内容
                        if (!string.IsNullOrEmpty(files))
                            model_T_Bus_SubmitSuper.F_File = files;//附件

                        new BLL.T_Bus_SubmitSuper().Update(model_T_Bus_SubmitSuper);
                        #endregion

                        #region 插入操作记录
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = model_T_Bus_SubmitSuper.F_WorkOrderId;
                        oper.F_File = model_T_Bus_SubmitSuper.F_File;

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        oper.F_Message = userinfo + " 修改了工单批示信息";
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);
                        #endregion

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

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 修改交办信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult EditAssignInfoByAdmin()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                int assignid = RequestString.GetInt("id", 0);
                //int maindeptid = RequestString.GetInt("maindeptid", 0);
                //string otherdeptids = RequestString.GetFormString("otherdeptids");
                DateTime limittime = DateTime.Parse(RequestString.GetFormString("limittime"));
                string assignedopinion = RequestString.GetFormString("assignedopinion");

                Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetModel(assignid);
                if (modelT_Bus_AssignedInfo != null)
                {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存交办信息

                        modelT_Bus_AssignedInfo.F_LimitTime = limittime;//办理时限
                        //modelT_Bus_AssignedInfo.F_MainDeptId = maindeptid;//主办单位id
                        //modelT_Bus_AssignedInfo.F_OtherDeptIds = otherdeptids;//协办单位id
                        modelT_Bus_AssignedInfo.F_AssignedOpinion = assignedopinion;//交办意见

                        assignBLL.Update(modelT_Bus_AssignedInfo);
                        #endregion

                        #region 插入操作记录
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = modelT_Bus_AssignedInfo.F_WorkOrderId;
                        oper.F_File = modelT_Bus_AssignedInfo.F_File;

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        oper.F_Message = userinfo + " 修改了工单交办信息";
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);
                        #endregion

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

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 修改办理信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult EditFeedBackInfoByAdmin()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                string dealman = RequestString.GetFormString("dealman");
                string result = RequestString.GetFormString("result");
                string files = RequestString.GetFormString("files");
                int feedbackid = RequestString.GetInt("id", 0);

                Model.T_Bus_Feedback model_T_Bus_Feedback = new BLL.T_Bus_Feedback().GetModel(feedbackid);
                if (model_T_Bus_Feedback != null)
                {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存办理信息

                        model_T_Bus_Feedback.F_DealUser = dealman;
                        model_T_Bus_Feedback.F_Result = result;//反馈内容
                        model_T_Bus_Feedback.F_File = files;

                        new BLL.T_Bus_Feedback().Update(model_T_Bus_Feedback);
                        #endregion

                        #region 保存工单信息
                        int maxid = Int32.Parse(DbHelperSQL.GetSingle("select max(F_Id) from T_Bus_AssignedInfo WITH(NOLOCK) where F_WorkOrderId='" + model_T_Bus_Feedback.F_WorkOrderId + "' and  F_State=1 and F_IsSure=1 and F_IsDelete=0 ").ToString());
                        var assign = assignBLL.GetModel(model_T_Bus_Feedback.F_AssignedId.Value);
                        if (maxid == assign.F_Id)
                        {
                            var order = workorderBLL.GetModel(model_T_Bus_Feedback.F_WorkOrderId);
                            order.F_Result = result;//反馈内容

                            workorderBLL.Update(order);
                        }
                        #endregion

                        #region 插入操作记录
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = model_T_Bus_Feedback.F_WorkOrderId;
                        oper.F_File = model_T_Bus_Feedback.F_File;

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        oper.F_Message = userinfo + " 修改了工单办理信息";
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);
                        #endregion

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

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 修改回访信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult EditVisitInfoByAdmin()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                string visituser = RequestString.GetFormString("visituser");//回访人
                int type = RequestString.GetInt("type", 0);//回访方式
                int issatisfie = RequestString.GetInt("issatisfie", 0);//0不满意 1满意
                int visitid = RequestString.GetInt("id", 0);
                string result = RequestString.GetFormString("result");//回访情况
                string guid = RequestString.GetFormString("guid");

                Model.T_Bus_VisitResult modelT_Bus_VisitResult = new BLL.T_Bus_VisitResult().GetModel(visitid);
                if (modelT_Bus_VisitResult != null)
                {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存回访信息

                        modelT_Bus_VisitResult.F_VisitUser = visituser;
                        modelT_Bus_VisitResult.F_Type = type;
                        modelT_Bus_VisitResult.F_IsSatisfie = issatisfie;
                        modelT_Bus_VisitResult.F_Result = result;

                        new BLL.T_Bus_VisitResult().Update(modelT_Bus_VisitResult);
                        //保存回访记录
                        new BLL.T_Bus_VisitResultRecords().AddInfo(modelT_Bus_VisitResult, userModel.F_UserCode, guid);
                        #endregion

                        #region 插入操作记录
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = modelT_Bus_VisitResult.F_WorkOrderId;
                        oper.F_File = modelT_Bus_VisitResult.F_File;

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        oper.F_Message = userinfo + " 修改了工单回访信息";
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);
                        #endregion

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

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 修改退回审核信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult EditAuditRebackByAdmin()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                string reason = RequestString.GetFormString("reason");
                int rebackid = RequestString.GetInt("id", 0);

                Model.T_Bus_Feedback modelT_Bus_Feedback = new BLL.T_Bus_Feedback().GetModel(rebackid);
                if (modelT_Bus_Feedback != null)
                {
                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存反馈信息
                        modelT_Bus_Feedback.F_AuditReason = reason;//交办意见

                        new BLL.T_Bus_Feedback().Update(modelT_Bus_Feedback);
                        #endregion

                        #region 插入操作记录
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = modelT_Bus_Feedback.F_WorkOrderId;

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        oper.F_Message = userinfo + " 修改了工单退回审核信息";
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);
                        #endregion

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

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }

        /// <summary>
        /// 修改延时审核信息
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult EditAuditDelayByAdmin()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
                string reason = RequestString.GetFormString("reason");
                //DateTime newlimittime = DateTime.Parse(RequestString.GetFormString("newlimittime"));

                int delayid = RequestString.GetInt("id", 0);

                Model.T_Bus_DelayTime modelT_Bus_DelayTime = new BLL.T_Bus_DelayTime().GetModel(delayid);

                if (modelT_Bus_DelayTime != null)
                {
                    Model.T_Bus_AssignedInfo modelT_Bus_AssignedInfo = assignBLL.GetModel(modelT_Bus_DelayTime.F_AssignedId.Value);

                    using (TransactionScope trans = new TransactionScope())
                    {
                        #region 保存延时审核信息
                        modelT_Bus_DelayTime.F_RefuseReason = reason;
                        //modelT_Bus_DelayTime.F_AgreeTime = newlimittime;
                        new BLL.T_Bus_DelayTime().Update(modelT_Bus_DelayTime);
                        #endregion

                        #region 插入操作记录
                        Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
                        oper.F_WorkOrderId = modelT_Bus_DelayTime.F_WorkOrderId;

                        string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        oper.F_Message = userinfo + " 修改了工单延时审核信息";
                        oper.F_CreateUser = userModel.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        operBLL.Add(oper);
                        #endregion

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

                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Error("权限不足");
            }
        }
        #endregion

        #region 县级对接

        /// <summary>
        /// 获取网点列表
        /// </summary>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetCityList(string code, string name)
        {
            string signcode = Configs.GetValue("CityOutSignCode");
            string url = Configs.GetValue("CityOutUrl");
            string outsigncode = CommonHelper.getsigncode("CountyBranch", "GetCityList", signcode);
            string strparams = "?code=" + code + "&name=" + name + "&signcode=" + outsigncode;
            string result = HttpMethods.HttpGet(url + "/CountyBranch/GetCityList" + strparams);
            return Content(result);
        }

        /// <summary>
        /// 获取网点详情
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetCityDetail(string code)
        {
            string signcode = Configs.GetValue("CityOutSignCode");
            string url = Configs.GetValue("CityOutUrl");
            string outsigncode = CommonHelper.getsigncode("CountyBranch", "GetCityDetail", signcode);
            string strparams = "?code=" + code + "&signcode=" + outsigncode;
            string result = HttpMethods.HttpGet(url + "/CountyBranch/GetCityDetail" + strparams);
            return Content(result);
        }

        /// <summary>
        /// 转派工单到县级
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult TurnWorkOrder()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

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

            if (userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXLDGLYGLY" || userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "DDZG")
            {
              //  string workorderid = RequestString.GetQueryString("workorderid");
                string workorderid = HttpUtility.UrlDecode(RequestString.GetFormString("workorderid"));
                string citycode = RequestString.GetFormString("citycode");
                Model.T_Bus_WorkOrder modelT_Bus_WorkOrder = workorderBLL.GetModel(workorderid);
                if (modelT_Bus_WorkOrder != null && (modelT_Bus_WorkOrder.F_WorkState == (int)EnumWorkState.submit))
                {
                    string code = Configs.GetValue("CityCode");
                    var branchmodel = GetCityInfo(code);
                    var citymodel = GetCityInfo(citycode);
                    if (branchmodel != null && citymodel != null)
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            string cityworkorderid = string.Empty;

                            #region 转单

                            string turnsigncode = citymodel["F_Sign"].ToString();
                            string turnurl = citymodel["F_Url"].ToString();
                            string turnoutsigncode = CommonHelper.getsigncode("CountyBusiness", "AddWorkOrder", turnsigncode);
                            string turnstrparams = "workorderid=" + modelT_Bus_WorkOrder.F_WorkOrderId + "&signcode=" + turnoutsigncode
                            + "&citycode=" + branchmodel["F_Code"].ToString() + "&cityname=" + branchmodel["F_Name"].ToString() + "&cusname=" + modelT_Bus_WorkOrder.F_CusName + "&cussex=" + modelT_Bus_WorkOrder.F_CusSex
                            + "&cusphone=" + modelT_Bus_WorkOrder.F_CusPhone + "&cusaddress=" + modelT_Bus_WorkOrder.F_CusAddress + "&email=" + modelT_Bus_WorkOrder.F_Email
                            + "&zipcode=" + modelT_Bus_WorkOrder.F_ZipCode + "&conname=" + modelT_Bus_WorkOrder.F_ConName + "&conphone=" + modelT_Bus_WorkOrder.F_ConPhone
                            + "&title=" + modelT_Bus_WorkOrder.F_ComTitle + "&content=" + modelT_Bus_WorkOrder.F_ComContent + "&sourceaddress=" + modelT_Bus_WorkOrder.F_SourceAddress
                            + "&isprotect=" + modelT_Bus_WorkOrder.F_IsProtect + "&level=" + modelT_Bus_WorkOrder.F_Level;

                            string turnresultstr = HttpMethods.HttpPost(turnurl + "/CountyBusiness/AddWorkOrder", turnstrparams);
                            var turnresult = turnresultstr.ToJObject();
                            if (turnresult["state"].ToString() != "success")
                            {
                                return Content(turnresultstr);
                            }
                            else
                            {
                                cityworkorderid = turnresult["data"].ToString();
                            }

                            #endregion

                            #region 保存工单信息
                            modelT_Bus_WorkOrder.F_WorkState = (int)EnumWorkState.finish;
                            modelT_Bus_WorkOrder.F_IsClosed = 1;
                            modelT_Bus_WorkOrder.F_Result = "已转单到" + citymodel["F_Name"].ToString();
                            modelT_Bus_WorkOrder.F_DealUser = userModel.F_UserCode;
                            modelT_Bus_WorkOrder.F_DealTime = DateTime.Now;
                            modelT_Bus_WorkOrder.F_CloseUser = userModel.F_UserCode;
                            modelT_Bus_WorkOrder.F_CloseTime = DateTime.Now;
                            modelT_Bus_WorkOrder.F_AssignUser = userModel.F_UserCode;
                            modelT_Bus_WorkOrder.F_AssignTime = DateTime.Now;
                            workorderBLL.Update(modelT_Bus_WorkOrder);
                            #endregion

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

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

                                assignBLL.Update(cg);
                            }
                            #endregion

                            #region 新增转单记录
                            Model.T_Bus_CityTurn modelT_Bus_CityTurn = new Model.T_Bus_CityTurn();
                            modelT_Bus_CityTurn.F_CityCode = citycode;
                            modelT_Bus_CityTurn.F_CityName = citymodel["F_Name"].ToString();
                            modelT_Bus_CityTurn.F_CityWorkOrderId = cityworkorderid;
                            modelT_Bus_CityTurn.F_WorkOrderId = modelT_Bus_WorkOrder.F_WorkOrderId;
                            modelT_Bus_CityTurn.F_Type = 2;
                            modelT_Bus_CityTurn.F_State = 1;
                            modelT_Bus_CityTurn.F_IsSure = 0;
                            modelT_Bus_CityTurn.F_IsDelete = 0;
                            modelT_Bus_CityTurn.F_CreateTime = DateTime.Now;

                            new BLL.T_Bus_CityTurn().Add(modelT_Bus_CityTurn);
                            #endregion

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

                            string userinfo = userModel.depname + "-" + userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                            oper.F_Message = userinfo + " 转派工单到 " + citymodel["F_Name"].ToString();
                            oper.F_CreateUser = userModel.F_UserCode;
                            oper.F_CreateTime = DateTime.Now;
                            oper.F_IsDelete = 0;

                            operBLL.Add(oper);
                            #endregion

                            trans.Complete();
                        }

                        return Success("操作成功");
                    }
                    else
                    {
                        return Error("操作失败");
                    }
                }
                else
                {
                    return Error("操作失败");
                }
            }
            else
            {
                return Success("权限不足");
            }
        }

        /// <summary>
        /// 获取当前网点信息
        /// </summary>
        /// <returns></returns>
        public Newtonsoft.Json.Linq.JObject GetCityInfo(string code)
        {
            string signcode = Configs.GetValue("CityOutSignCode");
            string url = Configs.GetValue("CityOutUrl");
            string outsigncode = CommonHelper.getsigncode("CountyBranch", "GetCityDetail", signcode);
            string strparams = "?code=" + code + "&signcode=" + outsigncode;
            var result = HttpMethods.HttpGet(url + "/CountyBranch/GetCityDetail" + strparams).ToJObject();
            if (result["state"].ToString() == "success")
            {
                return result["data"].ToString().ToJObject();
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 添加操作日志
        /// </summary>
        /// <param name="workorderid"></param>
        /// <param name="workstate"></param>
        /// <param name="msgs"></param>
        /// <param name="usercode"></param>
        private void addoptlog(string workorderid,int? workstate,int assid,string msgs,string usercode,int type=0)
        {
            Model.T_Bus_Operation oper = new Model.T_Bus_Operation();
            oper.F_WorkOrderId = workorderid;
            oper.F_State = workstate;
            oper.F_AssignedId = assid;
            oper.F_Message = msgs;
            oper.F_CreateUser = usercode;
            oper.F_CreateTime = DateTime.Now;
            oper.F_IsDelete = 0;
            oper.F_Type = type;

            operBLL.Add(oper);
        }

        #endregion



        public ActionResult  GetCBNumber()
 
        {

            DataTable dt = new DataTable();
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            //int userId = 689;
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            string sql = " and F_IsDelete=0";
          
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
 
             //被催办的工单可以在此列表进行显示处理，二级单位可以在此进行催办处 
 
                    if (strstate.Trim() != "" && strstate != "undefined")
                    {
                        if (strstate.Trim() == ((int)EnumWorkState.neworder).ToString())
                            sql += " and F_WorkState in (" + (int)EnumWorkState.neworder + "," + (int)EnumWorkState.audit + ") ";
                        else
                            sql += " and F_WorkState = '" + strstate.Trim() + "' ";
                    }
                    sql += "  and ReminderNum>0 and F_WorkOrderID in(select F_WorkOrderID from T_Bus_AssignedInfo WITH(NOLOCK) where F_State=1 and F_IsDelete=0 and F_IsSure in (0,1)";

                    if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXLD")
                    {
                        sql += "  and F_WorkState in ('" + (int)EnumWorkState.receive + "','" + (int)EnumWorkState.dealing + "','" + (int)EnumWorkState.reload + "' )";
                        sql += " and F_MainDeptId='" + userModel.F_DeptId + "')";
                    }
                    else
                    {
                        sql += ")";
                    }
 

            Object dtnum = DbHelperSQL.GetSingle(" select count(1) from T_Bus_WorkOrder where 1=1 " + sql);

        
            var obj = new
            {
                state = "success",
                message = "成功",
                cbnum = dtnum
          
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 调度员角色弹框：
        //1、超期未交办提醒：超过3天、6天、9天未交办的工单进行提醒，弹框提示“提示函【2023第xx号】超期未处理，请及时处理”
        //2、点击弹框确认之后，下次不在提醒，比如第一次超3天提醒一次，点击确定之后，下次提醒是第6天的时候
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult SendRemindMsg()
        {


            DataTable dt = new DataTable();
            dt = DbHelperSQL.Query("select * from T_Bus_WorkOrder where F_WorkState=1 and F_IsDelete=0 " +
                " and F_WorkOrderType=1 and dbo.GetDictionaryName(F_InfoConBigType)='敏感' " +
       "and datediff(day , F_CreateTime , getdate())>'" +3 + "' and F_SendMsgDay =0   ").Tables[0];

            DataTable userdt = DbHelperSQL.Query(" select F_usercode from t_sys_useraccount where F_rolecode='ZXLD'").Tables[0];

            if (dt != null & dt.Rows.Count > 0)
            {
                foreach (DataRow item in dt.Rows)
                {

                    foreach (DataRow user in userdt.Rows)
                    {
                        msg.AddInternalMessagesInfo("超期未交办提醒", "提示函 " + item["F_WorkOrderId"].ToString() + "超期未处理，请及时处理\n", user["F_usercode"].ToString(), "8000", (int)EnumSmsType.attention);
                    }
                    DbHelperSQL.ExecuteSql("update T_Bus_WorkOrder set F_SendMsgDay=3 where F_WorkOrderId='" + item["F_WorkOrderId"].ToString() + "'");

                }
            }

            DataTable dt2 = new DataTable();
            dt2 = DbHelperSQL.Query("select * from T_Bus_WorkOrder where F_WorkState=0 and F_IsDelete=0  " +
"and datediff(day , F_CreateTime , getdate())>'" + 6 + "' and F_SendMsgDay =3   ").Tables[0];
            if (dt2 != null & dt2.Rows.Count > 0)
            {
                foreach (DataRow item in dt2.Rows)
                {
                    foreach (DataRow user in userdt.Rows)
                    {
                        msg.AddInternalMessagesInfo("超期未交办提醒", "提示函 " + item["F_WorkOrderId"].ToString() + "超期未处理，请及时处理\n", user["F_usercode"].ToString(), "8000", (int)EnumSmsType.attention);
                    }
                    DbHelperSQL.ExecuteSql("update T_Bus_WorkOrder set F_SendMsgDay=6 where F_WorkOrderId='" + item["F_WorkOrderId"].ToString() + "'");

                }
            }

            DataTable dt3 = new DataTable();
            dt3 = DbHelperSQL.Query("select * from T_Bus_WorkOrder where F_WorkState=0 and F_IsDelete=0  " +
"and datediff(day , F_CreateTime , getdate())>'" + 9 + "' and F_SendMsgDay =6   ").Tables[0];
            if (dt3 != null & dt3.Rows.Count > 0)
            {
                foreach (DataRow item in dt3.Rows)
                {
                    foreach (DataRow user in userdt.Rows)
                    {
                        msg.AddInternalMessagesInfo("超期未交办提醒", "提示函 " + item["F_WorkOrderId"].ToString() + "超期未处理，请及时处理\n", user["F_usercode"].ToString(), "8000", (int)EnumSmsType.attention);
                    }
                    DbHelperSQL.ExecuteSql("update T_Bus_WorkOrder set F_SendMsgDay=9 where F_WorkOrderId='" + item["F_WorkOrderId"].ToString() + "'");

                }
            }


            return Success("发送消息完成");
        }


        //        二级办理单位弹框：
        //1、待查收提醒：新交办给该二级单位办理的工单发送弹框提醒，弹框提示“有新提示函【2023第xx号】未查收，请及时查收处理”
        //2、催办提醒：催办给对应二级单位发送提醒，弹框提示“催办提示函【2023第xx号】未处理，请及时处理”

        //3、按交办时间算)超期未处理提醒：超过3天、6天、9天未进行处理的工单进行提醒，弹框提示“提示函【2023第xx号】超期未处理，请及时处理”
        [AllowAnonymous]
        public ActionResult EJDWSendRemindMsg()
        {

            DataTable dt = new DataTable();
            dt = DbHelperSQL.Query("select * from T_Bus_WorkOrder where F_WorkState in (1,2)  and F_IsDelete=0  " +
       "and datediff(day , F_AssignTime , getdate())>'" + 3 + "' and F_EJSendMsgDay =0   ").Tables[0];

 

            if (dt != null & dt.Rows.Count > 0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    int deptid = Convert.ToInt32( item["F_MainDeptId"].ToString());
                    DataTable userdt = DbHelperSQL.Query(" select F_usercode from t_sys_useraccount where F_deptid='"+ deptid + "'").Tables[0];
                    foreach (DataRow user in userdt.Rows)
                    {
                        msg.AddInternalMessagesInfo("超期未处理提醒", "提示函 " + item["F_WorkOrderId"].ToString() + "超期未处理，请及时处理\n", user["F_usercode"].ToString(), "8000", (int)EnumSmsType.attention);
                    }
                    DbHelperSQL.ExecuteSql("update T_Bus_WorkOrder set F_EJSendMsgDay=3 where F_WorkOrderId='" + item["F_WorkOrderId"].ToString() + "'");

                }
            }

            DataTable dt2 = new DataTable();
            dt2 = DbHelperSQL.Query("select * from T_Bus_WorkOrder where F_WorkState in (1,2) and F_IsDelete=0  " +
"and datediff(day , F_AssignTime , getdate())>'" + 6 + "' and F_EJSendMsgDay =3   ").Tables[0];
            if (dt2 != null & dt2.Rows.Count > 0)
            {
                foreach (DataRow item in dt2.Rows)
                {
                    int deptid = Convert.ToInt32(item["F_MainDeptId"].ToString());
                    DataTable userdt = DbHelperSQL.Query(" select F_usercode from t_sys_useraccount where F_deptid='" + deptid + "'").Tables[0];
                    foreach (DataRow user in userdt.Rows)
                    {
                        msg.AddInternalMessagesInfo("超期未处理提醒", "提示函 " + item["F_WorkOrderId"].ToString() + "超期未处理，请及时处理\n", user["F_usercode"].ToString(), "8000", (int)EnumSmsType.attention);
                    }
                    DbHelperSQL.ExecuteSql("update T_Bus_WorkOrder set F_EJSendMsgDay=6 where F_WorkOrderId='" + item["F_WorkOrderId"].ToString() + "'");

                }
            }

            DataTable dt3 = new DataTable();
            dt3 = DbHelperSQL.Query("select * from T_Bus_WorkOrder where F_WorkState in (1,2) and F_IsDelete=0  " +
"and datediff(day , F_AssignTime , getdate())>'" + 9 + "' and F_EJSendMsgDay =6   ").Tables[0];
            if (dt3 != null & dt3.Rows.Count > 0)
            {
                foreach (DataRow item in dt3.Rows)
                {
                    int deptid = Convert.ToInt32(item["F_MainDeptId"].ToString());
                    DataTable userdt = DbHelperSQL.Query(" select F_usercode from t_sys_useraccount where F_deptid='" + deptid + "'").Tables[0];

                    foreach (DataRow user in userdt.Rows)
                    {
                        msg.AddInternalMessagesInfo("超期未处理提醒", "提示函 " + item["F_WorkOrderId"].ToString() + "超期未处理，请及时处理\n", user["F_usercode"].ToString(), "8000", (int)EnumSmsType.attention);
                    }
                    DbHelperSQL.ExecuteSql("update T_Bus_WorkOrder set F_EJSendMsgDay=9 where F_WorkOrderId='" + item["F_WorkOrderId"].ToString() + "'");

                }
            }


            return Success("发送消息完成");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stime">年月日</param>
        /// <returns></returns>
        public ActionResult DayReport(string stime)
        {
            if (string.IsNullOrEmpty(stime))
            {
                stime = DateTime.Now.ToString("yyyy-MM-dd");
            }

            DateTime date = DateTime.Parse(stime+" 16:00:00");

            DateTime lastdate = date.AddDays(-1);
            string sql= "select *,dbo.GetDeptNames(F_MainDeptId) maindeptname from T_Bus_WorkOrder where F_IsDelete=0 and  F_CreateTime>'" + lastdate+"' and F_CreateTime<='" + date + "'";
           var ordertable= DbHelperSQL.Query(sql).Tables[0];

            string blsql = "select * from T_Bus_Feedback  where F_Type=1 and F_CreateTime>'" + lastdate + "' and F_CreateTime<='" + date + "'";
            var bltable= DbHelperSQL.Query(blsql).Tables[0];

         
            var obj = new
            {
                state = "success",
                message = "成功",
                ordertable = ordertable,
                bltable = bltable
            };
            return Content(obj.ToJson());


        }

        /// <summary>
        /// 发送重办查收提醒短信《重办工单查收提醒》
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        /// <param name="tel"></param>
        /// <param name="tempid"></param>
        /// <param name="workorderid"></param>
        /// <returns></returns>
        public string sendCs(int userid,string content, string tel, string workorderid) {

            string mag = "[\"" + workorderid + "\"]";
            string v = SMSNewController.AddSmS(userid, content, tel, "1132299866192023552", mag, workorderid);
            return v;
        }

        /// <summary>
        /// 工单查收提醒
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        /// <param name="tel"></param>
        /// <param name="workorderid"></param>
        /// <returns></returns>
        public string sendjscs(int userid, string content, string tel, string workorderid)
        {

            string mag = "[\"" + workorderid + "\"]";
            string v = SMSNewController.AddSmS(userid, content, tel, "1132299838815801344", mag, workorderid);
            return v;
        }
        /// <summary>
        /// 即将超期提醒
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        /// <param name="tel"></param>
        /// <param name="workorderid"></param>
        /// <returns></returns>
        public string sendjjcq(int userid, string content, string tel, string workorderid,int hour)
        {
            string mag = "[\"" + workorderid + "\",\"" + hour + "\"]";
            
            string v = SMSNewController.AddSmS(userid, content, tel, "1132369071726223360", mag, workorderid);
            return v;
        }
        /// <summary>
        /// 工单催办提醒
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        /// <param name="tel"></param>
        /// <param name="workorderid"></param>
        /// <returns></returns>
        public string sendcbtx(int userid, string content, string tel, string workorderid)
        {
            string mag = "[\"" + workorderid + "\"]";

            string v = SMSNewController.AddSmS(userid, content, tel, "1132299872114380800", mag, workorderid);
            return v;
        }
  
        /// <summary>
        /// 工单超期提醒
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        /// <param name="tel"></param>
        /// <param name="workorderid"></param>
        /// <param name="hour"></param>
        /// <returns></returns>
        public string sendcqtx(int userid, string content, string tel, string workorderid, int hour)
        {
            string mag = "[\"" + workorderid + "\",\"" + hour + "\"]";

            string v = SMSNewController.AddSmS(userid, content, tel, "1132299858089172992", mag, workorderid);
            return v;
        }
    }
}