using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.workorder
{
    public class WorkOrderController : BaseController
    {
        #region 工单
        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetListAll()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                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 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 (strstate.Trim() != "" && strstate != "undefined")
                {
                    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 (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.GetDictionaryName(TypeClass) as TypeClassName,dbo.GetUserName(CreateUser) as CreateUserName, dbo.GetDeptName(ResponDept) as ResponDeptName,dbo.GetUserName(ResponUser) as ResponUserName,convert(decimal(18,2),DATEDIFF(minute, CreateTime, ISNULL(LastDealTime, GETDATE()))/60.00) as totalhour",
                    sql,
                    "ORDER BY T_Wo_WorkOrder.ID desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
                dt.Columns.Add("CLDeptName", typeof(String));
                dt.Columns.Add("CLUserName", typeof(String));
                foreach (DataRow dr in dt.Rows)
                {
                    string sqlitem = "select top 1 dbo.GetUserName(ToUser) as ToUserName, dbo.GetDeptName(ToDept) as ToDeptName from T_Wo_WorkOrderItem where WorkOrderID ='" + dr["WorkOrderID"].ToString() + "' and IsDel=0 and Type=1 order by ID desc";
                    var item = DbHelperSQL.Query(sqlitem).Tables[0];
                    if (item.Rows.Count > 0)
                    {
                        dr["CLUserName"] = item.Rows[0]["ToUserName"].ToString();
                        dr["CLDeptName"] = item.Rows[0]["ToDeptName"].ToString();
                    }
                }

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

                res = Content(obj.ToJson());

            }
            return res;
        }

        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string sql = " and isdel=0 ";
                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 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 strpageindex = RequestString.GetQueryString("page");
                        int pageindex = 1;
                        string strpagesize = RequestString.GetQueryString("pagesize");
                        int pagesize = 10;

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

                        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   ";
                        }

                        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.GetDictionaryName(TypeClass) as TypeClassName,dbo.GetUserName(CreateUser) as CreateUserName, dbo.GetDeptName(ResponDept) as ResponDeptName,dbo.GetUserName(ResponUser) as ResponUserName,convert(decimal(18,2),DATEDIFF(minute, CreateTime, ISNULL(LastDealTime, GETDATE()))/60.00) as totalhour",
                            sql,
                            "ORDER BY T_Wo_WorkOrder.ID desc",
                            pagesize,
                            pageindex,
                            true,
                            out recordCount);
                        dt.Columns.Add("CBCount", typeof(int));
                        foreach (DataRow dr in dt.Rows)
                        {
                            var list = new BLL.T_Wo_WorkOrderItem().GetList(" WorkOrderID='" + dr["WorkOrderID"].ToString() + "' and IsDel=0 and Type=2 and ','+ToUser+',' like ',%" + ua.F_UserCode + "%,' ").Tables[0];
                            dr["CBCount"] = list.Rows.Count;
                        }

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

                        res = Content(obj.ToJson());
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 获取可催办工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCBList()
        {
            ActionResult res = 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.GetDictionaryName(TypeClass) as TypeClassName,dbo.GetUserName(CreateUser) as CreateUserName, dbo.GetDeptName(ResponDept) as ResponDeptName,dbo.GetUserName(ResponUser) as ResponUserName,convert(decimal(18,2),DATEDIFF(minute, CreateTime, ISNULL(LastDealTime, GETDATE()))/60.00) as totalhour",
                            sql,
                            "ORDER BY T_Wo_WorkOrder.ID desc",
                            pagesize,
                            pageindex,
                            true,
                            out recordCount);
                        dt.Columns.Add("CBCount", typeof(int));
                        dt.Columns.Add("CLDeptName", typeof(String));
                        dt.Columns.Add("CLUserName", typeof(String));
                        foreach (DataRow dr in dt.Rows)
                        {
                            var list = new BLL.T_Wo_WorkOrderItem().GetList(" WorkOrderID='" + dr["WorkOrderID"].ToString() + "' and IsDel=0 and Type=2 and ','+ToUser+',' like ',%" + ua.F_UserCode + "%,' ").Tables[0];
                            dr["CBCount"] = list.Rows.Count;

                            string sqlitem = "select top 1 dbo.GetUserName(ToUser) as ToUserName, dbo.GetDeptName(ToDept) as ToDeptName from T_Wo_WorkOrderItem where WorkOrderID ='" + dr["WorkOrderID"].ToString() + "' and IsDel=0 and Type=1 order by ID desc";
                            var item = DbHelperSQL.Query(sqlitem).Tables[0];
                            if (item.Rows.Count > 0)
                            {
                                dr["CLUserName"] = item.Rows[0]["ToUserName"].ToString();
                                dr["CLDeptName"] = item.Rows[0]["ToDeptName"].ToString();
                            }
                        }

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

                        res = 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 string GetDWCWorkOrderID(string user)
        {
            string str = string.Empty;

            var list = new BLL.T_Wo_WorkOrderItem().GetModelList(" IsDel=0 and Type=1 and (state='1' and SureUser='" + 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()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                string orderid = RequestString.GetQueryString("orderid");
                //int id = Utils.StrToInt(RequestString.GetQueryString("id"), 0);
                if (!string.IsNullOrEmpty(orderid))
                {
                    //Model.T_Wo_WorkOrder userModel = new BLL.T_Wo_WorkOrder().GetModelList(" WorkOrderID ='"+ orderid + "' ").FirstOrDefault();
                    //if (userModel != null)
                    //{
                    //    var obj = new
                    //    {
                    //        data = userModel,
                    //        item = new BLL.T_Wo_WorkOrderItem().GetList(" IsDel=0 and  WorkOrderID='" + userModel.WorkOrderID + "' "),
                    //        process = new BLL.T_Wo_WorkOrderItem().GetList(" Type=1 and IsDel=0 and  WorkOrderID='" + userModel.WorkOrderID + "' "),
                    //        remind = new BLL.T_Wo_WorkOrderItem().GetList(" Type=2 and IsDel=0 and WorkOrderID='" + userModel.WorkOrderID + "' "),
                    //        exten = new BLL.T_Wo_WorkOrderItem().GetList(" Type=3 and IsDel=0 and WorkOrderID='" + userModel.WorkOrderID + "' "),
                    //        comment = new BLL.T_Wo_WorkOrderItem().GetList(" Type=4 and IsDel=0 and WorkOrderID='" + userModel.WorkOrderID + "' ")
                    //    };
                    //    res = Success("获取成功", userModel);
                    //}
                    //else
                    //{
                    //    res = Error("获取失败");
                    //}

                    string sql = "select *,dbo.GetDictionaryName(TypeClass) as TypeClassName,dbo.GetUserName(CreateUser) as CreateUserName, dbo.GetDeptName(ResponDept) as ResponDeptName,dbo.GetUserName(ResponUser) as ResponUserName from T_Wo_WorkOrder where WorkOrderID ='" + orderid + "'";
                    string sqlitem = "select *,dbo.GetUserName(CreateUser) as CreateUserName from T_Wo_WorkOrderItem where Type=3 and IsDel=0 and WorkOrderID ='" + orderid + "'";

                    var data = DbHelperSQL.Query(sql).Tables[0];
                    var item = DbHelperSQL.Query(sqlitem).Tables[0];
                    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
                    };
                    res = Success("获取成功", obj);
                }
                else
                {
                    res = Error("参数传输失败");
                }

            }
            return res;
        }

        /// <summary>
        /// 添加/修改工单信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrder()
        {
            ActionResult res = 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");
                        int zrbm = RequestString.GetInt("zrbm", 0);
                        int zrid = RequestString.GetInt("zrid", 0);
                        string cont = RequestString.GetFormString("cont");
                        string clcont = RequestString.GetFormString("clcont");
                        string file = RequestString.GetFormString("file");
                        string answer = RequestString.GetFormString("answer");

                        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 (type == 1)
                        {
                            model.State = 2;
                        }
                        else
                            model.State = 0;
                        model.IsDel = 0;
                        model.IsReturn = 0;
                        model.IsReturnBak = 0;
                        model.ResponDept = zrbm;
                        model.IsTimeOut = 0;
                        model.IsUserSend = 0;
                        model.IsAdminSend = 0;

                        Model.T_Sys_UserAccount us = new BLL.T_Sys_UserAccount().GetModel(zrid);
                        if (us != null)
                        {
                            model.ResponUser = us.F_UserCode;
                        }
                        Model.T_Wo_WorkOrderTimeOut to = new BLL.T_Wo_WorkOrderTimeOut().GetModel(type);
                        if (to != null)
                        {
                            model.LimitTime = to.MainTime;
                        }
                        model.IsAdminSend = 0;
                        model.IsUserSend = 0;
                        model.CreateUser = ua.F_UserCode;
                        model.CreateTime = DateTime.Now;

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

                            item.Detail = answer;
                            item.IsLast = 0;
                            item.State = 0;
                            item.IsStart = 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;//已指派
                            }
                        }

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

            }
            return res;
        }

        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelWorkOrder(string[] ids)
        {
            ActionResult res = 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)
                    {
                        if (ids != null && ids.Length > 0)
                        {
                            string idd = " ";
                            foreach (string str in ids)
                            {
                                idd += str + ",";
                            }

                            string sql = "update T_Wo_WorkOrder set IsDel=1,DelUser='" + ua.F_UserCode + "',DelTime=getdate() where ID in(" + idd.TrimEnd(',') + ")";
                            if (!string.IsNullOrEmpty(idd.Trim()))
                            {
                                if (DbHelperSQL.ExecuteSql(sql) > 0)
                                {
                                    res = Success("删除成功");
                                }
                                else
                                {
                                    res = Error("删除失败");
                                }
                            }
                            else
                            {
                                res = Error("请选择记录");
                            }
                        }
                        else
                        {
                            res = Error("获取参数失败");
                        }
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 处理工单信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DealWorkOrder()
        {
            ActionResult res = 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)
                    {
                        res = 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);



                        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

                            int n = new BLL.T_Wo_WorkOrder().DealWorkOrder(orderid, isend, cont, clbm, struser, ua.F_UserCode);
                            if (n > 0)
                            {
                                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
                                res = Success("处理成功");
                            }


                            #region no use
                            //Model.T_Wo_WorkOrderItem item = new BLL.T_Wo_WorkOrderItem().GetModelList(" WorkOrderID='" + orderid + "' and isdel=0 and Type=1 ").FirstOrDefault();
                            //if (item != null)
                            //{
                            //    Model.T_Wo_WorkOrderItem item1 = new BLL.T_Wo_WorkOrderItem().GetModelList(" WorkOrderID='" + orderid + "' and isdel=0 and Type=1 ").OrderByDescending(p => p.CreateTime).FirstOrDefault();
                            //    if (item1 != null && item1.State == 1 && item1.SureUser == ua.F_UserCode)
                            //    {
                            //        if (isend == 0)
                            //        {
                            //            #region 转派
                            //            item1.DealUser = ua.F_UserCode;
                            //            item1.Detail = cont;
                            //            item1.State = 2;
                            //            item1.DealTime = DateTime.Now;

                            //            if (item1.LimitTime > 0)
                            //            {
                            //                TimeSpan sp = item1.CreateTime.Value.Subtract(item1.DealTime.Value);
                            //                if (decimal.Parse(sp.TotalHours.ToString()) > item1.LimitTime.Value)
                            //                {
                            //                    item1.IsTimeOut = 1;
                            //                }
                            //            }

                            //            if (new BLL.T_Wo_WorkOrderItem().Update(item1))
                            //            {
                            //                Model.T_Wo_WorkOrderItem itemnew = new Model.T_Wo_WorkOrderItem();
                            //                itemnew.WorkOrderID = model.WorkOrderID;
                            //                itemnew.ToDept = clbm;

                            //                Model.T_Wo_WorkOrderTimeOut to = new BLL.T_Wo_WorkOrderTimeOut().GetModel(model.Type.Value);
                            //                if (to != null)
                            //                {
                            //                    itemnew.LimitTime = to.ItemTime;
                            //                }
                            //                if (clid != 0)
                            //                {
                            //                    Model.T_Sys_UserAccount clus = new BLL.T_Sys_UserAccount().GetModel(clid);
                            //                    if (clus != null)
                            //                    {
                            //                        itemnew.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;
                            //                        }
                            //                    }
                            //                    itemnew.ToUser = users;
                            //                }

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

                            //                if (new BLL.T_Wo_WorkOrderItem().Add(itemnew) > 0)
                            //                {
                            //                    res = Success("处理成功！");
                            //                }
                            //            }
                            //            #endregion
                            //        }
                            //        else
                            //        {
                            //            #region 结束
                            //            item1.Detail = cont;
                            //            item1.State = 1;
                            //            item1.IsLast = 1;
                            //            item1.DealUser = ua.F_UserCode;
                            //            item1.DealTime = DateTime.Now;

                            //            if (item1.LimitTime > 0)
                            //            {
                            //                TimeSpan sp = item1.CreateTime.Value.Subtract(item1.DealTime.Value);
                            //                if (decimal.Parse(sp.TotalHours.ToString()) > item1.LimitTime.Value)
                            //                {
                            //                    item1.IsTimeOut = 1;
                            //                }
                            //            }

                            //            if (new BLL.T_Wo_WorkOrderItem().Update(item1))
                            //            {
                            //                if (model.LimitTime > 0)
                            //                {
                            //                    TimeSpan sp = model.CreateTime.Value.Subtract(DateTime.Now);
                            //                    if (decimal.Parse(sp.TotalHours.ToString()) > model.LimitTime.Value)
                            //                    {
                            //                        model.IsTimeOut = 1;
                            //                    }
                            //                }

                            //                model.State = 2;
                            //                model.LastDealUser = ua.F_UserCode;
                            //                model.LastDealTime = DateTime.Now;
                            //                if (new BLL.T_Wo_WorkOrder().Update(model))
                            //                {
                            //                    res = Success("处理成功！");
                            //                }
                            //            }
                            //            #endregion
                            //        }
                            //    }
                            //}
                            //else
                            //{
                            //    item = new Model.T_Wo_WorkOrderItem();
                            //    item.WorkOrderID = model.WorkOrderID;
                            //    item.Type = 1;
                            //    item.IsDel = 0;
                            //    item.CreateUser = ua.F_UserCode;
                            //    item.CreateTime = DateTime.Now;

                            //    if (isend == 0)
                            //    {
                            //        #region 转派
                            //        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;

                            //        if (new BLL.T_Wo_WorkOrderItem().Add(item) > 0)
                            //        {
                            //            model.State = 1;
                            //            model.Answer = cont;
                            //            if (new BLL.T_Wo_WorkOrder().Update(model))
                            //            {
                            //                res = Success("处理成功！");
                            //            }
                            //        }
                            //        #endregion
                            //    }
                            //    else
                            //    {
                            //        #region 结束
                            //        item.Detail = cont;
                            //        item.State = 2;
                            //        item.IsLast = 1;
                            //        item.IsStart = 0;
                            //        item.IsTimeOut = 0;
                            //        item.DealUser = ua.F_UserCode;
                            //        item.DealTime = DateTime.Now;
                            //        if (new BLL.T_Wo_WorkOrderItem().Add(item) > 0)
                            //        {
                            //            if (model.LimitTime > 0)
                            //            {
                            //                TimeSpan sp = model.CreateTime.Value.Subtract(DateTime.Now);
                            //                if (decimal.Parse(sp.TotalHours.ToString()) > model.LimitTime.Value)
                            //                {
                            //                    model.IsTimeOut = 1;
                            //                }
                            //            }

                            //            model.State = 2;
                            //            model.LastDealUser = ua.F_UserCode;
                            //            model.LastDealTime = DateTime.Now;
                            //            if (new BLL.T_Wo_WorkOrder().Update(model))
                            //            {
                            //                res = Success("处理成功！");
                            //            }
                            //        }
                            //        #endregion
                            //    }
                            //}
                            #endregion
                        }
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 确认工单
        /// </summary>
        /// <returns></returns>
        public ActionResult SureWorkOrder()
        {
            ActionResult res = 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)
                    {
                        res = 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;
                                if (new BLL.T_Wo_WorkOrderItem().Update(item))
                                {
                                    res = Success("确认成功！");
                                }
                            }
                        }
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 催办工单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrderRemind()
        {
            ActionResult res = 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)
                    {
                        res = 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;

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

                                res = Success("催办成功！");
                            }
                        }
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 补充工单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrderExten()
        {
            ActionResult res = 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)
                    {
                        res = 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;

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

            }
            return res;
        }

        /// <summary>
        /// 评论工单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrderComment()
        {
            ActionResult res = 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)
                    {
                        res = Error("评论失败！");
                        string orderid = RequestString.GetFormString("orderid");
                        string cont = RequestString.GetFormString("cont");
                        string file = RequestString.GetFormString("file");

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

                            if (new BLL.T_Wo_WorkOrderItem().Add(item) > 0)
                            {
                                res = Success("评论成功！");
                            }
                        }
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 重新开启工单
        /// </summary>
        /// <returns></returns>
        public ActionResult StartWorkOrder()
        {
            ActionResult res = 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)
                    {
                        res = 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;

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

                                res = Success("开启成功！");
                            }
                        }
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 导出工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportListAll()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                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"));

                if (strorderid.Trim() != "" && strorderid != "undefined")
                {
                    sql += " and WorkOrderID like '%" + strorderid.Trim() + "%' ";
                }
                if (strstate.Trim() != "" && strstate != "undefined")
                {
                    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   ";
                }

                sql = " select WorkOrderID as '工单编号',( case isnull(Type,0) when 1 then '售前咨询' when 2 then '报修服务' when 3 then '投诉建议' else '' end) as '工单类型',"
                    + " dbo.GetDictionaryName(TypeClass) as '问题类型',Detail as '工单内容',Customer as '客户名称',CustomerTel as '客户电话',"
                    + " (case isnull(State,0) when 0 then '未指派' when 1 then '处理中' when 2 then '已完结' else '' end ) as '工单状态', dbo.GetDeptName(ResponDept) as '投诉部门',"
                    + " dbo.GetUserName(ResponUser) as '投诉人',CreateUser as '坐席工号',dbo.GetUserName(CreateUser) as '坐席姓名',"
                    + " convert(decimal(18,2),DATEDIFF(minute, CreateTime, ISNULL(LastDealTime, GETDATE()))/60.00) as '处理工时',CreateTime as '创建时间',AppointTime as '指派时间',"
                    + " dbo.GetUserName(LastDealUser) as '完结人',LastDealTime 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("导出失败");
                }

            }
            return res;
        }

        /// <summary>
        /// 导出工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string sql = " and isdel=0 ";
                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 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"));

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

                        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 2 then '报修服务' when 3 then '投诉建议' else '' end) as '工单类型',"
                            + " dbo.GetDictionaryName(TypeClass) as '问题类型',Detail as '工单内容',Customer as '客户名称',CustomerTel as '客户电话',"
                            + " (case isnull(State,0) when 0 then '未指派' when 1 then '处理中' when 2 then '已完结' else '' end ) as '工单状态', dbo.GetDeptName(ResponDept) as '投诉部门',"
                            + " dbo.GetUserName(ResponUser) as '投诉人',CreateUser as '坐席工号',dbo.GetUserName(CreateUser) as '坐席姓名',"
                            + " convert(decimal(18,2),DATEDIFF(minute, CreateTime, ISNULL(LastDealTime, GETDATE()))/60.00) as '处理工时',CreateTime as '创建时间',AppointTime as '指派时间',"
                            + " dbo.GetUserName(LastDealUser) as '完结人',LastDealTime 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("导出失败");
                        }
                    }
                }

            }
            return res;
        }

        #endregion

        #region 工单明细
        /// <summary>
        /// 获取工单明细列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetItemList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                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,case Type when 1 then convert(decimal(18,2),DATEDIFF(minute, CreateTime, ISNULL(DealTime, GETDATE()))/60.00) else 0 end as totalhour",
                    sql,
                    "ORDER BY T_Wo_WorkOrderItem.ID desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

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

                res = Content(obj.ToJson());

            }
            return res;
        }

        /// <summary>
        /// 获取工单明细信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkOrderItem()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                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)
                    {
                        res = Success("获取成功", userModel);
                    }
                    else
                    {
                        res = Error("获取失败");
                    }
                }
                else
                {
                    res = Error("参数传输失败");
                }

            }
            return res;
        }

        /// <summary>
        /// 添加工单明细信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrderItem()
        {
            ActionResult res = 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)
                    {
                        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 = ua.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)
                            {
                                res = Success("新增成功！");
                            }
                            else
                            {
                                res = Error("新增失败！");
                            }
                        }
                    }
                }

            }
            return res;
        }

        /// <summary>
        /// 删除工单明细
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelWorkOrderItem(string[] ids)
        {
            ActionResult res = 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)
                    {
                        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='" + ua.F_UserCode + "',DelTime=getdate() where ID in(" + idd.TrimEnd(',') + ")";
                            if (!string.IsNullOrEmpty(idd.Trim()))
                            {
                                if (DbHelperSQL.ExecuteSql(sql) > 0)
                                {
                                    res = Success("删除成功");
                                }
                                else
                                {
                                    res = Error("删除失败");
                                }
                            }
                            else
                            {
                                res = Error("请选择明细");
                            }
                        }
                        else
                        {
                            res = Error("获取参数失败");
                        }
                    }
                }

            }
            return res;
        }
        #endregion

        #region 工单超时
        /// <summary>
        /// 获取工单超时列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTimeOutList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                DataTable dt = new DataTable();

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

                res = Success("成功", dt);

            }
            return res;
        }

        /// <summary>
        /// 获取工单超时信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWorkOrderTimeOut()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                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)
                    {
                        res = Success("获取成功", userModel);
                    }
                    else
                    {
                        res = Error("获取失败");
                    }
                }
                else
                {
                    res = Error("参数传输失败");
                }

            }
            return res;
        }

        /// <summary>
        /// 添加/修改客户超时
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrderTimeOut()
        {
            ActionResult res = 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 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))
                                {
                                    res = Success("修改成功！");
                                }
                                else
                                {
                                    res = Error("修改失败！");
                                }
                            }
                        }
                        else
                        {

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

                            timeout.State = 0;
                            timeout.CreateUser = ua.F_UserCode;
                            timeout.CreateTime = DateTime.Now;

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

            }
            return res;
        }

        /// <summary>
        /// 删除工单超时
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelWorkOrderTimeOut(string[] ids)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                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)
                        {
                            res = Success("删除成功");
                        }
                        else
                        {
                            res = Error("删除失败");
                        }
                    }
                    else
                    {
                        res = Error("请选择记录");
                    }
                }
                else
                {
                    res = Error("获取参数失败");
                }

            }
            return res;
        }
        #endregion
    }
}