using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterAPI.WechatSDK;
using Senparc.Weixin.MP.TenPayLibV3;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;

namespace CallCenterApi.Interface.Controllers.workorder
{
    public class WorkOrderController : BaseController
    {
        private BLL.T_Sys_DictionaryValue dictionaryValueBLL = new BLL.T_Sys_DictionaryValue();
        #region 工单
        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetListAll()
        {
            string sql = " and isdel=0 ";
            DataTable dt = new DataTable();

            string strorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("orderid"));
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            string strtype = HttpUtility.UrlDecode(RequestString.GetQueryString("type"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strcode = HttpUtility.UrlDecode(RequestString.GetQueryString("code"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strinfotype = HttpUtility.UrlDecode(RequestString.GetQueryString("infotype"));

            string isrestore = HttpUtility.UrlDecode(RequestString.GetQueryString("isrestore"));



            string strclbm = RequestString.GetQueryString("clbmid");
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));


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

            if (isrestore.Trim() != "" && isrestore != "undefined")
            {
                sql += " and IsRestore like '%" + isrestore.Trim() + "%' ";
            }


            if (strorderid.Trim() != "" && strorderid != "undefined")
            {
                sql += " and WorkOrderID like '%" + strorderid.Trim() + "%' ";
            }
            if (strstate.Trim() != "" && strstate != "undefined")
            {
                if (strstate.Trim() == "0")
                    sql += " and State <> '2' ";
                else
                    sql += " and State = '2' ";
                //需求只展示是否完成
                //20180518 zhengbingbing
                //sql += " and State = '" + strstate.Trim() + "' ";
            }
            if (strtype.Trim() != "" && strtype != "undefined")
            {
                sql += " and Type = '" + strtype.Trim() + "' ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and Detail like '%" + strkey.Trim() + "%' ";
            }
            if (strcode.Trim() != "" && strcode != "undefined")
            {
                sql += " and CreateUser = '" + strcode.Trim() + "' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and Customer like '%" + strname.Trim() + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and CustomerTel like '%" + strtel + "%'  ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
            }
            if (strinfotype.Trim() != "" && strinfotype != "undefined")
            {
                sql += " and InfoTypeID = '" + strinfotype.Trim() + "' ";
            }

            if (strusercode.Trim() != "" && strusercode != "undefined")
            {
                sql += " and CreateUser = '" + strusercode.Trim() + "' ";
            }

            if (strclbm.Trim() != "" && strclbm != "undefined")
            {
                sql += " and UnitID = '" + strclbm.Trim() + "' ";
            }

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Wo_WorkOrder",
                "T_Wo_WorkOrder.ID",
                "*,dbo.GetUserName(CreateUser) as CreateUserName,dbo.GetDeptName(County) as DeptName,dbo.GetUserName(AuditUser) as AuditUserName,(case when AuditUser=CreateUser then '是' else '否' end) assign",
                sql,
                "ORDER BY T_Wo_WorkOrder.ID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

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

            return Content(obj.ToJson());

        }

        private string[] col()
        {
            string[] ccc = {

                   "工单编号", "反映问题","问题处理情况","问题分类","热点问题","处理部门"," 客户姓名"," 客户电话","坐席工号", "坐席姓名","创建时间","工单来源"
            };
            return ccc;
        }

        private string[] col2()
        {
            string[] ccc = {
              "工单编号", "工单状态","反映问题","问题处理情况","问题分类","热点问题","处理部门"," 客户姓名"," 客户电话","坐席工号", "坐席姓名","创建时间","工单来源"
            };
            return ccc;
        }



        /// <summary>
        /// 获取待处理工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(int  isexport=0)
        {
            string sql = " and isdel=0 ";
            DataTable dt = new DataTable();

            string strorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("orderid"));
            string strltype = HttpUtility.UrlDecode(RequestString.GetQueryString("ltype"));
            string strtype = HttpUtility.UrlDecode(RequestString.GetQueryString("type"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strisreward = HttpUtility.UrlDecode(RequestString.GetQueryString("isreward"));
            string state = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            string strinfotype = HttpUtility.UrlDecode(RequestString.GetQueryString("infotype"));
            string strpageindex = RequestString.GetQueryString("page");

            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));

            string strclbm = RequestString.GetQueryString("clbmid");

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

            #region 息县需求变动
            switch (strltype)
            {
                case "0"://待处理和处理中
                    sql += " and State!=2 and AuditUser like '%" + CurrentUser.UserData.F_UserCode + "%'";
                    //sql += " and State ='0' and CreateUser= '" + ua.F_UserCode + "' ";
                    //  sql += " and (( State ='1' and WorkOrderID in ( '" + GetDWCWorkOrderID(CurrentUser.UserData.F_UserCode) + "')) )";
                    // sql += " and (State ='0' or State ='1' or( State ='1' and WorkOrderID in ( '" + GetDWCWorkOrderID(CurrentUser.UserData.F_UserCode) + "')) )";
                    break;
                case "1"://已完成的
                    sql += " and State ='2' and LastDealUser = '" + CurrentUser.UserData.F_UserCode + "' ";
                    break;
                case "2"://我参与的
                    sql += " and (CreateUser = '" + CurrentUser.UserData.F_UserCode + "' or AuditUser like '%" + CurrentUser.UserData.F_UserCode + "%' )";

                  //  sql += " and (CreateUser= '" + CurrentUser.UserData.F_UserCode + "' or WorkOrderID in ( '" + GetCYWorkOrderID(CurrentUser.UserData.F_UserCode) + "')) ";
                    break;
            }
         
            #endregion

            #region 条件
            if (state.Trim() != "" && state != "undefined")
            {
                if (state.Trim() == "0")
                    sql += " and State <> '2' ";
                else
                    sql += " and State = '2' ";
            }
            if (strorderid.Trim() != "" && strorderid != "undefined")
            {
                sql += " and WorkOrderID like '%" + strorderid.Trim() + "%' ";
            }
            if (strtype.Trim() != "" && strtype != "undefined")
            {
                sql += " and Type = '" + strtype.Trim() + "' ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and Detail like '%" + strkey.Trim() + "%' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and Customer like '%" + strname.Trim() + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and CustomerTel like '%" + strtel + "%'  ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
            }
            if (strisreward.Trim() != "" && strisreward != "undefined")
            {
                sql += " and ISReward=" + strisreward.Trim();
            }
            if (strinfotype.Trim() != "" && strinfotype != "undefined")
            {
                sql += " and InfoTypeID = '" + strinfotype.Trim() + "' ";
            }

            if (strusercode.Trim() != "" && strusercode != "undefined")
            {
                sql += " and CreateUser = '" + strusercode.Trim() + "' ";
            }

            if (strclbm.Trim() != "" && strclbm != "undefined")
            {
                sql += " and UnitID = '" + strclbm.Trim() + "' ";
            }

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

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

            if (isexport>0)
            {

              

                NPOIHelper npoi = new NPOIHelper();
                if (strltype == "0")
                {
                    string sqldcl = "select WorkOrderID,Detail,clcontent,InfoType,InfoTypeDetail, Unit, Customer, CustomerTel, CreateUser, dbo.GetUserName(CreateUser) CreateUserName,CreateTime,Source      from T_Wo_WorkOrder where 1=1 "+sql+ " ORDER BY  ID desc";
                    DataTable dtdcl = DbHelperSQL.Query(sqldcl).Tables[0];
                    if (npoi.ExportToExcel("待处理工单列表", dtdcl, col()  ) == "")
                    {
                        return Success("导出成功");
                    }
                    else
                    {
                        return Error("导出失败");
                    }

                }
                if (strltype == "2")
                {
                    string sqlycy = "select WorkOrderID,case when State = 2 then '已完成' else '待完成'end statename,  Detail, clcontent, InfoType, InfoTypeDetail  , Unit, Customer, CustomerTel, CreateUser, dbo.GetUserName(CreateUser) CreateUserName,CreateTime,Source        from T_Wo_WorkOrder where 1=1 " + sql + " ORDER BY  ID desc";
                    DataTable dtycy = DbHelperSQL.Query(sqlycy).Tables[0];
                    if (npoi.ExportToExcel("已参与工单列表", dtycy, col2()) == "")
                    {
                        return Success("导出成功");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
               
            }


            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Wo_WorkOrder",
                "T_Wo_WorkOrder.ID",
                "*,dbo.GetUserName(CreateUser) as CreateUserName",
                sql,
                "ORDER BY T_Wo_WorkOrder.ID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

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

            return Content(obj.ToJson());

        }



        /// <summary>
        /// 获取待处理工单数 ltype=0。已参与工单ltype=2
        /// </summary>
        /// <returns></returns>
        public ActionResult workOrderCount()
        {
            string sql = " and isdel=0 ";
            DataTable dt = new DataTable();
            int pageindex = 1;          
            int pagesize = 10;
            string strltype = HttpUtility.UrlDecode(RequestString.GetQueryString("ltype"));
            string msg = "";
            switch (strltype)
            {
                case "0"://待处理 
                   
                    sql += " and State!=2 and AuditUser like '%" + CurrentUser.UserData.F_UserCode + "%'";
                  //  sql += " and (( State ='1' and WorkOrderID in ( '" + GetDWCWorkOrderID() + "')) )";
                    msg = "待处理工单数量";
                    break;
               
                case "2"://我参与的

                    //AuditUser like '%%' or CreateUser = ''

                    sql += " and (CreateUser = '" + CurrentUser.UserData.F_UserCode + "' or AuditUser like '%" + CurrentUser.UserData.F_UserCode + "%' )";

                    //sql += " and (CreateUser= '" + CurrentUser.UserData.F_UserCode + "' or WorkOrderID in ( '" + GetCYWorkOrderID(CurrentUser.UserData.F_UserCode) + "')) ";
                    msg = "我参与的工单数量";
                    break;
            }

        
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Wo_WorkOrder",
                "T_Wo_WorkOrder.ID",
                "*",
                sql,
                "ORDER BY T_Wo_WorkOrder.ID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

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

            return Success(msg, recordCount); ;

        }

        public ActionResult workOrderAllCount()
        {
            string sql = " and isdel=0 ";
            DataTable dt = new DataTable();     
            int pageindex = 1;
            int pagesize = 10;
        
           
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Wo_WorkOrder",
                "T_Wo_WorkOrder.ID",
                "*",
                sql,
                "ORDER BY T_Wo_WorkOrder.ID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

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

            return Success("综合查询的小汽泡数", recordCount);

        }




        /// <summary>
        /// 获取待完成的工单编号
        /// </summary>
        /// <returns></returns>
        public string GetDWCWorkOrderID(string user)
        {
            string str = string.Empty;

            var list = new BLL.T_Wo_WorkOrderItem().GetModelList(" IsDel=0 and Type=1 and (state<>'2' and ','+ToUser+',' like '%," + user + ",%')    ").Select(p => p.WorkOrderID).Distinct();

            foreach (var l in list)
            {
                if (string.IsNullOrEmpty(str))
                {
                    str = l;
                }
                else
                {
                    str = str + "','" + l;
                }
            }

            return str;
        }

        /// <summary>
        /// 获取我参与的工单编号
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetCYWorkOrderID(string user)
        {
            string str = string.Empty;

            var list = new BLL.T_Wo_WorkOrderItem().GetModelList(" IsDel=0 and  ','+ToUser+',' like '%," + user + ",%' ").Select(p => p.WorkOrderID).Distinct();

            foreach (var l in list)
            {
                if (string.IsNullOrEmpty(str))
                {
                    str = l;
                }
                else
                {
                    str = str + "','" + l;
                }
            }

            return str;
        }

        /// <summary>
        /// 获取工单信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkOrder()
        {
            string orderid = RequestString.GetQueryString("orderid");
            if (!string.IsNullOrEmpty(orderid))
            {
                string sql = "select *,dbo.GetUserName(CreateUser) as CreateUserName,dbo.GetUserName(AuditUser) as AuditUserName,dbo.GetDeptName (County) CountryName  from T_Wo_WorkOrder where WorkOrderID ='" + orderid + "'";
                string sqlitem = "select *,dbo.GetUserName(CreateUser) as CreateUserName from T_Wo_WorkOrderItem where IsDel=0 and WorkOrderID ='" + orderid + "'";

                var data = DbHelperSQL.Query(sql).Tables[0];
                var item = DbHelperSQL.Query(sqlitem).Tables[0];

                var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                if (configfj != null)
                {
                    data = BindFileData(data, configfj.F_ParamValue);
                }

                var obj = new
                {
                    data = data,
                    item = item,
                    processcount = new BLL.T_Wo_WorkOrderItem().GetList(" Type=1 and IsDel=0 and  WorkOrderID='" + orderid + "' ").Tables[0].Rows.Count,
                    remindcount = new BLL.T_Wo_WorkOrderItem().GetList(" Type=2 and IsDel=0 and  WorkOrderID='" + orderid + "' ").Tables[0].Rows.Count,
                    extencount = item.Rows.Count,
                    commentcount = new BLL.T_Wo_WorkOrderItem().GetList(" Type=4 and IsDel=0 and  WorkOrderID='" + orderid + "' ").Tables[0].Rows.Count
                };
                return Success("获取成功", obj);
            }
            else
            {
                return Error("参数传输失败");
            }

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

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

            return dt;
        }

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

        #region 添加工单调整前
        ///// <summary>
        ///// 添加/修改工单信息
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult AddWorkOrder()
        //{
        //    ActionResult return NoToken("未知错误，请重新登录");
        //    if (Request.IsAuthenticated)
        //    {

        //        int userId = CurrentUser.UserData.F_UserId;
        //        if (userId != 0)
        //        {
        //            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
        //            if (ua != null)
        //            {
        //                int type = RequestString.GetInt("type", 0);
        //                //int tslx = RequestString.GetInt("tslx", 0);
        //                string callid = RequestString.GetFormString("callid");
        //                int khid = RequestString.GetInt("khid", 0);
        //                string tskh = RequestString.GetFormString("tskh");
        //                string tsdh = RequestString.GetFormString("tsdh");
        //                #region 判断输入数据类型
        //                if (!Validate.IsNumber(tsdh))
        //                {
        //                    return Error("电话必须为数字");
        //                    return res;
        //                }
        //                #endregion
        //                string cont = RequestString.GetFormString("cont");
        //                string clcont = RequestString.GetFormString("clcont");
        //                string file = RequestString.GetFormString("file");
        //                string source = RequestString.GetFormString("source");
        //                #region 新增字段
        //                int infotypeid = RequestString.GetInt("infotypeid", 0);//信息分类
        //                int unitid = RequestString.GetInt("unitid", 0);//交办单位
        //                int isaudit = RequestString.GetInt("isaudit", 0);//0未审核，1无效，2有效
        //                #endregion

        //                Model.T_Wo_WorkOrder model = new Model.T_Wo_WorkOrder();
        //                model.WorkOrderID = DateTime.Now.ToString("yyyyMMddHHmmssmsfff");//工单编号
        //                model.CallID = callid;
        //                model.Customer = tskh;
        //                model.CustomerID = khid;
        //                model.CustomerTel = tsdh;
        //                model.Detail = cont;
        //                model.Clcontent = clcont;
        //                model.Files = file;
        //                model.Type = type;
        //                //model.TypeClass = tslx;
        //                if (source.Trim() == "1")
        //                    model.Source = "手工制单";
        //                else if (source.Trim() == "2")
        //                    model.Source = "电话";

        //                if (type == 1)
        //                {
        //                    model.State = 2;
        //                }
        //                else
        //                    model.State = 0;
        //                model.IsDel = 0;
        //                model.IsReturn = 0;
        //                model.IsReturnBak = 0;
        //                model.IsTimeOut = 0;
        //                model.IsUserSend = 0;
        //                model.IsAdminSend = 0;
        //                model.IsAudit = isaudit;//0未审核，1无效，2有效

        //                #region 新增字段
        //                model.InfoTypeID = infotypeid;
        //                if (infotypeid != 0)
        //                {
        //                    Model.T_Sys_DictionaryValue dicVModel = dictionaryValueBLL.GetModel(infotypeid);
        //                    if (dicVModel != null)
        //                    {
        //                        model.InfoType = dicVModel.F_Name;
        //                    }
        //                }
        //                model.ISReward = 0;
        //                //model.RewardAmount = reamount;
        //                //model.RewardTime = retime;
        //                model.UnitID = unitid;
        //                if (unitid != 0)
        //                {
        //                    Model.T_Sys_DictionaryValue dicVModel = dictionaryValueBLL.GetModel(unitid);
        //                    if (dicVModel != null)
        //                    {
        //                        model.Unit = dicVModel.F_Name;
        //                    }
        //                }
        //                #endregion

        //                model.CreateUser = ua.F_UserCode;
        //                model.CreateTime = DateTime.Now;

        //                #region 工单超时
        //                Model.T_Wo_WorkOrderTimeOut to = new BLL.T_Wo_WorkOrderTimeOut().GetModel(type);
        //                if (to != null)
        //                {
        //                    model.LimitTime = to.MainTime;
        //                }
        //                #endregion

        //                #region 工单明细
        //                int clbm = RequestString.GetInt("clbm", 0);
        //                int clid = RequestString.GetInt("clid", 0);

        //                if (clbm != 0 || clid != 0)
        //                {
        //                    Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
        //                    item.WorkOrderID = model.WorkOrderID;
        //                    item.ToDept = clbm;


        //                    if (clid != 0)
        //                    {
        //                        Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModel(clid);
        //                        if (clus != null)
        //                        {
        //                            item.ToUser = clus.F_UserCode;
        //                        }
        //                    }
        //                    else
        //                    {
        //                        string users = string.Empty;
        //                        var list = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId='" + clbm + "'");
        //                        foreach (var l in list)
        //                        {
        //                            if (string.IsNullOrEmpty(users))
        //                            {
        //                                users = l.F_UserCode;
        //                            }
        //                            else
        //                            {
        //                                users = users + "," + l.F_UserCode;
        //                            }
        //                        }
        //                        item.ToUser = users;
        //                    }

        //                    if (to != null)
        //                    {
        //                        item.LimitTime = to.ItemTime;
        //                    }

        //                    if (item.ToUser != "")
        //                    {
        //                        item.SureUser = ua.F_UserCode;
        //                        item.State = 1;
        //                        item.SureTime = DateTime.Now;
        //                        item.IsStart = 1;
        //                    }
        //                    else
        //                    {
        //                        item.State = 0;
        //                        item.IsStart = 0;
        //                    }
        //                    item.Detail = clcont;
        //                    item.IsLast = 0;
        //                    item.IsTimeOut = 0;
        //                    item.CreateUser = ua.F_UserCode;
        //                    item.CreateTime = DateTime.Now;

        //                    if (new BLL.T_Wo_WorkOrderItem().Add(item) > 0)
        //                    {
        //                        model.State = 1;//已指派
        //                    }
        //                }
        //                #endregion

        //                #region 插入操作记录
        //                Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
        //                oper.F_WorkOrderId = model.WorkOrderID;
        //                oper.F_State = model.State;
        //                oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
        //                oper.F_File = model.Files;

        //                string userinfo = ua.depname + "-" + ua.F_UserName + "(" + ua.F_UserCode + ")";
        //                if (model.State == 0)
        //                {
        //                    oper.F_Message = userinfo + " 登记了工单,工单编号：" + model.WorkOrderID;
        //                }
        //                if (model.State == 1)
        //                {
        //                    oper.F_Message = userinfo + " 登记并提交了工单,工单编号：" + model.WorkOrderID;
        //                }
        //                if (model.State == 2)
        //                {
        //                    oper.F_Message = userinfo + " 登记并完结了工单,工单编号：" + model.WorkOrderID;
        //                }

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

        //                new BLL.T_Wo_Operation().Add(oper);
        //                #endregion

        //                if (new BLL.T_Wo_WorkOrder().Add(model) > 0)
        //                {
        //                    return Success("新增成功！");
        //                }
        //                else
        //                {
        //                    return Error("新增失败！");
        //                }
        //            }
        //        }

        //    }
        //    return res;
        //}

        ////微信添加工单
        //public string AddWorkOrders(int type, string tskh, string tsdh, string cont, string file)
        //{
        //    string workorderid = string.Empty;
        //    Model.T_Wo_WorkOrder model = new Model.T_Wo_WorkOrder();
        //    model.WorkOrderID = DateTime.Now.ToString("yyyyMMddHHmmssmsfff");//工单编号
        //    model.Customer = tskh;
        //    model.CustomerTel = tsdh;
        //    model.Detail = cont;
        //    model.Files = file;
        //    model.Type = type;

        //    model.Source = "微信";

        //    model.State = 0;
        //    model.CallID = "";

        //    model.IsDel = 0;
        //    model.IsReturn = 0;
        //    model.IsReturnBak = 0;
        //    model.IsTimeOut = 0;
        //    model.IsUserSend = 0;
        //    model.IsAdminSend = 0;
        //    model.IsAudit = 0;//是否审核有效：0未审核，1无效，2有效
        //                      //model.CreateUser = ua.F_UserCode;
        //    model.CreateTime = DateTime.Now;

        //    #region 工单超时
        //    Model.T_Wo_WorkOrderTimeOut to = new BLL.T_Wo_WorkOrderTimeOut().GetModel(type);
        //    if (to != null)
        //    {
        //        model.LimitTime = to.MainTime;
        //    }
        //    #endregion

        //    #region 工单明细
        //    Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
        //    item.WorkOrderID = model.WorkOrderID;

        //    if (to != null)
        //    {
        //        item.LimitTime = to.ItemTime;
        //    }

        //    item.IsLast = 0;
        //    item.State = 0;
        //    item.IsStart = 0;
        //    item.IsTimeOut = 0;
        //    item.CreateTime = DateTime.Now;

        //    new BLL.T_Wo_WorkOrderItem().Add(item);
        //    #endregion

        //    #region 插入操作记录
        //    Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
        //    oper.F_WorkOrderId = model.WorkOrderID;
        //    oper.F_State = model.State;
        //    oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
        //    oper.F_File = model.Files;

        //    string userinfo = "由 " + model.Source;
        //    if (model.State == 0)
        //    {
        //        oper.F_Message = userinfo + " 登记了工单,工单编号：" + model.WorkOrderID;
        //    }

        //    oper.F_CreateTime = DateTime.Now;
        //    oper.F_IsDelete = 0;

        //    new BLL.T_Wo_Operation().Add(oper);
        //    #endregion
        //    workorderid = new BLL.T_Wo_WorkOrder().Add(model).ToString();

        //    return workorderid;
        //}
        #endregion

        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelWorkOrder( int id=0)
        {
            if (id  > 0)
            {
                
                string sql = "update T_Wo_WorkOrder set IsDel=1,DelUser='" + CurrentUser.UserData.F_UserCode + "',DelTime=getdate() where ID ='"+id+"'";
                 
                    if (DbHelperSQL.ExecuteSql(sql) > 0)
                    {
                        BLL.T_Wo_WorkOrder bll = new BLL.T_Wo_WorkOrder();
                        Model.T_Wo_WorkOrder ordermodel= bll.GetModel((long)id);
                        Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
                        oper.F_WorkOrderId = ordermodel.WorkOrderID;
                        oper.F_State = ordermodel.State;
                         oper.F_CallRecordId = ordermodel.CallID != "" ? int.Parse(ordermodel.CallID) : 0;
                         oper.F_File = ordermodel.Files;

                        string userinfo = CurrentUser.UserData.depname + "-" + CurrentUser.UserData.F_UserName + "(" + CurrentUser.UserData.F_UserCode + ")";                        
                        oper.F_Message = userinfo + " 删除了工单";                      

                        oper.F_CreateUser = CurrentUser.UserData.F_UserCode;
                        oper.F_CreateTime = DateTime.Now;
                        oper.F_IsDelete = 0;

                        new BLL.T_Wo_Operation().Add(oper);
                        return Success("删除成功");
                    
                }
                else
                {
                    return Error("请选择记录");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }                              

        #region 添加处理工单
        // 添加工单 来电弹屏
        /// <summary>
        /// 添加工单信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrder(
            string callid, string source, string file, string custel
            , string customer, string country, string address, string inqtime, string inquser
           , string detail, string cont, string answer, string remark, string wjid,
            string infotype, string unit, string clbm, string clr, int khid = 0
            , int infotypeid = 0, int unitid = 0, int clid = 0,int state=1)
        {
            Model.T_Wo_WorkOrder model = new Model.T_Wo_WorkOrder();
            model.WorkOrderID = DateTime.Now.ToString("yyyyMMddHHmmss");//工单编号
            model.CallID = callid;
            model.CustomerID = khid;
            #region 息县工单
            if (!string.IsNullOrWhiteSpace(customer))
                model.Customer = customer;
            if (!string.IsNullOrWhiteSpace(custel))
                model.CustomerTel = custel;
            if (!string.IsNullOrWhiteSpace(inqtime))
                model.Inqtime = DateTime.Parse(inqtime);
            if (!string.IsNullOrWhiteSpace(inquser))
                model.Inquser = inquser;
            if (!string.IsNullOrWhiteSpace(country))
                model.County = country;
            if (!string.IsNullOrWhiteSpace(address))
                model.Address = address;
            if (!string.IsNullOrWhiteSpace(detail))
                model.Detail = detail;
            if (!string.IsNullOrWhiteSpace(answer))
                model.Answer = answer;
            if (!string.IsNullOrWhiteSpace(cont))
                model.Clcontent = cont;
            if (!string.IsNullOrWhiteSpace(remark))
                model.Remark = remark;
            if (!string.IsNullOrWhiteSpace(wjid))
                model.WjID = int.Parse(wjid);
            #endregion
            #region 信息分类和交办单位 
            model.InfoType = infotype;
            model.Unit = unit;
          
            #endregion

            model.Files = file;
            if (source.Trim() == "1")
                model.Source = "手工制单";
            else if (source.Trim() == "2")
                model.Source = "电话";

            #region 无需参数字段
            model.Type = 3;//默认为投诉工单
            model.State = 0;
            model.IsDel = 0;
            model.IsReturn = 0;
            model.IsReturnBak = 0;
            model.IsTimeOut = 0;
            model.IsUserSend = 0;
            model.IsAdminSend = 0;

            model.CreateUser = CurrentUser.UserData.F_UserCode;
            model.CreateTime = DateTime.Now;
            #endregion

            if (state == 2)
            {
                model.State = 2;
            }
            else
            {

            //20180514 郑兵兵 无需走流程，所有注释
            #region 工单明细 

            //if (clbm != 0 || clid != 0)
            //{
            int depid = 0; //部门id
            var model_Dep = new BLL.T_Sys_Department().GetModel(clbm);
            depid = model_Dep != null ? model_Dep.F_DeptId : 0;

            Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
            item.WorkOrderID = model.WorkOrderID;
            item.ToDept = depid; //部门clbm
            item.Type = 1;

            if (!string.IsNullOrEmpty(clr))  //if (clid != 0)
            {
                //Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModel(clid);
                Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModelByName(clr);
                if (clus != null)
                {
                    item.ToUser = clus.F_UserCode;
                }
            }
            else
            {
                string users = string.Empty;
                var list = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId='" + clbm + "'");
                foreach (var l in list)
                {
                    if (string.IsNullOrEmpty(users))
                    {
                        users = l.F_UserCode;
                    }
                    else
                    {
                        users = users + "," + l.F_UserCode;
                    }
                }
                item.ToUser = users;
            }

            if (item.ToUser != "")
            {
                item.SureUser = CurrentUser.UserData.F_UserCode;
                item.State = 1;
                item.SureTime = DateTime.Now;
                item.IsStart = 1;
            }
            else
            {
                item.State = 0;
                item.IsStart = 0;
            }
            item.Detail = model.Detail;
            item.IsLast = 0;
            item.IsTimeOut = 0;
            item.IsDel = 0;
            item.CreateUser = CurrentUser.UserData.F_UserCode;
            item.CreateTime = DateTime.Now;

            long itemid = new BLL.T_Wo_WorkOrderItem().Add(item);
            if (itemid > 0)
            {
                model.State = 1;//已指派
                model.AppointTime = DateTime.Now;

            }
                #endregion


            }
            #region 插入操作记录
            Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
            oper.F_WorkOrderId = model.WorkOrderID;
            oper.F_State = model.State;
            oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
            oper.F_File = model.Files;

            string userinfo = CurrentUser.UserData.depname + "-" + CurrentUser.UserData.F_UserName + "(" + CurrentUser.UserData.F_UserCode + ")";
            if (model.State == 0)
            {
                oper.F_Message = userinfo + " 登记了工单,工单编号：" + model.WorkOrderID;
            }
            if (model.State == 1)
            {
                oper.F_Message = userinfo + " 登记并提交了工单,工单编号：" + model.WorkOrderID;
            }

            if (model.State == 2)
            {
                oper.F_Message = userinfo + " 登记并完结了工单,工单编号：" + model.WorkOrderID;
            }

            oper.F_CreateUser = CurrentUser.UserData.F_UserCode;
            oper.F_CreateTime = DateTime.Now;
            oper.F_IsDelete = 0;

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

            if (new BLL.T_Wo_WorkOrder().Add(model) > 0)
            {
                return Success("新增成功！");
            }
            else
            {
                return Error("新增失败！");
            }

        }

        //客户需求，所有项目为非必填项
        //信息分类、交办单位、处理部门、处理人为文本输入
        //调查人员自动填充当前登录人工号
        //可以修改工单

        /// <summary>
        /// 处理工单信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DealWorkOrder(string orderid, int isend
           , string customer, string inqtime, string inquser, string country, string address
           , string detail, string cont, string answer, string remark,
            string infotype, string infotypedetail, string clgh,int isrestore,int infotypeid=0,int infotypedetailid=0
            ,int buttontype=0, int unit = 0, int clbm = 0)
            //
            //客户名，调查时间，调查人，营业部，地址
        //问题详情，处理内容，回复内容，备注，
        //问题分类string，处理部门string，处理部门string，处理人工号
        {
            Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
            if (model != null)
            {

                if (buttontype==1)
                {
                    model.Clcontent = cont;
                    new  BLL.T_Wo_WorkOrder().Update(model);
                    return Success("保存成功");

                }






                var model_Dep = new BLL.T_Sys_Department().GetModel(unit);

                #region 信息分类和交办单位
                model.InfoType = infotype;
                model.InfoTypeID = infotypeid;

                model.InfoTypeDetail = infotypedetail;
                model.InfoTypeDetailID = infotypedetailid;


                model.Unit = model_Dep.F_DeptName??"";
                model.UnitID = unit;

                model.IsRestore = isrestore;


                #endregion
                string inqtimes = "";
                #region 息县工单
                if (!string.IsNullOrWhiteSpace(customer))
                    model.Customer = customer;
                if (!string.IsNullOrWhiteSpace(inqtime))
                {
                    model.Inqtime = DateTime.Parse(inqtime);
                    inqtimes = model.Inqtime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }
                if (!string.IsNullOrWhiteSpace(inquser))
                    model.Inquser = inquser;
                if (!string.IsNullOrWhiteSpace(country))
                    model.County = country;
                if (!string.IsNullOrWhiteSpace(address))
                    model.Address = address;
                if (!string.IsNullOrWhiteSpace(detail))
                    model.Detail = detail;
                if (!string.IsNullOrWhiteSpace(answer))
                    model.Answer = answer;
                if (!string.IsNullOrWhiteSpace(cont))
                    model.Clcontent = cont;
                if (!string.IsNullOrWhiteSpace(remark))
                    model.Remark = remark;

                #endregion
                if (isend == 1)
                    model.State = 2;
                else
                    model.State = 1;

               
                #region 无需走流程
                var item = new Model.T_Wo_WorkOrderItem();
                #region 获取接收人
                int depid = 0; //部门id

                depid = unit;

                if (!string.IsNullOrEmpty(clgh))   
                {

                    Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModelByName(clgh);
                    if (clus != null)
                    {
                        item.ToUser = clus.F_UserCode;
                    }
                }
                else
                {
                    string users = string.Empty;
                    var list = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId='" + clbm + "'");
                    foreach (var l in list)
                    {
                        if (string.IsNullOrEmpty(users))
                        {
                            users = l.F_UserCode;
                        }
                        else
                        {
                            users = users + "," + l.F_UserCode;
                        }
                    }
                    item.ToUser = users;
                }
                model.AuditUser = item.ToUser;
                var rerere = new BLL.T_Wo_WorkOrder().Update(model);

                #endregion
                item.WorkOrderID = orderid;
                item.Type = 1;      //处理
               item.ToDept = depid; //部门clbm
                                     //item.ToUser = clus != null ? clus.F_UserCode : "";  //接收人
                item.Detail = cont;
                item.IsDel = 0;
                //转派
                if (isend == 0) //页面选了未完结
                {
                    item.State = 0;
                    item.IsLast = 0;
                    item.DealUser = CurrentUser.UserData.F_UserCode;
                    item.DealTime = DateTime.Now;
                }
                else//完结
                {
                    item.State = 2;
                    item.IsLast = 1;
                    item.DealUser = CurrentUser.UserData.F_UserCode;
                    item.DealTime = DateTime.Now;
                }
                //item.Detail = remark;
                //item.IsStart = 0;
                item.IsTimeOut = 0;
                item.CreateUser = CurrentUser.UserData.F_UserCode;
                item.CreateTime = DateTime.Now;
                long itemid = new BLL.T_Wo_WorkOrderItem().Add(item);

                
             
                #endregion

                if (rerere)
                {
                  
                    #region 插入操作记录
                    Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
                    oper.F_WorkOrderId = model.WorkOrderID;
                    oper.F_State = model.State;
                    oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
                    oper.F_File = model.Files;

                    string userinfo = CurrentUser.UserData.depname + "-" + CurrentUser.UserData.F_UserName + "(" + CurrentUser.UserData.F_UserCode + ")";
                    if (model.State < 2)
                    {
                        oper.F_Message = userinfo + " 指派了工单，单号：" + model.WorkOrderID;
                    }
                    if (model.State == 2)
                    {
                        oper.F_Message = userinfo + " 完结了工单，单号：" + model.WorkOrderID;
                    }

                    oper.F_CreateUser = CurrentUser.UserData.F_UserCode;
                    oper.F_CreateTime = DateTime.Now;
                    oper.F_IsDelete = 0;

                    new BLL.T_Wo_Operation().Add(oper);
                    #endregion
                }

                return Success("处理成功");
            }
            else
            {
                return Error("处理失败！");
            }
        }

        #region 微信工单
        //微信添加工单
        public string AddWorkOrders(string customer, string custel, string country, string address, string detail, string file, string infotype, string infotypeid, string agentcode, string agentname, string unit)
        {
            string workorderid = string.Empty;
            Model.T_Wo_WorkOrder model = new Model.T_Wo_WorkOrder();
            model.WorkOrderID = DateTime.Now.ToString("yyyyMMddHHmmss");//工单编号
            model.Customer = customer;
            model.CustomerTel = custel;
            model.County = country;
            model.Address = address;
            model.Detail = detail;
            model.Files = file;
            model.InfoType = infotype;
            if (!string.IsNullOrWhiteSpace(infotypeid))
            {
                model.InfoTypeID = Convert.ToInt32(infotypeid);
            }
            #region 无需参数字段
            model.Type = 3;//默认为投诉工单
            model.Source = "微信";
            model.State = 0;
            model.CallID = "";
            model.WjID = 0;
            model.IsDel = 0;
            model.IsReturn = 0;
            model.IsReturnBak = 0;
            model.IsTimeOut = 0;
            model.IsUserSend = 0;
            model.IsAdminSend = 0;
            model.IsAudit = 0;//是否审核有效：0未审核，1无效，2有效
                              //model.CreateUser = ua.F_UserCode;
            model.CreateUser = agentcode;
            model.Unit = unit;
            model.CreateTime = DateTime.Now;
            #endregion

            #region 工单明细
            Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
            item.WorkOrderID = model.WorkOrderID;

            item.Detail = model.Detail;
            item.IsLast = 0;
            item.State = 0;
            item.IsStart = 0;
            item.IsTimeOut = 0;
            item.CreateTime = DateTime.Now;

            new BLL.T_Wo_WorkOrderItem().Add(item);
            #endregion

            #region 插入操作记录
            Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
            oper.F_WorkOrderId = model.WorkOrderID;
            oper.F_State = model.State;
            oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
            oper.F_File = model.Files;

            string userinfo = "由 " + model.Source;
            if (model.State == 0)
            {
                oper.F_Message = userinfo + " 登记了工单,工单编号：" + model.WorkOrderID;
            }

            oper.F_CreateTime = DateTime.Now;
            oper.F_IsDelete = 0;

            new BLL.T_Wo_Operation().Add(oper);
            #endregion
            workorderid = new BLL.T_Wo_WorkOrder().Add(model).ToString();

            return workorderid;
        }

        //微信处理工单
        public bool DealWorkOrders(string orderid, int isend, string customer, string inqtime,
            string inquser, string country, string address, string detail, string cont,
            string answer, string remark, string infotype, string unit, string openid)
        //int infotypeid, int unitid, string openid)
        {
            bool res = false;
            Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" id=" + orderid + "").FirstOrDefault();
            if (model != null)
            {
                if (openid != "")
                {
                    Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModelList(" F_WxOpenId='" + openid + "'").FirstOrDefault();
                    if (ua != null)
                    {
                        string inqtimes = "";
                        #region 信息分类/交办单位
                        model.InfoType = infotype;
                        model.Unit = unit;
                        //20180514 zhengbingbing 不传ID调整为只有文字
                        //model.InfoTypeID = infotypeid;//信息分类
                        //if (infotypeid != 0)
                        //{
                        //    Model.T_Sys_DictionaryValue dicVModel = dictionaryValueBLL.GetModel(infotypeid);
                        //    if (dicVModel != null)
                        //    {
                        //        model.InfoType = dicVModel.F_Name;
                        //    }
                        //}
                        //model.ISReward = 0;
                        //model.UnitID = unitid;//交办单位
                        //if (unitid != 0)
                        //{
                        //    Model.T_Sys_DictionaryValue dicVModel = dictionaryValueBLL.GetModel(unitid);
                        //    if (dicVModel != null)
                        //    {
                        //        model.Unit = dicVModel.F_Name;
                        //    }
                        //}
                        #endregion
                        #region 息县工单
                        if (!string.IsNullOrWhiteSpace(customer))
                            model.Customer = customer;
                        if (!string.IsNullOrWhiteSpace(inqtime))
                        {
                            model.Inqtime = DateTime.Parse(inqtime);
                            inqtimes = model.Inqtime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        if (!string.IsNullOrWhiteSpace(inquser))
                            model.Inquser = inquser;
                        if (!string.IsNullOrWhiteSpace(country))
                            model.County = country;
                        if (!string.IsNullOrWhiteSpace(address))
                            model.Address = address;
                        if (!string.IsNullOrWhiteSpace(detail))
                            model.Detail = detail;
                        if (!string.IsNullOrWhiteSpace(answer))
                            model.Answer = answer;
                        if (!string.IsNullOrWhiteSpace(cont))
                            model.Clcontent = cont;
                        if (!string.IsNullOrWhiteSpace(remark))
                            model.Remark = remark;
                        #endregion

                        if (isend == 1)
                            model.State = 2;
                        else
                            model.State = 1;
                        var rerere = new BLL.T_Wo_WorkOrder().Update(model);
                        #region 无需走流程
                        //int n = new BLL.T_Wo_WorkOrder().DealWorkOrder1(model.WorkOrderID, 1
                        //        , model.Customer, model.CustomerTel, inqtimes, model.Inquser
                        //        , model.County, model.Address, model.Detail, model.Clcontent, model.Answer, model.Remark
                        //        , ua.F_DeptId, ua.F_UserCode, ua.F_UserCode, model.InfoType, model.InfoTypeID.Value, model.UnitID.Value, model.Unit);

                        //if (n > 0)
                        #endregion
                        if (rerere)
                        {
                            #region 消息通知
                            //Model.T_Wo_WorkOrderItem item = new BLL.T_Wo_WorkOrderItem().GetModelList(" WorkOrderID='" + orderid + "' and Type=1 ").OrderByDescending(p => p.CreateTime).FirstOrDefault();

                            //string strmsg = string.Empty;
                            //strmsg = ua.F_UserName + "通过微信完结了工单，单号：" + model.WorkOrderID;

                            #endregion

                            #region 插入操作记录
                            Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
                            oper.F_WorkOrderId = model.WorkOrderID;
                            oper.F_State = model.State;
                            oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
                            oper.F_File = model.Files;

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

                            oper.F_Message = userinfo + "通过微信完结了工单，单号：" + model.WorkOrderID;

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

                            new BLL.T_Wo_Operation().Add(oper);
                            #endregion
                            res = true;
                        }
                    }
                }
            }
            return res;
        }
        #endregion
        #endregion

        #region 处理工单 调整前

        ///// <summary>
        ///// 处理工单信息
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult DealWorkOrder()
        //{
        //    ActionResult return NoToken("未知错误，请重新登录");
        //    if (Request.IsAuthenticated)
        //    {

        //        int userId = CurrentUser.UserData.F_UserId;
        //        if (userId != 0)
        //        {
        //            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
        //            if (ua != null)
        //            {
        //                return Error("处理失败！");
        //                string orderid = RequestString.GetFormString("orderid");
        //                int isend = RequestString.GetInt("isend", 0);
        //                string cont = RequestString.GetFormString("cont");
        //                int clbm = RequestString.GetInt("clbm", 0);
        //                int clid = RequestString.GetInt("clid", 0);
        //                int isaudit = RequestString.GetInt("isaudit", 0);//0未审核，1无效，2有效
        //                #region 新增字段
        //                int infotypeid = RequestString.GetInt("infotypeid", 0);//信息分类
        //                //int isreward = RequestString.GetInt("isreward", 0);//上报奖励
        //                //string reamount = RequestString.GetFormString("reamount");//奖励金额
        //                //string retime = RequestString.GetFormString("retime");//奖励时间
        //                int unitid = RequestString.GetInt("unitid", 0);//交办单位
        //                #endregion


        //                Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
        //                if (model != null)
        //                {

        //                    #region 获取处理人工号
        //                    string struser = string.Empty;
        //                    if (clbm != 0)
        //                    {
        //                        if (clid != 0)
        //                        {
        //                            Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModel(clid);
        //                            if (clus != null)
        //                            {
        //                                struser = clus.F_UserCode;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            string users = string.Empty;
        //                            var list = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId='" + clbm + "'");
        //                            foreach (var l in list)
        //                            {
        //                                if (string.IsNullOrEmpty(users))
        //                                {
        //                                    users = l.F_UserCode;
        //                                }
        //                                else
        //                                {
        //                                    users = users + "," + l.F_UserCode;
        //                                }
        //                            }
        //                            struser = users;
        //                        }
        //                    }
        //                    #endregion

        //                    #region 新增字段
        //                    model.IsAudit = isaudit;//0未审核，1无效，2有效
        //                    model.InfoTypeID = infotypeid;
        //                    if (infotypeid != 0)
        //                    {
        //                        Model.T_Sys_DictionaryValue dicVModel = dictionaryValueBLL.GetModel(infotypeid);
        //                        if (dicVModel != null)
        //                        {
        //                            model.InfoType = dicVModel.F_Name;
        //                        }
        //                    }
        //                    //model.ISReward = isreward;
        //                    //model.RewardAmount = reamount;
        //                    //model.RewardTime = retime;
        //                    model.UnitID = unitid;
        //                    if (unitid != 0)
        //                    {
        //                        Model.T_Sys_DictionaryValue dicVModel = dictionaryValueBLL.GetModel(unitid);
        //                        if (dicVModel != null)
        //                        {
        //                            model.Unit = dicVModel.F_Name;
        //                        }
        //                    }
        //                    #endregion

        //                    int n = new BLL.T_Wo_WorkOrder().DealWorkOrder(orderid, isend, cont, clbm, struser, ua.F_UserCode
        //                        , model.IsAudit.Value, model.InfoType, model.InfoTypeID.Value
        //                        , model.UnitID.Value, model.Unit);
        //                    if (n > 0)
        //                    {
        //                        #region 消息通知
        //                        Model.T_Wo_WorkOrderItem item = new BLL.T_Wo_WorkOrderItem().GetModelList(" WorkOrderID='" + orderid + "' and Type=1 ").OrderByDescending(p => p.CreateTime).FirstOrDefault();

        //                        string strmsg = string.Empty;
        //                        if (item.IsLast == 0)
        //                        {
        //                            strmsg = ua.F_UserName + "给你指派了工单，单号：" + model.WorkOrderID;
        //                        }
        //                        else if (item.IsLast == 1)
        //                        {
        //                            strmsg = ua.F_UserName + "完结了工单，单号：" + model.WorkOrderID;
        //                        }
        //                        #region 消息表
        //                        //foreach (string ur in item.ToUser.Split(','))
        //                        //{
        //                        //    Model.T_Msg_List msg = new Model.T_Msg_List();
        //                        //    msg.Type = 1;
        //                        //    msg.ToUser = ur;
        //                        //    msg.ToID = Int32.Parse(item.ID.ToString());
        //                        //    msg.Detail = strmsg;
        //                        //    msg.State = 0;
        //                        //    msg.IsDel = 0;
        //                        //    msg.CreateUser = ua.F_UserCode;
        //                        //    msg.CreateDate = DateTime.Now;

        //                        //    new BLL.T_Msg_List().Add(msg);
        //                        //}
        //                        #endregion
        //                        #endregion
        //                        #region 插入操作记录
        //                        Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
        //                        oper.F_WorkOrderId = model.WorkOrderID;
        //                        oper.F_State = model.State;
        //                        oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
        //                        oper.F_File = model.Files;

        //                        string userinfo = ua.depname + "-" + ua.F_UserName + "(" + ua.F_UserCode + ")";
        //                        if (model.State == 1)
        //                        {
        //                            oper.F_Message = userinfo + " 指派了工单，单号：" + model.WorkOrderID;
        //                        }
        //                        if (model.State == 2)
        //                        {
        //                            oper.F_Message = userinfo + " 完结了工单，单号：" + model.WorkOrderID;
        //                        }

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

        //                        new BLL.T_Wo_Operation().Add(oper);
        //                        #endregion


        //                        return Success("处理成功");
        //                    }

        //                }
        //            }
        //        }

        //    }
        //    return res;
        //}

        ////微信处理工单
        //public bool DealWorkOrders(string orderid, string cont, string openid, int isaudit, int infotypeid, int unitid)
        //{
        //    bool return false;
        //    Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" id=" + orderid + "").FirstOrDefault();
        //    if (model != null)
        //    {
        //        if (openid != "")
        //        {
        //            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModelList(" F_WxOpenId='" + openid + "'").FirstOrDefault();
        //            if (ua != null)
        //            {

        //                #region 新增字段
        //                model.IsAudit = isaudit;//0未审核，1无效，2有效
        //                model.InfoTypeID = infotypeid;//信息分类
        //                if (infotypeid != 0)
        //                {
        //                    Model.T_Sys_DictionaryValue dicVModel = dictionaryValueBLL.GetModel(infotypeid);
        //                    if (dicVModel != null)
        //                    {
        //                        model.InfoType = dicVModel.F_Name;
        //                    }
        //                }
        //                model.ISReward = 0;
        //                model.UnitID = unitid;//交办单位
        //                if (unitid != 0)
        //                {
        //                    Model.T_Sys_DictionaryValue dicVModel = dictionaryValueBLL.GetModel(unitid);
        //                    if (dicVModel != null)
        //                    {
        //                        model.Unit = dicVModel.F_Name;
        //                    }
        //                }
        //                #endregion

        //                int n = new BLL.T_Wo_WorkOrder().DealWorkOrder(model.WorkOrderID, 1, cont, ua.F_DeptId, ua.F_UserCode, ua.F_UserCode
        //                    , model.IsAudit.Value, model.InfoType, model.InfoTypeID.Value
        //                    , model.UnitID.Value, model.Unit);
        //                if (n > 0)
        //                {
        //                    #region 消息通知
        //                    Model.T_Wo_WorkOrderItem item = new BLL.T_Wo_WorkOrderItem().GetModelList(" WorkOrderID='" + orderid + "' and Type=1 ").OrderByDescending(p => p.CreateTime).FirstOrDefault();

        //                    string strmsg = string.Empty;
        //                    strmsg = ua.F_UserName + "通过微信完结了工单，单号：" + model.WorkOrderID;
        //                    #region 消息表
        //                    //foreach (string ur in item.ToUser.Split(','))
        //                    //{
        //                    //    Model.T_Msg_List msg = new Model.T_Msg_List();
        //                    //    msg.Type = 1;
        //                    //    msg.ToUser = ur;
        //                    //    msg.ToID = Int32.Parse(item.ID.ToString());
        //                    //    msg.Detail = strmsg;
        //                    //    msg.State = 0;
        //                    //    msg.IsDel = 0;
        //                    //    msg.CreateUser = ua.F_UserCode;
        //                    //    msg.CreateDate = DateTime.Now;

        //                    //    new BLL.T_Msg_List().Add(msg);
        //                    //}
        //                    #endregion
        //                    #endregion

        //                    #region 插入操作记录
        //                    Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
        //                    oper.F_WorkOrderId = model.WorkOrderID;
        //                    oper.F_State = model.State;
        //                    oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
        //                    oper.F_File = model.Files;

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

        //                    oper.F_Message = userinfo + "通过微信完结了工单，单号：" + model.WorkOrderID;

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

        //                    new BLL.T_Wo_Operation().Add(oper);
        //                    #endregion
        //                    return true;
        //                }
        //            }
        //        }
        //    }
        //    return res;
        //}

        #endregion

        /// <summary>
        /// 评论工单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrderComment()
        {

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

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

                #region 插入操作记录
                Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
                oper.F_WorkOrderId = model.WorkOrderID;
                oper.F_State = model.State;
                oper.F_CallRecordId = model.CallID != "" ? int.Parse(model.CallID) : 0;
                oper.F_File = model.Files;

                string userinfo = CurrentUser.UserData.depname + "-" + CurrentUser.UserData.F_UserName + "(" + CurrentUser.UserData.F_UserCode + ")";
                oper.F_Message = userinfo + " 评论工单，工单编号：" + model.WorkOrderID + "，内容为：" + cont;

                oper.F_CreateUser = CurrentUser.UserData.F_UserCode;
                oper.F_CreateTime = DateTime.Now;
                oper.F_IsDelete = 0;

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

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

        #region nouse
        ///// <summary>
        ///// 获取可催办工单列表
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult GetCBList()
        //{
        //    ActionResult return NoToken("未知错误，请重新登录");
        //    if (Request.IsAuthenticated)
        //    {
        //        string sql = " and isdel=0 and State !='2'";
        //        DataTable dt = new DataTable();

        //        int userId = CurrentUser.UserData.F_UserId;
        //        if (userId != 0)
        //        {
        //            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
        //            if (ua != null)
        //            {
        //                string strorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("orderid"));
        //                string strtype = HttpUtility.UrlDecode(RequestString.GetQueryString("type"));
        //                string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
        //                string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
        //                string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
        //                string strcode = HttpUtility.UrlDecode(RequestString.GetQueryString("code"));
        //                string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
        //                string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

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

        //                if (strorderid.Trim() != "" && strorderid != "undefined")
        //                {
        //                    sql += " and WorkOrderID like '%" + strorderid.Trim() + "%' ";
        //                }
        //                if (strtype.Trim() != "" && strtype != "undefined")
        //                {
        //                    sql += " and Type = '" + strkey.Trim() + "' ";
        //                }
        //                if (strkey.Trim() != "" && strkey != "undefined")
        //                {
        //                    sql += " and Detail like '%" + strkey.Trim() + "%' ";
        //                }
        //                if (strname.Trim() != "" && strname != "undefined")
        //                {
        //                    sql += " and Customer like '%" + strname.Trim() + "%' ";
        //                }
        //                if (strtel.Trim() != "" && strtel != "undefined")
        //                {
        //                    sql += " and CustomerTel like '%" + strtel + "%'  ";
        //                }
        //                if (strcode.Trim() != "" && strcode != "undefined")
        //                {
        //                    sql += " and CreateUser = '" + strcode.Trim() + "' ";
        //                }
        //                if (strstarttime.Trim() != "" && strstarttime != "undefined")
        //                {
        //                    sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
        //                }
        //                if (strendtime.Trim() != "" && strendtime != "undefined")
        //                {
        //                    sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
        //                }

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

        //                if (strpagesize.Trim() != "")
        //                {
        //                    pagesize = Convert.ToInt32(strpagesize);
        //                }
        //                int recordCount = 0;
        //                dt = BLL.PagerBLL.GetListPager(
        //                    "T_Wo_WorkOrder",
        //                    "T_Wo_WorkOrder.ID",
        //                    "*,dbo.GetUserName(CreateUser) as CreateUserName",
        //                    sql,
        //                    "ORDER BY T_Wo_WorkOrder.ID desc",
        //                    pagesize,
        //                    pageindex,
        //                    true,
        //                    out recordCount);

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

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

        //    }
        //    return res;
        //}

        ///// <summary>
        ///// 获取待接单的工单编号
        ///// </summary>
        ///// <returns></returns>
        //public string GetDJDWorkOrderID(string user)
        //{
        //    string str = string.Empty;

        //    var list = new BLL.T_Wo_WorkOrderItem().GetModelList(" IsDel=0 and Type=1 and (state='0' and ','+ToUser+',' like '%," + user + ",%')  ").Select(p => p.WorkOrderID).Distinct();

        //    foreach (var l in list)
        //    {
        //        if (string.IsNullOrEmpty(str))
        //        {
        //            str = l;
        //        }
        //        else
        //        {
        //            str = str + "','" + l;
        //        }
        //    }

        //    return str;
        //}
        ///// <summary>
        ///// 确认工单
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult SureWorkOrder()
        //{
        //    ActionResult return NoToken("未知错误，请重新登录");
        //    if (Request.IsAuthenticated)
        //    {

        //        int userId = CurrentUser.UserData.F_UserId;
        //        if (userId != 0)
        //        {
        //            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
        //            if (ua != null)
        //            {
        //                return Error("确认失败！");
        //                //int itemid = RequestString.GetInt("itemid", 0);
        //                //Model.T_Wo_WorkOrderItem item = new BLL.T_Wo_WorkOrderItem().GetModel(itemid);
        //                string orderid = RequestString.GetFormString("orderid");
        //                Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
        //                if (model != null)
        //                {
        //                    Model.T_Wo_WorkOrderItem item = new BLL.T_Wo_WorkOrderItem().GetModelList(" WorkOrderID='" + orderid + "' and isdel=0 and Type=1 ").OrderByDescending(p => p.CreateTime).FirstOrDefault();
        //                    if (item != null && item.State == 0 && ("," + item.ToUser + ",").Contains("," + ua.F_UserCode + ","))
        //                    {
        //                        item.SureUser = ua.F_UserCode;
        //                        item.State = 1;
        //                        item.SureTime = DateTime.Now;

        //                        #region 插入操作记录
        //                        Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
        //                        oper.F_WorkOrderId = model.WorkOrderID;
        //                        oper.F_State = model.State;
        //                        oper.F_CallRecordId = model.CallID != null ? int.Parse(model.CallID) : 0;
        //                        oper.F_File = model.Files;

        //                        string userinfo = ua.depname + "-" + ua.F_UserName + "(" + ua.F_UserCode + ")";
        //                        oper.F_Message = userinfo + " 确认了工单";

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

        //                        new BLL.T_Wo_Operation().Add(oper);
        //                        #endregion

        //                        if (new BLL.T_Wo_WorkOrderItem().Update(item))
        //                        {
        //                            return Success("确认成功！");
        //                        }
        //                    }
        //                }
        //            }
        //        }

        //    }
        //    return res;
        //}

        ///// <summary>
        ///// 催办工单
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult AddWorkOrderRemind()
        //{
        //    ActionResult return NoToken("未知错误，请重新登录");
        //    if (Request.IsAuthenticated)
        //    {

        //        int userId = CurrentUser.UserData.F_UserId;
        //        if (userId != 0)
        //        {
        //            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
        //            if (ua != null)
        //            {
        //                return Error("催办失败！");
        //                string orderid = RequestString.GetFormString("orderid");
        //                string cont = RequestString.GetFormString("cont");
        //                string callid = RequestString.GetFormString("callid");
        //                Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
        //                if (model != null)
        //                {
        //                    Model.T_Wo_WorkOrderItem itemlast = new BLL.T_Wo_WorkOrderItem().GetModelList(" WorkOrderID='" + orderid + "' and IsDel=0 and Type=1 and (State=0 or State=1) ").FirstOrDefault();

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

        //                    if (itemlast != null)
        //                    {
        //                        item.ToDept = itemlast.ToDept;
        //                        item.ToUser = itemlast.ToUser;
        //                    }
        //                    else
        //                    {
        //                        var cu = new BLL.T_Sys_UserAccount().GetModel(model.CreateUser);
        //                        if (cu != null)
        //                        {
        //                            item.ToDept = cu.F_DeptId;
        //                            item.ToUser = cu.F_UserCode;
        //                        }
        //                    }

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

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

        //                    #region 插入操作记录
        //                    Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
        //                    oper.F_WorkOrderId = model.WorkOrderID;
        //                    oper.F_State = model.State;
        //                    oper.F_CallRecordId = model.CallID != null ? int.Parse(model.CallID) : 0;
        //                    oper.F_File = model.Files;

        //                    string userinfo = ua.depname + "-" + ua.F_UserName + "(" + ua.F_UserCode + ")";
        //                    oper.F_Message = userinfo + " 催办了工单，工单编号：" + model.WorkOrderID + "，内容为：" + cont;

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

        //                    new BLL.T_Wo_Operation().Add(oper);
        //                    #endregion

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

        //                        //    new BLL.T_Msg_List().Add(msg);
        //                        //}

        //                        return Success("催办成功！");
        //                    }
        //                }
        //            }
        //        }

        //    }
        //    return res;
        //}

        ///// <summary>
        ///// 补充工单
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult AddWorkOrderExten()
        //{
        //    ActionResult return NoToken("未知错误，请重新登录");
        //    if (Request.IsAuthenticated)
        //    {

        //        int userId = CurrentUser.UserData.F_UserId;
        //        if (userId != 0)
        //        {
        //            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
        //            if (ua != null)
        //            {
        //                return Error("补充失败！");
        //                string orderid = RequestString.GetFormString("orderid");
        //                string cont = RequestString.GetFormString("cont");
        //                string file = RequestString.GetFormString("file");
        //                string callid = RequestString.GetFormString("callid");
        //                Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
        //                if (model != null)
        //                {
        //                    Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
        //                    item.WorkOrderID = orderid;
        //                    item.Type = 3;
        //                    item.Detail = cont;
        //                    item.Files = file;
        //                    item.CallID = callid;
        //                    item.State = 0;
        //                    item.IsDel = 0;
        //                    item.IsLast = 0;
        //                    item.IsStart = 0;
        //                    item.IsTimeOut = 0;
        //                    item.CreateUser = ua.F_UserCode;
        //                    item.CreateTime = DateTime.Now;

        //                    #region 插入操作记录
        //                    Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
        //                    oper.F_WorkOrderId = model.WorkOrderID;
        //                    oper.F_State = model.State;
        //                    oper.F_CallRecordId = model.CallID != null ? int.Parse(model.CallID) : 0;
        //                    oper.F_File = model.Files;

        //                    string userinfo = ua.depname + "-" + ua.F_UserName + "(" + ua.F_UserCode + ")";
        //                    oper.F_Message = userinfo + " 补充工单，工单编号：" + model.WorkOrderID + "，内容为：" + cont;

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

        //                    new BLL.T_Wo_Operation().Add(oper);
        //                    #endregion

        //                    if (new BLL.T_Wo_WorkOrderItem().Add(item) > 0)
        //                    {
        //                        return Success("补充成功！");
        //                    }
        //                }
        //            }
        //        }

        //    }
        //    return res;
        //}



        ///// <summary>
        ///// 重新开启工单
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult StartWorkOrder()
        //{
        //    ActionResult return NoToken("未知错误，请重新登录");
        //    if (Request.IsAuthenticated)
        //    {

        //        int userId = CurrentUser.UserData.F_UserId;
        //        if (userId != 0)
        //        {
        //            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
        //            if (ua != null)
        //            {
        //                return Error("开启失败！");
        //                string orderid = RequestString.GetFormString("orderid");
        //                string cont = RequestString.GetFormString("cont");
        //                string file = RequestString.GetFormString("file");
        //                string callid = RequestString.GetFormString("callid");
        //                Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
        //                if (model != null && model.State == 2)
        //                {
        //                    model.State = 1;
        //                    model.LastDealUser = "";
        //                    model.LastDealTime = null;
        //                    if (new BLL.T_Wo_WorkOrder().Update(model))
        //                    {
        //                        var last = new BLL.T_Wo_WorkOrderItem().GetModelList("  WorkOrderID='" + orderid + "' and IsDel=0 ").OrderByDescending(p => p.ID).FirstOrDefault();

        //                        //Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
        //                        //item.WorkOrderID = model.WorkOrderID;
        //                        //item.Type = 5;
        //                        //item.Detail = cont;
        //                        //item.Files = file;
        //                        //item.CallID = callid;
        //                        //item.State = 0;
        //                        //item.IsDel = 0;
        //                        //item.IsLast = 0;
        //                        //item.CreateUser = ua.F_UserCode;
        //                        //item.CreateTime = DateTime.Now;

        //                        //new BLL.T_Wo_WorkOrderItem().Add(item);
        //                        if (last != null)
        //                        {
        //                            Model.T_Wo_WorkOrderItem itemnew = new Model.T_Wo_WorkOrderItem();
        //                            itemnew.WorkOrderID = model.WorkOrderID;
        //                            itemnew.Type = 1;
        //                            itemnew.ToDept = last.ToDept;
        //                            itemnew.ToUser = last.ToUser;
        //                            itemnew.Files = file;
        //                            itemnew.CallID = callid;
        //                            itemnew.IsStart = 1;
        //                            itemnew.IsTimeOut = 0;
        //                            itemnew.State = 0;
        //                            itemnew.IsDel = 0;
        //                            itemnew.IsLast = 0;
        //                            itemnew.CreateUser = ua.F_UserCode;
        //                            itemnew.CreateTime = DateTime.Now;

        //                            #region 插入操作记录
        //                            Model.T_Wo_Operation oper = new Model.T_Wo_Operation();
        //                            oper.F_WorkOrderId = model.WorkOrderID;
        //                            oper.F_State = model.State;
        //                            oper.F_CallRecordId = model.CallID != null ? int.Parse(model.CallID) : 0;
        //                            oper.F_File = model.Files;

        //                            string userinfo = ua.depname + "-" + ua.F_UserName + "(" + ua.F_UserCode + ")";
        //                            oper.F_Message = userinfo + " 重新开启工单，工单编号为：" + model.WorkOrderID;

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

        //                            new BLL.T_Wo_Operation().Add(oper);
        //                            #endregion

        //                            long itemid = new BLL.T_Wo_WorkOrderItem().Add(itemnew);
        //                            if (itemid > 0)
        //                            {
        //                                //foreach (string ur in itemnew.ToUser.Split(','))
        //                                //{
        //                                //    Model.T_Msg_List msg = new Model.T_Msg_List();
        //                                //    msg.Type = 1;
        //                                //    msg.ToUser = ur;
        //                                //    msg.ToID = Int32.Parse(itemid.ToString());
        //                                //    msg.Detail = ua.F_UserName + "重新开启工单，单号：" + model.WorkOrderID;
        //                                //    msg.State = 0;
        //                                //    msg.IsDel = 0;
        //                                //    msg.CreateUser = ua.F_UserCode;
        //                                //    msg.CreateDate = DateTime.Now;

        //                                //    new BLL.T_Msg_List().Add(msg);
        //                                //}
        //                            }
        //                        }

        //                        return Success("开启成功！");
        //                    }
        //                }
        //            }
        //        }

        //    }
        //    return res;
        //}
        #endregion
        /// <summary>
        /// 综合查询的导出工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportListAll()
        {
            string sql = " and isdel=0 ";
            DataTable dt = new DataTable();

            string strorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("orderid"));
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
            string strtype = HttpUtility.UrlDecode(RequestString.GetQueryString("type"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strcode = HttpUtility.UrlDecode(RequestString.GetQueryString("code"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

            string strclbm = RequestString.GetQueryString("clbmid");
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));


            #region 条件
            if (strorderid.Trim() != "" && strorderid != "undefined")
            {
                sql += " and WorkOrderID like '%" + strorderid.Trim() + "%' ";
            }
            if (strstate.Trim() != "" && strstate != "undefined")
            {
                if (strstate.Trim() == "0")
                    sql += " and State <> '2' ";
                else
                    sql += " and State = '2' ";

                //20180518 zhengbingbing
                //sql += " and State = '" + strstate.Trim() + "' ";
            }
            if (strtype.Trim() != "" && strtype != "undefined")
            {
                sql += " and Type = '" + strtype.Trim() + "' ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and Detail like '%" + strkey.Trim() + "%' ";
            }
            if (strcode.Trim() != "" && strcode != "undefined")
            {
                sql += " and CreateUser = '" + strcode.Trim() + "' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and Customer like '%" + strname.Trim() + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and CustomerTel like '%" + strtel + "%'  ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
            }

            if (strusercode.Trim() != "" && strusercode != "undefined")
            {
                sql += " and CreateUser = '" + strusercode.Trim() + "' ";
            }

            if (strclbm.Trim() != "" && strclbm != "undefined")
            {
                sql += " and UnitID = '" + strclbm.Trim() + "' ";
            }

            #endregion
            sql = " select WorkOrderID as '工单编号',"
                + " (case isnull(State,0) when 0 then '未指派' when 1 then '处理中' when 2 then '已完成' else '' end ) as '工单状态',"
                + " Detail as '反映问题',clcontent as '问题处理情况',InfoType as '问题分类',InfoTypeDetail as '热点问题',Unit as '处理部门',dbo.GetUserName(AuditUser) as '处理人',Customer as '客户姓名',CustomerTel as '客户电话',"
                + " CreateUser as '创建人工号',dbo.GetUserName(CreateUser) as '创建人姓名',"
                + " CONVERT(varchar(19), CreateTime, 20) as '创建时间',Source as '工单来源',(case when AuditUser=CreateUser then '是' else '否' end) '是否转办'"
                + "  from T_Wo_WorkOrder where 1=1 " + sql + " ORDER BY T_Wo_WorkOrder.ID desc";
            dt = DbHelperSQL.Query(sql).Tables[0];

            NPOIHelper npoi = new NPOIHelper();
            if (npoi.ExportToExcel("工单列表", dt) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }

        }

        /// <summary>
        /// 导出工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportList()
        {
            string sql = " and isdel=0 ";
            DataTable dt = new DataTable();

            string strorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("orderid"));
            string strltype = HttpUtility.UrlDecode(RequestString.GetQueryString("ltype"));
            string strtype = HttpUtility.UrlDecode(RequestString.GetQueryString("type"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

            #region 息县需求变动
            switch (strltype)
            {
                case "0"://待处理和处理中
                         //sql += " and State ='0' and CreateUser= '" + ua.F_UserCode + "' ";
                    sql += " and (State ='0' or( State ='1' and WorkOrderID in ( '" + GetDWCWorkOrderID(CurrentUser.UserData.F_UserCode) + "')) )";
                    break;
                case "1"://已完成的
                    sql += " and State ='2' and LastDealUser = '" + CurrentUser.UserData.F_UserCode + "' ";
                    break;
                case "2"://我参与的
                    sql += " and (CreateUser= '" + CurrentUser.UserData.F_UserCode + "' or WorkOrderID in ( '" + GetCYWorkOrderID(CurrentUser.UserData.F_UserCode) + "')) ";
                    break;
            }
            #region
            //20180518 zhengbingbing
            //switch (strltype)
            //{
            //    case "0"://我创建的
            //        sql += " and State ='0' and CreateUser= '" + ua.F_UserCode + "' ";
            //        break;
            //    //case "1"://待接单的
            //    //    sql += " and State ='1' and WorkOrderID in ( '" + GetDJDWorkOrderID(ua.F_UserCode) + "') ";
            //    //    break;
            //    case "2"://待完成的
            //        sql += " and State ='1' and WorkOrderID in ( '" + GetDWCWorkOrderID(ua.F_UserCode) + "') ";
            //        break;
            //    case "3"://已完成的
            //        sql += " and State ='2' and LastDealUser = '" + ua.F_UserCode + "' ";
            //        break;
            //    case "4"://我参与的
            //        sql += " and (CreateUser= '" + ua.F_UserCode + "' or WorkOrderID in ( '" + GetCYWorkOrderID(ua.F_UserCode) + "')) ";
            //        break;
            //}
            #endregion
            #endregion

            if (strorderid.Trim() != "" && strorderid != "undefined")
            {
                sql += " and WorkOrderID like '%" + strorderid.Trim() + "%' ";
            }
            if (strtype.Trim() != "" && strtype != "undefined")
            {
                sql += " and Type = '" + strkey.Trim() + "' ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and Detail like '%" + strkey.Trim() + "%' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and Customer like '%" + strname.Trim() + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and CustomerTel like '%" + strtel + "%'  ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
            }

            sql = " select WorkOrderID as '工单编号',( case isnull(Type,0) when 1 then '咨询' when 3 then '投诉建议' else '' end) as '工单类型',"
                + " Detail as '工单内容',Customer as '客户名称',CustomerTel as '客户电话',"
                + " (case isnull(State,0) when 0 then '未指派' when 1 then '处理中' when 2 then '已完结' else '' end ) as '工单状态',"
                + " dbo.GetUserName(ResponUser) as '投诉人',CreateUser as '坐席工号',dbo.GetUserName(CreateUser) as '坐席姓名',"
                + " convert(decimal(18,2),CreateTime as '创建时间'"
                + "  from T_Wo_WorkOrder where 1=1 " + sql;
            dt = DbHelperSQL.Query(sql).Tables[0];

            NPOIHelper npoi = new NPOIHelper();
            if (npoi.ExportToExcel("工单列表", dt) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }

        }

        #endregion

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

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

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

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

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Wo_WorkOrderItem",
                "T_Wo_WorkOrderItem.ID",
                "*,dbo.GetUserName(ToUser) as ToUserName, dbo.GetDeptName(ToDept) as ToDeptName,dbo.GetUserName(SureUser) as SureUserName,dbo.GetUserName(DealUser) as DealUserName,dbo.GetUserName(CreateUser) as CreateUserName",
                sql,
                "ORDER BY T_Wo_WorkOrderItem.ID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

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

            return Content(obj.ToJson());

        }

        /// <summary>
        /// 获取工单明细信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkOrderItem()
        {
            int id = Utils.StrToInt(RequestString.GetQueryString("id"), 0);
            if (id != 0)
            {
                Model.T_Wo_WorkOrderItem userModel = new BLL.T_Wo_WorkOrderItem().GetModel(id);
                if (userModel != null)
                {
                    return Success("获取成功", userModel);
                }
                else
                {
                    return Error("获取失败");
                }
            }
            else
            {
                return Error("参数传输失败");
            }

        }

        /// <summary>
        /// 添加工单明细信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrderItem()
        {
            string orderid = RequestString.GetFormString("orderid");
            int clbm = RequestString.GetInt("clbm", 0);
            int clid = RequestString.GetInt("clid", 0);

            Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID='" + orderid + "'").FirstOrDefault();
            if (model != null)
            {
                Model.T_Wo_WorkOrderItem item = new Model.T_Wo_WorkOrderItem();
                item.WorkOrderID = model.WorkOrderID;
                item.Type = 1;
                item.ToDept = clbm;

                Model.T_Wo_WorkOrderTimeOut to = new BLL.T_Wo_WorkOrderTimeOut().GetModel(model.Type.Value);
                if (to != null)
                {
                    item.LimitTime = to.ItemTime;
                }
                if (clid != 0)
                {
                    Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModel(clid);
                    if (clus != null)
                    {
                        item.ToUser = clus.F_UserCode;
                    }
                }
                else
                {
                    string users = string.Empty;
                    var list = new BLL.T_Sys_UserAccount().GetModelList(" F_DeptId='" + clbm + "'");
                    foreach (var l in list)
                    {
                        if (string.IsNullOrEmpty(users))
                        {
                            users = l.F_UserCode;
                        }
                        else
                        {
                            users = users + "," + l.F_UserCode;
                        }
                    }
                    item.ToUser = users;
                }

                item.IsLast = 0;
                item.IsStart = 0;
                item.IsTimeOut = 0;
                item.State = 0;
                item.CreateUser = CurrentUser.UserData.F_UserCode;
                item.CreateTime = DateTime.Now;

                model.State = 1;//已指派
                new BLL.T_Wo_WorkOrder().Update(model);

                if (new BLL.T_Wo_WorkOrderItem().Add(item) > 0)
                {
                    return Success("新增成功！");
                }
                else
                {
                    return Error("新增失败！");
                }
            }
            else
            {
                return Error("新增失败！");
            }
        }

        /// <summary>
        /// 删除工单明细
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelWorkOrderItem(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }

                string sql = "Update T_Wo_WorkOrderItem set IsDel=1,DelUser='" + CurrentUser.UserData.F_UserCode + "',DelTime=getdate() where ID in(" + idd.TrimEnd(',') + ")";
                if (!string.IsNullOrEmpty(idd.Trim()))
                {
                    if (DbHelperSQL.ExecuteSql(sql) > 0)
                    {
                        return Success("删除成功");
                    }
                    else
                    {
                        return Error("删除失败");
                    }
                }
                else
                {
                    return Error("请选择明细");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }
        #endregion

        #region 工单超时
        /// <summary>
        /// 获取工单超时列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTimeOutList()
        {
            DataTable dt = new DataTable();

            dt = new BLL.T_Wo_WorkOrderTimeOut().GetList(" state=0 ").Tables[0];

            return Success("成功", dt);

        }

        /// <summary>
        /// 获取工单超时信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkOrderTimeOut()
        {
            int id = Utils.StrToInt(RequestString.GetQueryString("id"), 0);
            if (id != 0)
            {
                Model.T_Wo_WorkOrderTimeOut userModel = new BLL.T_Wo_WorkOrderTimeOut().GetModel(id);
                if (userModel != null)
                {
                    return Success("获取成功", userModel);
                }
                else
                {
                    return Error("获取失败");
                }
            }
            else
            {
                return Error("参数传输失败");
            }

        }

        /// <summary>
        /// 添加/修改客户超时
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrderTimeOut()
        {
            int id = RequestString.GetInt("id", 0);
            int type = RequestString.GetInt("type", 0);
            string mtime = RequestString.GetFormString("mtime");
            string itime = RequestString.GetFormString("itime");

            Model.T_Wo_WorkOrderTimeOut timeout = new Model.T_Wo_WorkOrderTimeOut();

            if (id != 0)
            {
                timeout = new BLL.T_Wo_WorkOrderTimeOut().GetModel(id);
                if (timeout != null)
                {
                    timeout.MainTime = decimal.Parse(mtime);
                    timeout.ItemTime = decimal.Parse(itime);

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

                timeout.Type = type;
                timeout.MainTime = decimal.Parse(mtime);
                timeout.ItemTime = decimal.Parse(itime);

                timeout.State = 0;
                timeout.CreateUser = CurrentUser.UserData.F_UserCode;
                timeout.CreateTime = DateTime.Now;

                if (new BLL.T_Wo_WorkOrderTimeOut().Add(timeout) > 0)
                {
                    return Success("新增成功！");
                }
                else
                {
                    return Error("新增失败！");
                }
            }
        }

        /// <summary>
        /// 删除工单超时
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelWorkOrderTimeOut(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }

                string sql = "Delete T_Wo_WorkOrderTimeOut where ID in(" + idd.TrimEnd(',') + ")";
                if (!string.IsNullOrEmpty(idd.Trim()))
                {
                    if (DbHelperSQL.ExecuteSql(sql) > 0)
                    {
                        return Success("删除成功");
                    }
                    else
                    {
                        return Error("删除失败");
                    }
                }
                else
                {
                    return Error("请选择记录");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }
        #endregion

        #region 奖励记录
        //获取微信提交的工单
        public ActionResult GetAMList()
        {
            string sql = " and isdel=0 ";
            DataTable dt = new DataTable();


            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strisreward = HttpUtility.UrlDecode(RequestString.GetQueryString("isreward"));
            string strisaudit = HttpUtility.UrlDecode(RequestString.GetQueryString("isaudit"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            sql += " and State = '2' ";
            sql += " and Type = '3' ";
            sql += " and Source = '微信' ";
            if (strisaudit.Trim() != "" && strisaudit != "undefined")
            {
                sql += " and IsAudit =" + strkey.Trim() + " ";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and Detail like '%" + strkey.Trim() + "%' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and Customer like '%" + strname.Trim() + "%' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and CustomerTel like '%" + strtel + "%'  ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
            }
            if (strisreward.Trim() != "" && strisreward != "undefined")
            {
                sql += " and ISReward=" + strisreward.Trim() + " ";
            }

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Wo_WorkOrder",
                "T_Wo_WorkOrder.ID",
                "*,dbo.GetUserName(CreateUser) as CreateUserName",
                sql,
                "ORDER BY ISReward asc,T_Wo_WorkOrder.ID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            dt.Columns.Add("CBCount", typeof(int));
            foreach (DataRow dr in dt.Rows)
            {
                var list = new BLL.T_Wo_WorkOrderItem().GetList(" WorkOrderID='" + dr["WorkOrderID"].ToString() + "' and IsDel=0 and Type=2 and ','+ToUser+',' like ',%" + CurrentUser.UserData.F_UserCode + "%,' ").Tables[0];
                dr["CBCount"] = list.Rows.Count;
            }

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

            return Content(obj.ToJson());

        }

        //获取奖励记录
        public ActionResult GetAMSList(string woid)
        {
            string sql = "";
            DataTable dt = new DataTable();
            if (woid.Trim() != "")
            {
                sql += " and F_WorkOrderId=" + woid.Trim() + " ";
            }
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

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

            dt = BLL.PagerBLL.GetListPager(
               "T_Wo_AwardRecord",
               "F_Id",
               "*",
               " " + sql,
               "ORDER BY F_Id desc",
               pagesize,
               pageindex,
               true,
               out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());

        }
        //添加奖励记录
        public ActionResult AddAmount(string woid, string amount)
        {
            Model.T_Wo_AwardRecord dModel = new Model.T_Wo_AwardRecord();
            Model.T_Wo_WorkOrder womodel = new BLL.T_Wo_WorkOrder().GetModel(long.Parse(woid));
            #region
            if (womodel != null)
            {
                var uwo = new BLL.T_WO_UserWorkOrder().GetModelList(" F_WorkOrderId=" + woid).FirstOrDefault();
                if (uwo != null)
                {
                    var opu = new BLL.T_Sys_Users().GetModelList(" F_Id=" + uwo.F_UserId).FirstOrDefault();
                    if (opu != null)
                        dModel.F_openid = opu.F_OpenId;
                }
                dModel.F_WorkOrderId = woid;
            }

            dModel.F_RewardUser = CurrentUser.UserData.F_UserId;
            dModel.F_RewardTime = DateTime.Now;
            womodel.RewardTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            dModel.F_RewardAmount = amount;

            dModel.F_CreateUser = CurrentUser.UserData.F_UserCode;
            dModel.F_CreateTime = DateTime.Now;
            //int b = new BLL.T_Wo_AwardRecord().Add(dModel);

            //womodel.ISReward = 1;
            //womodel.RewardAmount = amount;
            //new BLL.T_Wo_WorkOrder().UpdateReward(womodel.ID, womodel.ISReward.Value, womodel.RewardAmount, womodel.RewardTime);
            #endregion
            string s = WxHelper.TenPay(decimal.Parse(amount), dModel.F_openid);
            string[] re = s.Split('|');
            if (re[0].ToLower() == "true")
            {
                dModel.F_IsState = 1;
                dModel.F_IsSendState = 0;
                dModel.F_Remark = "红包发放成功！";
                int b = new BLL.T_Wo_AwardRecord().Add(dModel);

                womodel.ISReward = 1;
                womodel.RewardAmount = amount;
                new BLL.T_Wo_WorkOrder().UpdateReward(womodel.ID, womodel.ISReward.Value, womodel.RewardAmount, womodel.RewardTime);
                if (b > 0)
                {
                    int state = 1;
                    new BLL.T_Wo_AwardRecord().UpdateState(b, state);

                }
                return Success("红包发放成功！");
            }
            else
            {
                dModel.F_IsState = 0;
                dModel.F_IsSendState = 0;
                dModel.F_Remark = "红包发放失败！失败原因：" + re[1];
                int b = new BLL.T_Wo_AwardRecord().Add(dModel);
                return Error("红包发放失败！失败原因：" + re[1]);
            }
        }

        #endregion

        #region 微信报表接口
        //按天统计
        //select SUM(case when state=2 then 1 else 0 end) as finish,SUM(case when state!=2 then 1 else 0 end) as unfinish from T_Wo_WorkOrder where CreateTime between '2017-11-22 00:00:00' and '2017-11-22 23:00:00' and IsDel=0
        #region  数据查询--获取日统计
        public ActionResult GetDayReport()
        {
            string startdate = HttpUtility.UrlDecode(RequestString.GetQueryString("startdate")) + " 00:00:00";
            string enddate = HttpUtility.UrlDecode(RequestString.GetQueryString("startdate")) + " 23:59:59";//enddate
            if (HttpUtility.UrlDecode(RequestString.GetQueryString("startdate")) == null || HttpUtility.UrlDecode(RequestString.GetQueryString("startdate")) == "")
            {
                startdate = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
                enddate = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59";
            }
            DataSet ds = DbHelperSQL.Query("select isnull(SUM(case when state=2 then 1 else 0 end),0) as finish,isnull(SUM(case when state!=2 then 1 else 0 end),0) as unfinish from T_Wo_WorkOrder where CreateTime between '" + startdate + "' and '" + enddate + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");

            DataTable dt = ds.Tables[0];
            return Success("获取微信日统计数据成功", dt);


        }
        #endregion

        #region  数据查询--获取周统计
        public ActionResult GetWeekReport()
        {
            DateTime dtnow = DateTime.Now; //当前时间
            DateTime startWeek = dtnow.AddDays(1 - Convert.ToInt32(dtnow.DayOfWeek.ToString("d"))); //本周周一
            DateTime endWeek = startWeek.AddDays(6); //本周周日
            string startdate = startWeek.ToString("yyyy-MM-dd") + " 00:00:00";
            string enddate = endWeek.ToString("yyyy-MM-dd") + " 23:59:59";//enddate

            #region 周一至周末
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("ID", Type.GetType("System.String"));
            dtnew.Columns.Add("finish", Type.GetType("System.Int32"));
            dtnew.Columns.Add("unfinish", Type.GetType("System.Int32"));
            string starttime = "";
            string endtime = "";
            for (int i = 0; i < 7; i++)
            {
                DataRow dr = dtnew.NewRow();
                starttime = startWeek.AddDays(i).ToString("yyyy-MM-dd") + " 00:00:00";
                endtime = startWeek.AddDays(i).ToString("yyyy-MM-dd") + " 23:59:59";
                DataSet ds0 = DbHelperSQL.Query("select isnull(SUM(case when state=2 then 1 else 0 end),0) as finish,isnull(SUM(case when state!=2 then 1 else 0 end),0) as unfinish from T_Wo_WorkOrder where CreateTime between '" + starttime + "' and '" + endtime + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
                if (ds0 != null && ds0.Tables.Count > 0)
                {
                    DataTable dt0 = ds0.Tables[0];
                    if (dt0.Rows.Count > 0)
                    {
                        dr["ID"] = "周" + GetWeek((i + 1).ToString());
                        dr["finish"] = dt0.Rows[0]["finish"];
                        dr["unfinish"] = dt0.Rows[0]["unfinish"];
                        dtnew.Rows.Add(dr);
                    }
                    else
                    {
                        dr["ID"] = "周" + GetWeek((i + 1).ToString());
                        dr["finish"] = 0;
                        dr["unfinish"] = 0;
                        dtnew.Rows.Add(dr);
                    }
                }
                else
                {
                    dr["ID"] = "周" + GetWeek((i + 1).ToString());
                    dr["finish"] = 0;
                    dr["unfinish"] = 0;
                    dtnew.Rows.Add(dr);
                }
            }
            #endregion
            DataSet ds = DbHelperSQL.Query("select isnull(SUM(case when state=2 then 1 else 0 end),0) as finish,isnull(SUM(case when state!=2 then 1 else 0 end),0) as unfinish from T_Wo_WorkOrder where CreateTime between '" + startdate + "' and '" + enddate + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dtnew.NewRow();
                    dr["ID"] = "本周统计";
                    dr["finish"] = dt.Rows[0]["finish"];
                    dr["unfinish"] = dt.Rows[0]["unfinish"];
                    dtnew.Rows.Add(dr);
                }
                else
                {
                    DataRow dr = dtnew.NewRow();
                    dr["ID"] = "本周统计";
                    dr["finish"] = 0;
                    dr["unfinish"] = 0;
                    dtnew.Rows.Add(dr);
                }

            }
            else
            {
                DataRow dr = dtnew.NewRow();
                dr["ID"] = "本周统计";
                dr["finish"] = 0;
                dr["unfinish"] = 0;
                dtnew.Rows.Add(dr);
            }
            return Success("获取微信周统计数据成功", dtnew);

        }
        #endregion

        #region  数据查询--获取月统计
        public ActionResult GetMonthReport()
        {
            DateTime checkmonth = DateTime.Now;
            string trandate = HttpUtility.UrlDecode(RequestString.GetQueryString("startdate"));
            if (trandate != null && trandate != "")
            {
                checkmonth = Convert.ToDateTime(trandate + "-01 00:00:00");
            }
            string startdate = checkmonth.ToString("yyyy-MM-01") + " 00:00:00";//月初//string startdate = DateTime.Now.ToString("yyyy-MM-01") + " 00:00:00";//月初
            string enddate = DateTime.Parse(checkmonth.ToString("yyyy-MM-01")).AddMonths(1).AddDays(-1).ToShortDateString() + " 23:59:59";//月末
                                                                                                                                          //获取本月总天数
                                                                                                                                          //DateTime dtNow = DateTime.Now;
            int days = DateTime.DaysInMonth(checkmonth.Year, checkmonth.Month);
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("ID", Type.GetType("System.String"));
            dtnew.Columns.Add("finish", Type.GetType("System.Int32"));
            dtnew.Columns.Add("unfinish", Type.GetType("System.Int32"));
            string starttime = "";
            string endtime = "";
            for (int i = 0; i < days; i++)
            {
                DataRow dr = dtnew.NewRow();
                starttime = Convert.ToDateTime(startdate).AddDays(i).ToString("yyyy-MM-dd") + " 00:00:00";
                endtime = Convert.ToDateTime(startdate).AddDays(i).ToString("yyyy-MM-dd") + " 23:59:59";
                DataSet ds0 = DbHelperSQL.Query("select isnull(SUM(case when state=2 then 1 else 0 end),0) as finish,isnull(SUM(case when state!=2 then 1 else 0 end),0) as unfinish from T_Wo_WorkOrder where CreateTime between '" + starttime + "' and '" + endtime + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
                if (ds0 != null && ds0.Tables.Count > 0)
                {
                    DataTable dt0 = ds0.Tables[0];
                    if (dt0.Rows.Count > 0)
                    {
                        dr["ID"] = (i + 1).ToString() + "号";
                        dr["finish"] = dt0.Rows[0]["finish"];
                        dr["unfinish"] = dt0.Rows[0]["unfinish"];
                        dtnew.Rows.Add(dr);
                    }
                    else
                    {
                        dr["ID"] = (i + 1).ToString() + "号";
                        dr["finish"] = 0;
                        dr["unfinish"] = 0;
                        dtnew.Rows.Add(dr);
                    }
                }
                else
                {
                    dr["ID"] = (i + 1).ToString() + "号";
                    dr["finish"] = 0;
                    dr["unfinish"] = 0;
                    dtnew.Rows.Add(dr);
                }
            }
            DataSet ds = DbHelperSQL.Query("select isnull(SUM(case when state=2 then 1 else 0 end),0) as finish,isnull(SUM(case when state!=2 then 1 else 0 end),0) as unfinish from T_Wo_WorkOrder where CreateTime between '" + startdate + "' and '" + enddate + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dtnew.NewRow();
                    dr["ID"] = "本月统计";
                    dr["finish"] = dt.Rows[0]["finish"];
                    dr["unfinish"] = dt.Rows[0]["unfinish"];
                    dtnew.Rows.Add(dr);
                }
                else
                {
                    DataRow dr = dtnew.NewRow();
                    dr["ID"] = "本月统计";
                    dr["finish"] = 0;
                    dr["unfinish"] = 0;
                    dtnew.Rows.Add(dr);
                }

            }
            else
            {
                DataRow dr = dtnew.NewRow();
                dr["ID"] = "本月统计";
                dr["finish"] = 0;
                dr["unfinish"] = 0;
                dtnew.Rows.Add(dr);
            }
            return Success("获取微信月统计数据成功", dtnew);

        }
        #endregion

        #region  数据查询--获取总统计
        public ActionResult GetTotalReport()
        {
            string startdate = HttpUtility.UrlDecode(RequestString.GetQueryString("startdate"));
            string enddate = HttpUtility.UrlDecode(RequestString.GetQueryString("enddate"));//enddate
            string strwhere = "";
            if (startdate != null && startdate != "" && enddate != null && enddate != "")
            {
                strwhere = " and CreateTime between '" + startdate + " 00:00:00' and  '" + enddate + " 23:59:59'";
            }

            DataSet ds = DbHelperSQL.Query("select isnull(SUM(case when state=2 then 1 else 0 end),0) as finish,isnull(SUM(case when state!=2 then 1 else 0 end),0) as unfinish from T_Wo_WorkOrder where  IsDel=0" + strwhere);// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");

            DataTable dt = ds.Tables[0];
            return Success("获取微信全部数据成功", dt);

        }
        #endregion

        #region 按分类统计数据
        #region  数据查询--获取分类统计
        public ActionResult GetReportByFL()
        {
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("fl", Type.GetType("System.String"));
            dtnew.Columns.Add("finish", Type.GetType("System.Int32"));
            dtnew.Columns.Add("unfinish", Type.GetType("System.Int32"));
            DataSet ds = DbHelperSQL.Query("select * from T_Sys_DictionaryValue where F_DictionaryFlag='XXFL'");//获取信息分类
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string fl = dt.Rows[i]["F_Name"].ToString();
                        DataRow dr = dtnew.NewRow();
                        dr["fl"] = fl;

                        DataSet ds1 = DbHelperSQL.Query("select isnull(SUM(case when state=2 then 1 else 0 end),0) as finish,isnull(SUM(case when state!=2 then 1 else 0 end),0) as unfinish from T_Wo_WorkOrder where InfoType='" + fl + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
                        if (ds1 != null && ds1.Tables.Count > 0)
                        {
                            DataTable dt1 = ds1.Tables[0];
                            if (dt1.Rows.Count > 0)
                            {
                                dr["finish"] = dt1.Rows[0]["finish"];
                                dr["unfinish"] = dt1.Rows[0]["unfinish"];
                                dtnew.Rows.Add(dr);
                            }
                            else
                            {
                                dr["finish"] = 0;
                                dr["unfinish"] = 0;
                                dtnew.Rows.Add(dr);
                            }
                        }
                        else
                        {
                            dr["finish"] = 0;
                            dr["unfinish"] = 0;
                            dtnew.Rows.Add(dr);
                        }
                    }
                }
            }
            return Success("获取分类统计数据成功", dtnew);
        }
        #endregion
        #endregion

        #region  数据查询--获取分乡镇统计
        public ActionResult GetReportByDept()
        {
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("dept", Type.GetType("System.String"));
            dtnew.Columns.Add("finish", Type.GetType("System.Int32"));
            dtnew.Columns.Add("unfinish", Type.GetType("System.Int32"));
            DataSet ds = DbHelperSQL.Query("select * from T_Sys_DictionaryValue where F_DictionaryFlag='JBDW'");//获取信息分类
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string fl = dt.Rows[i]["F_Name"].ToString();
                        int flid = Convert.ToInt32(dt.Rows[i]["F_DictionaryValueId"].ToString());
                        DataRow dr = dtnew.NewRow();
                        dr["dept"] = fl;

                        DataSet ds1 = DbHelperSQL.Query("select isnull(SUM(case when state=2 then 1 else 0 end),0) as finish,isnull(SUM(case when state!=2 then 1 else 0 end),0) as unfinish from T_Wo_WorkOrder where County='" + flid + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
                        if (ds1 != null && ds1.Tables.Count > 0)
                        {
                            DataTable dt1 = ds1.Tables[0];
                            if (dt1.Rows.Count > 0)
                            {
                                dr["finish"] = dt1.Rows[0]["finish"];
                                dr["unfinish"] = dt1.Rows[0]["unfinish"];
                                dtnew.Rows.Add(dr);
                            }
                            else
                            {
                                dr["finish"] = 0;
                                dr["unfinish"] = 0;
                                dtnew.Rows.Add(dr);
                            }
                        }
                        else
                        {
                            dr["finish"] = 0;
                            dr["unfinish"] = 0;
                            dtnew.Rows.Add(dr);
                        }
                    }
                }
            }
            return Success("获取乡镇统计数据成功", dtnew);

        }
        #endregion

        #region 导出Excel接口
        #region  数据导出--获取周统计
        public ActionResult GetWeekReportExpt()
        {
            DateTime dtnow = DateTime.Now; //当前时间
            DateTime startWeek = dtnow.AddDays(1 - Convert.ToInt32(dtnow.DayOfWeek.ToString("d"))); //本周周一
            DateTime endWeek = startWeek.AddDays(6); //本周周日
            string startdate = startWeek.ToString("yyyy-MM-dd") + " 00:00:00";
            string enddate = endWeek.ToString("yyyy-MM-dd") + " 23:59:59";//enddate

            #region 周一至周末
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("ID", Type.GetType("System.String"));
            dtnew.Columns.Add("finish", Type.GetType("System.Int32"));
            dtnew.Columns.Add("unfinish", Type.GetType("System.Int32"));
            string starttime = "";
            string endtime = "";
            for (int i = 0; i < 7; i++)
            {
                DataRow dr = dtnew.NewRow();
                starttime = startWeek.AddDays(i).ToString("yyyy-MM-dd") + " 00:00:00";
                endtime = startWeek.AddDays(i).ToString("yyyy-MM-dd") + " 23:59:59";
                DataSet ds0 = DbHelperSQL.Query("select SUM(case when state=2 then 1 else 0 end) as finish,SUM(case when state!=2 then 1 else 0 end) as unfinish from T_Wo_WorkOrder where CreateTime between '" + startdate + "' and '" + enddate + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
                if (ds0 != null && ds0.Tables.Count > 0)
                {
                    DataTable dt0 = ds0.Tables[0];
                    if (dt0.Rows.Count > 0)
                    {
                        dr["ID"] = "周" + GetWeek((i + 1).ToString());
                        dr["finish"] = dt0.Rows[0]["finish"];
                        dr["unfinish"] = dt0.Rows[0]["unfinish"];
                        dtnew.Rows.Add(dr);
                    }
                    else
                    {
                        dr["ID"] = "周" + GetWeek((i + 1).ToString());
                        dr["finish"] = 0;
                        dr["unfinish"] = 0;
                        dtnew.Rows.Add(dr);
                    }
                }
                else
                {
                    dr["ID"] = "周" + GetWeek((i + 1).ToString());
                    dr["finish"] = 0;
                    dr["unfinish"] = 0;
                    dtnew.Rows.Add(dr);
                }
            }
            #endregion
            DataSet ds = DbHelperSQL.Query("select SUM(case when state=2 then 1 else 0 end) as finish,SUM(case when state!=2 then 1 else 0 end) as unfinish from T_Wo_WorkOrder where CreateTime between '" + startdate + "' and '" + enddate + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dtnew.NewRow();
                    dr["ID"] = "本周统计";
                    dr["finish"] = dt.Rows[0]["finish"];
                    dr["unfinish"] = dt.Rows[0]["unfinish"];
                    dtnew.Rows.Add(dr);
                }
                else
                {
                    DataRow dr = dtnew.NewRow();
                    dr["ID"] = "本周统计";
                    dr["finish"] = 0;
                    dr["unfinish"] = 0;
                    dtnew.Rows.Add(dr);
                }

            }
            else
            {
                DataRow dr = dtnew.NewRow();
                dr["ID"] = "本周统计";
                dr["finish"] = 0;
                dr["unfinish"] = 0;
                dtnew.Rows.Add(dr);
            }
            //return Success("获取微信周统计数据成功", dtnew);
            //}
            //导出dtnew
            NPOIHelper npoi = new NPOIHelper();
            string[] col = { "", "已完成", "未完成" };
            if (npoi.ExportToExcel("本周统计数据", dtnew, col) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }

        }
        #endregion

        #region  数据查询--获取月统计
        public ActionResult GetMonthReportExpt()
        {
            string startdate = DateTime.Now.ToString("yyyy-MM-01") + " 00:00:00";//月初
            string enddate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(1).AddDays(-1).ToShortDateString() + " 23:59:59";//月末
                                                                                                                                            //获取本月总天数
            DateTime dtNow = DateTime.Now;
            int days = DateTime.DaysInMonth(dtNow.Year, dtNow.Month);
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("ID", Type.GetType("System.String"));
            dtnew.Columns.Add("finish", Type.GetType("System.Int32"));
            dtnew.Columns.Add("unfinish", Type.GetType("System.Int32"));
            string starttime = "";
            string endtime = "";
            for (int i = 0; i < days; i++)
            {
                DataRow dr = dtnew.NewRow();
                starttime = Convert.ToDateTime(startdate).AddDays(i).ToString("yyyy-MM-dd") + " 00:00:00";
                endtime = Convert.ToDateTime(startdate).AddDays(i).ToString("yyyy-MM-dd") + " 23:59:59";
                DataSet ds0 = DbHelperSQL.Query("select SUM(case when state=2 then 1 else 0 end) as finish,SUM(case when state!=2 then 1 else 0 end) as unfinish from T_Wo_WorkOrder where CreateTime between '" + starttime + "' and '" + endtime + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
                if (ds0 != null && ds0.Tables.Count > 0)
                {
                    DataTable dt0 = ds0.Tables[0];
                    if (dt0.Rows.Count > 0)
                    {
                        dr["ID"] = (i + 1).ToString() + "号";
                        dr["finish"] = dt0.Rows[0]["finish"];
                        dr["unfinish"] = dt0.Rows[0]["unfinish"];
                        dtnew.Rows.Add(dr);
                    }
                    else
                    {
                        dr["ID"] = (i + 1).ToString() + "号";
                        dr["finish"] = 0;
                        dr["unfinish"] = 0;
                        dtnew.Rows.Add(dr);
                    }
                }
                else
                {
                    dr["ID"] = (i + 1).ToString() + "号";
                    dr["finish"] = 0;
                    dr["unfinish"] = 0;
                    dtnew.Rows.Add(dr);
                }
            }
            DataSet ds = DbHelperSQL.Query("select SUM(case when state=2 then 1 else 0 end) as finish,SUM(case when state!=2 then 1 else 0 end) as unfinish from T_Wo_WorkOrder where CreateTime between '" + startdate + "' and '" + enddate + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dtnew.NewRow();
                    dr["ID"] = "本月统计";
                    dr["finish"] = dt.Rows[0]["finish"];
                    dr["unfinish"] = dt.Rows[0]["unfinish"];
                    dtnew.Rows.Add(dr);
                }
                else
                {
                    DataRow dr = dtnew.NewRow();
                    dr["ID"] = "本月统计";
                    dr["finish"] = 0;
                    dr["unfinish"] = 0;
                    dtnew.Rows.Add(dr);
                }

            }
            else
            {
                DataRow dr = dtnew.NewRow();
                dr["ID"] = "本月统计";
                dr["finish"] = 0;
                dr["unfinish"] = 0;
                dtnew.Rows.Add(dr);
            }
            //导出dtnew
            NPOIHelper npoi = new NPOIHelper();
            string[] col = { "日期", "已完成", "未完成" };
            if (npoi.ExportToExcel("月统计数据", dtnew, col) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }
        }
        #endregion

        #region  数据查询--获取分类统计
        public ActionResult GetReportByFLExpt()
        {
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("fl", Type.GetType("System.String"));
            dtnew.Columns.Add("finish", Type.GetType("System.Int32"));
            dtnew.Columns.Add("unfinish", Type.GetType("System.Int32"));
            DataSet ds = DbHelperSQL.Query("select * from T_Sys_DictionaryValue where F_DictionaryFlag='XXFL'");//获取信息分类
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string fl = dt.Rows[i]["F_Name"].ToString();
                        DataRow dr = dtnew.NewRow();
                        dr["fl"] = fl;

                        DataSet ds1 = DbHelperSQL.Query("select SUM(case when state=2 then 1 else 0 end) as finish,SUM(case when state!=2 then 1 else 0 end) as unfinish from T_Wo_WorkOrder where InfoType='" + fl + "' and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
                        if (ds1 != null && ds1.Tables.Count > 0)
                        {
                            DataTable dt1 = ds1.Tables[0];
                            if (dt1.Rows.Count > 0)
                            {
                                dr["finish"] = dt1.Rows[0]["finish"];
                                dr["unfinish"] = dt1.Rows[0]["unfinish"];
                                dtnew.Rows.Add(dr);
                            }
                            else
                            {
                                dr["finish"] = 0;
                                dr["unfinish"] = 0;
                                dtnew.Rows.Add(dr);
                            }
                        }
                        else
                        {
                            dr["finish"] = 0;
                            dr["unfinish"] = 0;
                            dtnew.Rows.Add(dr);
                        }
                    }
                }
                //return Success("获取分类统计数据成功", dtnew);
            }
            //}
            //导出dtnew
            NPOIHelper npoi = new NPOIHelper();
            string[] col = { "信息分类", "已完成", "未完成" };
            if (npoi.ExportToExcel("按信息分类统计数据", dtnew, col) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }
        }
        #endregion

        #region  数据导出--获取分部门统计
        public ActionResult GetReportByDeptExpt()
        {
            DataTable dtnew = new DataTable();
            dtnew.Columns.Add("dept", Type.GetType("System.String"));
            dtnew.Columns.Add("finish", Type.GetType("System.Int32"));
            dtnew.Columns.Add("unfinish", Type.GetType("System.Int32"));
            DataSet ds = DbHelperSQL.Query("select * from T_Sys_DictionaryValue where F_DictionaryFlag='JBDW'");//获取信息分类
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string fl = dt.Rows[i]["F_Name"].ToString();
                        int flid = Convert.ToInt32(dt.Rows[i]["F_DictionaryValueId"].ToString());
                        DataRow dr = dtnew.NewRow();
                        dr["dept"] = fl;

                        DataSet ds1 = DbHelperSQL.Query("select SUM(case when state=2 then 1 else 0 end) as finish,SUM(case when state!=2 then 1 else 0 end) as unfinish from T_Wo_WorkOrder where ResponDept=" + flid + " and IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");
                        if (ds1 != null && ds1.Tables.Count > 0)
                        {
                            DataTable dt1 = ds1.Tables[0];
                            if (dt1.Rows.Count > 0)
                            {
                                dr["finish"] = dt1.Rows[0]["finish"];
                                dr["unfinish"] = dt1.Rows[0]["unfinish"];
                                dtnew.Rows.Add(dr);
                            }
                            else
                            {
                                dr["finish"] = 0;
                                dr["unfinish"] = 0;
                                dtnew.Rows.Add(dr);
                            }
                        }
                        else
                        {
                            dr["finish"] = 0;
                            dr["unfinish"] = 0;
                            dtnew.Rows.Add(dr);
                        }
                    }
                }
                //return Success("获取分类统计数据成功", dtnew);
            }
            //}
            //导出dtnew
            NPOIHelper npoi = new NPOIHelper();
            string[] col = { "部门", "已完成", "未完成" };
            if (npoi.ExportToExcel("按部门分类统计数据", dtnew, col) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }
        }
        #endregion

        #endregion

        //将数字转换为汉字
        public string GetWeek(string num)
        {
            string w = "";
            switch (num)
            {
                case "1":
                    w = "一";
                    break;
                case "2":
                    w = "二";
                    break;
                case "3":
                    w = "三";
                    break;
                case "4":
                    w = "四";
                    break;
                case "5":
                    w = "五";
                    break;
                case "6":
                    w = "六";
                    break;
                case "7":
                    w = "日";
                    break;
                default:
                    w = "";
                    break;
            }
            return w;
        }

        #region 统计奖励数据
        public ActionResult GetReward()
        {
            //select SUM(case when ISReward=1 then 1 else 0 end)as finish,SUM(case when ISReward=0 then 1 else 0 end) as unfinish from T_Wo_WorkOrder where IsDel=0

            DataSet ds = DbHelperSQL.Query("select isnull(SUM(case when ISReward=1 then 1 else 0 end),0) as reward,isnull(SUM(case when ISReward!=1 then 1 else 0 end),0) as unreward from T_Wo_WorkOrder where IsDel=0");// WHERE F_ItemId IN (SELECT F_QIID FROM T_Call_OutAnswers WHERE F_CusTelID IN (select F_CusTelID from T_Call_OutAnswers where F_OptOn between '" + startdate + "' and '" + enddate + "' and F_QID=102 ) and F_QID=101 group by F_QIID)");

            DataTable dt = ds.Tables[0];
            return Success("获取微信奖励统计数据成功", dt);

        }
        #endregion
        #endregion
    }
}