using RMYY_CallCenter_Api.Models.Dto;
using RMYY_CallCenter_Api.Models.Enum;
using RMYY_CallCenter_Api.Models.Input;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Transactions;
using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Model;

namespace RMYY_CallCenter_Api.Controllers
{
    public class Con_WorkOrderController : BaseController
    {
        private Bll.T_Dis_WorkOrderItem itembll = new Bll.T_Dis_WorkOrderItem();
        private Bll.T_Sys_UserAccount userbll = new Bll.T_Sys_UserAccount();
        private Bll.T_Sys_Department deptbll = new Bll.T_Sys_Department();
        private Bll.T_Con_WorkOrder orderbll = new Bll.T_Con_WorkOrder();
        private Bll.T_Sys_Role rolebll = new Bll.T_Sys_Role();
        private Bll.T_Sys_GongDan tybll = new Bll.T_Sys_GongDan();
        private Bll.AddLogBll logbll = new Bll.AddLogBll();
        private Bll.T_Sys_SystemConfig configBll = new Bll.T_Sys_SystemConfig();
        private Bll.T_Sys_DictionaryValue dvBll = new Bll.T_Sys_DictionaryValue();
        private static InternalMessagesController msg = new InternalMessagesController();

        //工单详情

        public ActionResult GetWorkOrder()
        {
            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("WorkOrderCode"));
            Model.T_Con_WorkOrder model = orderbll.GetModelByCode(strworkorderid);
            int type = RequestString.GetInt("type", 0);//0基本信息
            if (!string.IsNullOrEmpty(strworkorderid))
            {
                switch (type)
                {
                    case 0:
                        //基本信息
                        string sql = "select *, dbo.GetDepName(F_ComplaintDept) ComplaintDept,[dbo].[GetUserName](F_CreateUser) F_CreateUserName,(select F_urgecount from [T_Wo_CommonBase] where F_WoCode='" + strworkorderid + "') F_UrgeCount,[dbo].[GetUserName](F_HandleBy) F_DealUserName " +
                            "  from T_Con_WorkOrder where F_WorkOrderCode='" + strworkorderid + "'";
                        DataTable dtbase = DbHelperSQL.Query(sql).Tables[0];
                       
                        dtbase.Columns.Add("StateName");
                        dtbase.Columns.Add("TypeName");
                        dtbase.Columns.Add("DealDept");
                        dtbase.Columns.Add("DealUser");
                        dtbase.Columns.Add("DealUserCode");
                        dtbase.Columns.Add("DealDeptName");
                        dtbase.Columns.Add("DealUserName");
                        dtbase.Columns.Add("SourceName");

                        foreach (DataRow dr in dtbase.Rows)
                        {
                            dr["TypeName"] = "业务咨询";

                            if (dr["F_ComplaintSource"] != null && dr["F_ComplaintSource"].ToString()!="")
                            {
                                Model.T_Sys_DictionaryValue dvmodel = dvBll.GetModel(Convert.ToInt32(dr ["F_ComplaintSource"].ToString()));

                                dr["SourceName"] = dvmodel.F_Name;
                            }
                           
                                
                           


                            if (Convert.ToInt32(dr["F_State"]) == (int)EnumWorkOrderState.neworder)
                            {
                                dr["StateName"] = "新工单";
                            }
                            else if (Convert.ToInt32(dr["F_State"]) == (int)EnumWorkOrderState.assign)
                            {
                                dr["StateName"] = "已指派";
                            }
                            else if (Convert.ToInt32(dr["F_State"]) == (int)EnumWorkOrderState.dealing)
                            {
                                dr["StateName"] = "处理中";
                            }
                            else if (Convert.ToInt32(dr["F_State"]) == (int)EnumWorkOrderState.finish)
                            {
                                dr["StateName"] = "已完结";
                            }
                            else if (Convert.ToInt32(dr["F_State"]) == (int)EnumWorkOrderState.audit)
                            {
                                dr["StateName"] = "待审核";
                            }
                            
                        }
                        string Wosql = "select *, dbo.GetDepName(F_DealDept) DealDept," +
                            "[dbo].[GetUserNameByUserId](F_DealUser) UserName,[dbo].[GetUserCodedByUserID](F_DealUser) UserCode" +
                           "  from T_Wo_CommonBase where F_WoCode='" + strworkorderid + "'";
                        DataTable wodtbase = DbHelperSQL.Query(Wosql).Tables[0];
                        if (wodtbase != null && wodtbase.Rows .Count >0)
                        {
                            dtbase.Rows[0]["DealDept"] = wodtbase.Rows[0]["F_DealDept"].ToString();
                            dtbase.Rows[0]["DealUser"] = wodtbase.Rows[0]["F_DealUser"].ToString();
                            dtbase.Rows[0]["DealDeptName"] = wodtbase.Rows[0]["DealDept"].ToString();
                            dtbase.Rows[0]["DealUserName"] = wodtbase.Rows[0]["UserName"].ToString();
                            dtbase.Rows[0]["DealUserCode"] = wodtbase.Rows[0]["UserCode"].ToString();
                            
                        }

                       



                      //  var CommonBase = new BLL.T_Wo_CommonBase().GetModelList($"F_WoCode='{dtbase.Rows[0]["F_WorkOrderCode"].ToString () }' and F_IsDelete=0");
                        return Success("获取成功", dtbase);
                      
                    case 1://工单流程
                        var sqllog = "select *,dbo.GetUserNameUserCode(F_CreateUser) username from T_Dis_WorkOrderItem where F_WoID = '" + model.F_ID  + "' " + " order by F_ID desc";

                        DataTable dtlog = DbHelperSQL.Query(sqllog).Tables[0];
                        return Success("获取成功", dtlog);
                    case 2://回访列表
                      
                        var sqlvisit = "select * from T_Wo_VisitResult where F_WorkOrderCode = '" + model.F_WorkOrderCode  + "' and F_IsDelete=0 " + "" +
                            " order by F_ID desc";
                        DataTable dtvisit = DbHelperSQL.Query(sqlvisit).Tables[0];
                        var config = new Bll.T_Sys_SystemConfig().GetModelList(" F_ParamCode='PlayPath' ").FirstOrDefault();
                        dtvisit.Columns.Add("FilePath", typeof(object));//操作按钮
                        foreach (DataRow dr in dtvisit.Rows)
                        {
                             if (dr["F_Callid"]!=null && dr["F_Callid"].ToString ()!="")
                            {
                                var call = new Bll.T_Call_CallRecords().GetModel(int.Parse(dr["F_Callid"].ToString()));
                                if (call!=null )
                                {
                                    if (call.FilePath != "" && config != null && !string.IsNullOrEmpty(config.F_ParamValue))
                                    {
                                        var ym = config.F_ParamValue;
                                        if (ym.Substring(ym.Length - 1) == "/")
                                        {
                                            ym = ym.Substring(0, ym.Length - 1);
                                        }

                                        string lujing = call.FilePath.Substring(call.FilePath.IndexOf(':') + 1).Replace('\\', '/');
                                        string wlpath = ym + lujing;
                                        dr["FilePath"] = wlpath;
                                    }
                                }
                               
                            }
                           
                        }
                        return Success("获取成功", dtvisit);
                }

            }

            return Error("没传参数");

        }




        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="type"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult GetList(string keywords, string starttime="",string endtime="",int isvisit=-1,int satisfaction = -1,  int type = 0, int pageindex = 1, int pagesize = 10,int state=-1)
        {
            if (User!=null)
            {
                #region 查询条件
                string transql = "";
                List<string> wokerlist = new List<string>();
                string sql = $" and F_IsDel=0";
                DataTable date = new DataTable();
                if (type != 0)
                {
                    //if (type == 1001 || type == 1002 || type == 1003 || type == 1004 || type == 1005)
                    //{
                        sql += $" and F_type2=" + type;
                    //}
                    //else return Error("工单类型错误！");
                }
                if (starttime.Trim() != "" && starttime != "undefined")
                    sql += $" and datediff(day,F_CreateTime,'" + starttime + "') <=0 ";
                if (endtime.Trim() != "" && endtime != "undefined")
                    sql += $" and datediff(day,F_CreateTime,'" + endtime + "')>=0";
                if (!string.IsNullOrEmpty(keywords))
                {
                    sql += $" and (F_Customer like '%" + keywords.Trim() + "%' or F_WorkOrderCode like '%" + keywords.Trim() + "%' or F_Phon like '%" + keywords.Trim() + "%')";
                }
                if (state >= 0)
                {

                    List<int> tlist = Common.GetGongDanState<EnumWorkOrderState>().Select(t=>Convert.ToInt32(t.StateId)).ToList();
                    string liststr = string.Join(",", tlist);
                    if (liststr.Contains(state.ToString()))
                    {
                        sql += $"and F_State=" + state;
                    }
                }
                if (isvisit==1)
                {
                    sql +=  $"and F_State IN(7,10) ";
                }
                if (satisfaction > -1)
                {
                    sql += $"and F_Satisfaction={satisfaction}";
                }
                
                if (User.F_UserCode != "8000")
                {
                    sql += $" and F_CreateUser=" + User.F_UserCode;

                    if (User.F_RoleCode == "HSZ")//护士长角色
                    {
                        string idstr = GetGongDanstr(User.F_UserCode);
                        if (!string.IsNullOrEmpty(idstr))
                        {
                            sql += $" or F_ID in (" + idstr + ")";
                        }
                    }
                    if (User.F_RoleCode == "BZ")//行风办
                    {
                        transql = GetTranPersonsql(User.F_UserCode);
                        sql += $" or F_Id in (" + transql + ")";
                        wokerlist = transql.Split(',').Distinct().ToList();
                    }
                }
                #endregion
                int recordCount = 0;
                if(!string.IsNullOrEmpty(sql))
                {
                    date = Bll.PagerBll.GetListPager
                        (
                        "T_Con_WorkOrder",
                        "F_ID",
                        "*",
                        sql,
                        "ORDER BY F_ID desc",
                        pagesize,
                        pageindex,
                        true,
                        out recordCount);                                                                                                                                       
                }
                List<Model.T_Con_WorkOrder> modellist = orderbll.DataTableToList(date);
                //if (modellist.Count > 0)
                //{
                    //List<Con_WorkOrderInput> Input = modeltoopi(modellist);
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = modellist.Select(p =>
                              new
                              {
                                  Wostate = EnumHelper.GetDescription((EnumWorkOrderState)p.F_State),
                                  typename1 = tybll.GetModel(Convert.ToInt32(p.F_type1))?.F_Name ?? "",
                                  typename2 = tybll.GetModel(Convert.ToInt32(p.F_type2))?.F_Name ?? "",
                                  typename3 = tybll.GetModel(Convert.ToInt32(p.F_type3))?.F_Name ?? "",
                                  roleid=User.F_RoleId,
                                  rolecode=User.F_RoleCode,
                                  F_ID=p.F_ID,
                                  F_WorkOrderCode=p.F_WorkOrderCode,
                                  F_Source=p.F_Source,
                                  F_type1= p.F_type1,
                                  F_type2=p.F_type2,
                                  F_type3=p.F_type3,
                                  F_Customer=p.F_Customer,
                                  F_Sex=p.F_Sex,
                                  F_Phon=p.F_Phon,
                                  F_CusAddress=p.F_CusAddress,
                                  F_IdCard=p.F_IdCard,
                                  F_ServiceItems=p.F_ServiceItems,
                                  F_Address=p.F_Address,
                                  F_FirstCheckHospital=p.F_FirstCheckHospital,
                                  F_NoduleSize=p.F_NoduleSize,
                                  F_FirstFindTime=p.F_FirstFindTime,
                                  F_Urgency=p.F_Urgency,
                                  F_Cathetertype=p.F_Cathetertype,
                                  F_Catheterdept=p.F_Catheterdept,
                                  F_Cathetertime=p.F_Cathetertime,
                                  F_BedNum=p.F_BedNum,
                                  F_InpatientNum=p.F_InpatientNum,
                                  F_DealType=p.F_DealType,
                                  F_WorkOrderContents=p.F_WorkOrderContents,
                                  F_DealOpinions=p.F_DealOpinions,
                                  F_CallID=p.F_CallID,
                                  F_DealResult=p.F_DealResult,
                                  F_HandleBy=p.F_HandleBy,
                                  F_HandleTime=p.F_HandleTime,
                                  F_NotHandleReasons=p.F_NotHandleReasons,
                                  F_ResponDept=p.F_ResponDept,
                                  F_ResponPerson=p.F_ResponPerson,
                                  F_LimitTime=p.F_LimitTime,
                                  F_IsReturnBak=p.F_IsReturnBak,
                                  F_ReturnBakTime=p.F_ReturnBakTime,
                                  F_CreateUserID=p.F_CreateUserID,
                                  F_CreateUser=p.F_CreateUser,
                                  F_CreateTime=p.F_CreateTime,
                                  F_IsDel=p.F_IsDel,
                                  F_CreateUserName=p.F_CreateUserName,
                                  F_DeleteBy=p.F_DeleteBy,
                                  F_DeleteTime=p.F_DeleteTime,
                                  F_IsAudit=p.F_IsAudit,
                                  F_AuditState=p.F_AuditState,
                                  F_AuditUser=p.F_AuditUser,
                                  F_AuditTime=p.F_AuditTime,
                                  F_AuditCont=p.F_AuditCont,
                                  F_AppointTime=p.F_AppointTime,
                                  F_Answer=p.F_Answer,
                                  F_DealContents=p.F_DealContents,
                                  F_File=p.F_File,
                                  F_Satisfaction=p.F_Satisfaction,
                                  F_State=p.F_State,
                                  F_Relationship=p.F_Relationship,
                                  F_FullName = p.F_FullName,
                                  F_IDNumber = p.F_IDNumber,
                                  F_ComplaintDept = p.F_ComplaintDept,
                                  F_ComplaintUser = p.F_ComplaintUser,
                                  F_AppointmentTime=p .F_AppointmentTime
                              }),
                        total = recordCount
                    };
                    return Content(obj.ToJson());
                //}
                //else return Success("暂无工单记录");
                    
            }
            return Error("无操作权限！");
        }


        /// <summary>
        /// 获取待审核工单
        /// </summary>
        /// <param name="ucode"></param>
        /// <returns></returns>
        private string GetGongDanstr(string ucode)
        {
            string wotype = $"{(int)EnumWorkOrder.consultation},{(int)EnumWorkOrder.complaint},{(int)EnumWorkOrder.externalcons},{(int)EnumWorkOrder.appointment}";
            string str = string.Empty;
            str = $"select F_WoID from T_Dis_WorkOrderItem where F_OptType=" + (int)EnumItemOpt.audit + " and F_ItemType=" + (int)EnumItemType.audit + " and F_WoState=" + (int)EnumWorkOrderState.audit + " and F_NextUser=" + ucode + " and F_WoType in(" + wotype + ")";
            //var list = itembll.GetModelList("F_OptType=" + (int)EnumItemOpt.audit + " and F_ItemType=" + (int)EnumItemType.audit + " and F_WoState="+(int)EnumWorkOrderState.audit+" and F_NextUser=" + ucode + " and F_WoType in("+wotype+")").Select(t => t.F_WoID).Distinct().ToList();
            //if (list.Count > 0)
            //    foreach (var item in list)
            //    {
            //        str = string.IsNullOrEmpty(str) ? item.ToString() : str + "," + item.ToString();
            //    }
            return str;
        }
        /// <summary>
        /// 待处理工单
        /// </summary>
        /// <param name="usercode"></param>
        /// <returns></returns>
        private string GetTransql(string usercode)
        {
            string wotype = $"{(int)EnumWorkOrder.consultation},{(int)EnumWorkOrder.complaint},{(int)EnumWorkOrder.externalcons},{(int)EnumWorkOrder.appointment}";
            string str = string.Empty;
            str = $"select F_WoID from T_Dis_WorkOrderItem where F_OptType = " + (int)EnumItemOpt.assign + "and F_WoState = " + (int)EnumWorkOrderState.assign + " and F_NextUser = " + usercode + " and F_WoType in(" + wotype + ")";           
            return str;
        }
        /// <summary>
        /// 操作的工单
        /// </summary>
        /// <param name="usercode"></param>
        /// <param name="roleid"></param>
        /// <returns></returns>
        private string GetTranPersonsql(string usercode)
        {
            string wotype = $"{(int)EnumWorkOrder.consultation},{(int)EnumWorkOrder.complaint},{(int)EnumWorkOrder.externalcons},{(int)EnumWorkOrder.appointment}";
            string wokerlist = $"select F_WoID from T_Dis_WorkOrderItem where F_CreateUser=" + usercode + " or F_NextUser=" + usercode + " and F_WoType in(" + wotype + ")";         
            return wokerlist;
        }

        /// <summary>
        /// 获取工单类型
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTypeState()
        {
            List<TypeState> tlist= Common.GetGongDanState<EnumWorkOrderState>();
            return Content(tlist.ToJson());
        }

        /// <summary>
        /// 获取工单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetModelDetail(int id)
        {
            if (User != null)
            {
                if (id <= 0)
                {
                    return Error("请选择要查询的工单！");
                }
                 var model = orderbll.GetModel(id);
                var user = new Model.T_Sys_UserAccount();
                if (!string.IsNullOrEmpty(model.F_HandleBy))
                {
                    user = userbll.GetModel(model.F_HandleBy);
                }
                var itemlist = itembll.GetModelList(" F_WoID="+ id +"");
                model.typename1 = tybll.GetModel(Convert.ToInt32(model.F_type1))?.F_Name ?? "";
                model.typename2 = tybll.GetModel(Convert.ToInt32(model.F_type2))?.F_Name ?? "";
                model.typename3 = tybll.GetModel(Convert.ToInt32(model.F_type3))?.F_Name ?? "";

                //花费时长
                if (model.F_HandleTime == null || model.F_AcceptTime == null)
                {
                    model.SpendTime = "";
                }
                else
                {
                    string strspend = "";
                    TimeSpan ts = model.F_HandleTime.Value - model.F_AcceptTime.Value;
                    if (ts.Days != 0)
                    {
                        strspend += ts.Days + "天";
                    }
                    strspend += ts.Hours + "时";
                    strspend += ts.Minutes + "分";
                    strspend += ts.Seconds + "秒";
                    model.SpendTime = strspend;
                }


                model.ComplaintSourceName = dvBll.GetModel(Convert.ToInt32(model.F_ComplaintSource))?.F_Name ??"";
                    if (model != null)
                    {
                        var obj = new
                        {
                            state = "success",
                            message = "成功",
                            model = model                       
                        };
                        return Content(obj.ToJson());
                    }
                    else
                        return Error("没有查询到此工单！");
            }
            return Error("无操作权限！");
        }
     
        /// <summary>
        /// 查询工单记录列表
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult GetItemList(int Id,int pageindex=1,int pagesize=10)
        {
            if(User != null)
            {
                string sql = "";
                sql += " and F_WoID=" + Id+ "" ;
                DataTable dt = new DataTable();
                int recordCount;
                dt = Bll.PagerBll.GetListPager(
                                            "T_Con_WorkOrderItem",
                                            "F_ID",
                                            "*",
                                            sql,
                                            "ORDER BY F_ID desc",
                                            pagesize,
                                            pageindex,
                                            true,
                                            out recordCount);
                List<Model.T_Con_WorkOrderItem> itemlists = new Bll.T_Con_WorkOrderItem().DataTableToList(dt);
                if (itemlists != null)
                {
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = dt,
                        total = recordCount
                    };
                    return Content(obj.ToJson());
                }
                else
                {
                    return Error("暂无工单记录！");
                }
                    
            }
            return Error("无操作权限！");
        }

        /// <summary>
        /// 添加工单
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWorkOrder(Con_WorkOrderInput input, int overtime = 0, int opt = 0, string cont = "",string  clid="",int clbm=0)
        {

            if (User != null)
            {
                #region 添加判断
                //if (!(input.F_Type2 != 1001 || input.F_Type2 != 1002 || input.F_Type2 != 1003 || input.F_Type2 != 1004 || input.F_Type2 != 1005))
                //    return Error("工单类型错误！");
           
                if (string.IsNullOrEmpty(input.F_Customer))
                    return Error("请输入客户姓名！");
                if (string.IsNullOrEmpty(input.F_Phon))
                    return Error("请输入客户电话！");
                if (input.F_Type2 == 1004)
                {
                    if (string.IsNullOrEmpty(input.F_ServiceItems))
                        return Error("请选择服务项目！");
                }
                if (input.F_Type2 == 1003)
                {
                    if (string.IsNullOrEmpty(input.F_Address))
                        return Error("请填写地区！");
                    if (input.F_Urgency == null)
                        return Error("请选择紧急程度！");
                }
                if (string.IsNullOrEmpty(input.F_WorkOrderContents))
                    return Error("请输入工单内容！");
                #endregion
                var model = new Model.T_Con_WorkOrder();
                model = inputtoobj(model, input, 0);
                var gdmodel = new Bll.T_Sys_GongDan().GetModel(Convert.ToInt32(input.F_Type1));
                if (gdmodel != null)
                {
                    model.F_LimitTime =Convert.ToDecimal( gdmodel.F_TimeOut) ;
                }
                if (opt == 1)
                    model.F_DealType = "立即办理";
                else if (opt == 2)
                    model.F_DealType = "提交审核";
                else if (opt == 3)
                    model.F_DealType = "转派";
                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
                {
                    #region 添加工单
                    model.F_ReplayCount = 0;

                    //业务咨询类工单满意度   1、直接完工 使用IVR满意度
                    if (!string.IsNullOrEmpty(model.F_CallID) && opt == 1)
                    {
                        Bll.T_Call_CallRecords callbll = new Bll.T_Call_CallRecords();
                        Model.T_Call_CallRecords  callmodel=callbll.GetModelByCallId(model.F_CallID);
                        model.F_Satisfaction = callmodel.MYD;
                    }
                    //业务咨询工单添加用户信息
                    var sql = $"select count(1) from T_Cus_Customer where F_Telephone='{input.F_Phon}' " +
                        $" and F_CustomerName='{input.F_Customer}'";
                    if (int .Parse(DbHelperSQL.GetSingle(sql).ToString()) <=0)
                    {
                        Model.T_Cus_Customer cusmodel = new Model.T_Cus_Customer();
                        Bll.T_Cus_Customer cusbll = new Bll.T_Cus_Customer();
                        cusmodel.F_Address = input.F_Address;
                        cusmodel.F_Telephone = input.F_Phon;
                        cusmodel.F_Sex = input.F_Sex == 0 ? "男" : "女";
                        cusmodel.F_CustomerName = input.F_Customer;
                        cusmodel.F_AboutLinkMan = input.F_FullName;//患者姓名
                        cusmodel.F_IdCard = input.F_IDNumber;
                        cusmodel.F_RelationShip = input.F_Relationship;//与患者关系
                        cusmodel.F_Address = input.F_CusAddress;
                        cusmodel.F_CreateBy = User.F_UserCode;
                        cusmodel.F_CreatedOn = DateTime.Now;
                        cusbll.Add(cusmodel);
                    }

                    int n = orderbll.Add(model);
                    if (n > 0)
                    {
                        Model.T_Con_WorkOrder work = orderbll.GetModel(n);
                        var deptmodel = deptbll.GetModel(User.F_DeptId);
                        string deptname = "";
                        if (deptmodel != null)
                            deptname = deptmodel.F_DeptName + "-";
                       logbll.AddLog(work.F_ID, 0,(int)work.F_type1, deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "创建工单", (int)EnumWorkOrderState.neworder, (int)EnumItemOpt.create, "", 0, User.F_UserCode);
                        if (opt == 1)//立即办理
                        {

                            //if (input.F_Type2 == 1001 || input.F_Type2 == 1003)
                            //{
                                var res = DealWO(User, work, cont, "", 1);
                                if (res)
                                {
                                    #region 给患者发送短信
                                    #endregion
                                }
                            //}
                            //else return Error("此工单类型不支持立即办理！");
                        }
                        else if (opt == 2)//提交审核
                        {
                            if (input.F_Type2 == 1002)//投诉建议需要提交审核
                            {
                                Model.T_Sys_UserAccount userleader = userbll.GetModelList(" F_DeptId=" + deptmodel.F_DeptId + " and F_RoleId=2016 ").FirstOrDefault();//护士长角色
                                if (userleader != null)
                                {
                                    work.F_State = (int)EnumWorkOrderState.audit;
                                    orderbll.Update(work);
                                   logbll.AddLog(work.F_ID, (int)work.F_State,(int)work.F_type1, deptname + userleader.F_UserName + "(" + User.F_UserCode + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, userleader.F_UserCode, userleader.F_DeptId, User.F_UserCode);
                                }
                                else
                                    return Error("提交审核失败！");
                            }
                            else return Error("此工单类型不支持审核！");

                        }
                        else if (opt == 3)//转派
                        {
                            bool tt = AssignWO(User, work, cont, clid, clbm);
                            if (tt)
                            {
                                #region  给健康事业部或 置管室 推送一条钉钉消息
                                #endregion
                            }
                        }

                    }
                    else
                        return Error("添加失败！");
                    #endregion
                    trans.Complete();
                }
                return Success("添加成功！");
            }
            return Error("无操作权限！");
        }

        /// <summary>
        /// 修改工单
        /// </summary>
        /// <param name="input"></param>
        /// <param name="opt"></param>
        /// <param name="cont"></param>
        /// <returns></returns>
        public ActionResult UpdateWorkOrder(Con_WorkOrderInput input, int opt = 0, string cont = "", string  clid = "", int clbm = 0)
        {
            if (User != null)
            {
                //Model.T_Sys_Role role = rolebll.GetModel(user.F_RoleId);
                #region 添加判断
                //if (!(input.F_Type2 != 1001 || input.F_Type2 != 1002 || input.F_Type2 != 1003 || input.F_Type2 != 1004 || input.F_Type2 != 1005))
                //    return Error("工单类型错误！");
                if (string.IsNullOrEmpty(input.F_Customer))
                    return Error("请输入客户姓名！");
                if (string.IsNullOrEmpty(input.F_Phon))
                    return Error("请输入客户电话！");
                if (input.F_Type2 == 4)
                {
                    if (string.IsNullOrEmpty(input.F_ServiceItems))
                        return Error("请选择服务项目！");
                }
                if (input.F_Type2 == 3)
                {
                    if (string.IsNullOrEmpty(input.F_Address))
                        return Error("请填写地区！");
                    if (input.F_Urgency == null)
                        return Error("请选择紧急程度！");
                }
                if (string.IsNullOrEmpty(input.F_WorkOrderContents))
                    return Error("请输入工单内容！");
                #endregion
                var model = orderbll.GetModel(input.F_ID);
                if (model == null)
                    return Error("查询不到此工单！");
                if (User.F_UserCode != "8000")
                {
                    if (model.F_CreateUser != User.F_UserCode )
                        return Error("非创建人不能修改工单！");
                    if (model.F_State == (int)EnumWorkOrderState.assign)
                        return Error("此工单已派单不能修改！");
                    else if (model.F_State == (int)EnumWorkOrderState.finish)
                        return Error("此工单已处理不能修改！");
                }
                model = inputtoobj(model, input, 1);
                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
                {
                    #region 修改工单
                    if (opt == 1)
                        model.F_DealType = "立即办理";
                    else if (opt == 2)
                        model.F_DealType = "提交审核";
                    else if (opt == 3)
                        model.F_DealType = "转派";
                    bool n = orderbll.Update(model);
                    if (n)
                    {
                        var deptmodel = deptbll.GetModel(User.F_DeptId);
                        string deptname = "";
                        if (deptmodel != null)
                            deptname = deptmodel.F_DeptName + "-";
                       logbll.AddLog(input.F_ID, 0,(int)model.F_type1, deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "修改工单", (int)EnumItemType.update, (int)EnumItemOpt.update, "", 0, User.F_UserCode);
                        if (opt == 1)//立即办理
                        {
                            //if (input.F_Type2 == 1001 || input.F_Type2 == 1003)
                            //{
                                var res = DealWO(User, model, cont, "", 1);
                                if (res)
                                {
                                    #region 给患者发送短信
                                    #endregion
                                }
                            //}
                            //else return Error("此工单类型不支持立即办理！");

                        }
                        else if (opt == 2)//提交审核
                        {
                            if (input.F_Type2 == 1002)//投诉建议需要提交审核
                            {
                                Model.T_Sys_UserAccount userleader = userbll.GetModelList(" F_DeptId=" + deptmodel.F_DeptId + " and F_RoleId=2016 ").FirstOrDefault();//护士长角色
                                if (userleader != null)
                                {
                                    model.F_State = (int)EnumWorkOrderState.audit;
                                    orderbll.Update(model);
                                   logbll.AddLog(model.F_ID, (int)model.F_State, (int)model.F_type1, deptname + userleader.F_UserName + "(" + User.F_UserCode + ")" + "待审批", (int)EnumItemType.audit, (int)EnumItemOpt.audit, userleader.F_UserCode, userleader.F_DeptId, User.F_UserCode);
                                }
                                else
                                    return Error("提交审核失败！");
                            }
                            else return Error("此工单类型不支持审核！");

                        }
                        else if (opt == 3)//转派
                        {
                            bool tt = AssignWO(User, model, cont, clid , clbm );
                            if (tt)
                            {
                                #region  给健康事业部或 置管室 推送一条钉钉消息
                                #endregion
                            }
                        }

                    }
                    else
                        return Error("修改失败！");
                    #endregion
                    trans.Complete();
                }
                return Success("操作成功！");

            }

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

        }

        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //public ActionResult DelWorkOrder(int id)
        //{
        //    int userId = User.F_UserId;
        //    if (userId != 0)
        //    {
        //        if (id <= 0)
        //            return Error("选择要删除的工单！");
        //        var model = orderbll.GetModel(id);
        //        if (model == null)
        //            return Error("查询不到此工单！");
        //        Model.T_Sys_UserAccount ua = userbll.GetModel(userId);
        //        if (ua == null)
        //            return Error("无操作权限！");
        //        if (ua.F_UserCode != model.F_CreateUser)
        //            return Error("非创建人不能删除工单！");
        //        if (orderbll.Delete(id))
        //            return Success("操作成功！");
        //        else return Error("设置失败！");
        //    }            
        //    return Error("无操作权限！");
        //}


        /// <summary>
        /// 删除工单
        /// </summary>
        /// <returns></returns>
        public ActionResult DelWorkOrder(string WorkOrderCode)
        {
            if (!string .IsNullOrEmpty (WorkOrderCode))
            {
                Model.T_Con_WorkOrder womodel = orderbll.GetModelByCode (WorkOrderCode);
                if (womodel != null)//0)
                {
                    #region 修改工单记录
                    womodel.F_IsDel = 1;
                    womodel.F_DeleteBy = User.F_UserCode;
                    womodel.F_DeleteTime = DateTime.Now;
                    orderbll.Update(womodel);
                    #endregion

                    #region 插入操作记录
                    logbll.AddLog(womodel.F_ID, (int)womodel.F_type1, (int)womodel.F_State, User.F_UserName + "(" + User.F_UserCode + ")" + "删除了工单", (int)EnumItemType.delete, (int)EnumItemOpt.delete, "", 0, User.F_UserCode);
                    #endregion
                }
                else return Error("删除失败！");
                return Success("删除成功！");
            }
            return Error("请选择要删除的记录！");
        }


        /// <summary>
        /// 根据传入的对象和input的内容返回对象（添加修改使用）
        /// </summary>
        private Model.T_Con_WorkOrder inputtoobj(Model.T_Con_WorkOrder model, Con_WorkOrderInput input, int type)
        {
            string usercode = User.F_UserCode;
            var newmodel = model;
            if (input.F_ID != 0)
            {
                model.F_ID = input.F_ID;
            }
            else
            {
                model.F_ID = model.F_ID;//工单ID
            }
            if (type == 0)
            {
                model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");  //工单编号  
                model.F_Source = input.F_Source;//1电话2系统3App
            }
            else
            {
                model.F_WorkOrderCode = model.F_WorkOrderCode;//工单编号
                model.F_Source = model.F_Source;//工单来源
            }
            model.F_type1 = input.F_Type1;//一级工单类型
            model.F_type2 = input.F_Type2;//工单类型:健康咨询，投诉建议，外聘专家咨询，家庭预约上门，静脉置管维护
            model.F_type3 = input.F_Type3;//三级工单类型

            model.F_Customer = input.F_Customer;//来电人姓名
            model.F_Sex = input.F_Sex;
            model.F_Phon = input.F_Phon;//来电人电话
            model.F_CusAddress = input.F_CusAddress;//地址
            model.F_IdCard = input.F_IdCard;//身份证号
           if (input.F_AppointmentTime!=null )
            {
                if ( model.F_AppointmentTime != input.F_AppointmentTime&&!string .IsNullOrEmpty (model.F_Phon))
                {
                    if (model.F_Phon.Length > 11)
                        model.F_Phon = model.F_Phon.Substring(1, 11);
                    var Template = new BLL.T_SMS_Template().GetModelList("F_Title='两癌筛查' and F_State=1 and F_IsDelete=0");
                    if (Template!=null && Template.Count >0)
                    {
                        Template[0].F_Content = Template[0].F_Content.Replace("#P#", input.F_AppointmentTime.Value.ToString("yyyy年MM月dd日HH时"));
                        SMSController.AddSmS(User.F_UserId, Template[0].F_Content,
                        model.F_Phon.Trim(), model.F_WorkOrderCode , Template[0].F_ID );
                    }

                   
                }
                model.F_AppointmentTime = input.F_AppointmentTime;
            }
            
                 model.F_Relationship = input.F_Relationship;
            model.F_FullName = input.F_FullName;
            model.F_IDNumber = input.F_IDNumber;
            model.F_ComplaintDept = input.F_ComplaintDept;
            model.F_ComplaintUser = input.F_ComplaintUser;
            model.F_ComplaintSource = input.F_ComplaintSource;

            model.F_ServiceItems = input.F_ServiceItems;//服务项目
            model.F_EmergencyTypes = input.EmergencyTypes;
        
                model.F_Address = input.F_Address;//地区
                model.F_FirstCheckHospital = input.F_FirstCheckHospital;//首次检查医院
                model.F_NoduleSize = input.F_NoduleSize;//肺结节大小
                model.F_FirstFindTime = input.F_FirstFindTime;//首次发现肺结节时间
                if (!string.IsNullOrEmpty(input.F_Urgency.ToString()))
                    model.F_Urgency = input.F_Urgency;// 紧急程度:0,常规1，紧急
                else
                    model.F_Urgency = model.F_Urgency;
            
             model.F_Cathetertype = input.F_Cathetertype;//  
                model.F_Catheterdept = input.F_Catheterdept;//置管科室
                model.F_Cathetertime = input.F_Cathetertime;//置管时间
                model.F_BedNum = input.F_BedNum;//床号
                model.F_InpatientNum = input.F_InpatientNum;//住院号
            if (input.LeaveRecordId != null &&input .LeaveRecordId > 0)
            {
                var ld = new Bll.T_Call_LeaveRecord().GetModel(input.LeaveRecordId.Value );
                if (ld != null)
                {

                    ld.F_Status = 1;
                    ld.F_DealTime = DateTime.Now;
                    ld.F_UserId = User.F_UserId;
                    ld.F_UserCode = User.F_UserCode;
                    ld.F_UserName = User.F_UserName;
                    ld.F_WorkOrderId = model.F_WorkOrderCode;
                    ld.F_Type = 1000;
                    new Bll.T_Call_LeaveRecord().Update(ld);
                    model.F_LeaveRecordId = input.LeaveRecordId;
                }
            }


            //model.F_DealType = input.F_DealType;//处理方式：立即办理，提交审核，转派部门
            model.F_WorkOrderContents = input.F_WorkOrderContents;//工单内容
            model.F_DealOpinions = input.F_DealOpinions;//处理意见  
            //model.F_DealContents = input.F_DealContents;//处理内容
            if (!string.IsNullOrEmpty(input.F_CallID))
            {
                model.F_CallID = input.F_CallID;//通话记录id
            }
            else
                model.F_CallID = model.F_CallID;//通话记录id
            if (type == 1)
            { 
                model.F_State = model.F_State;//工单状态
                model.F_CreateTime = model.F_CreateTime;//添加时间
                model.F_CreateUser = model.F_CreateUser;//添加人
            }
            else
            {               
                model.F_State = (int)EnumWorkOrderState.neworder;//0
                model.F_CreateUser = User.F_UserCode;
                model.F_CreateUserName = User.F_UserName;
                model.F_CreateTime = DateTime.Now;//添加时间
            }
            model.F_IsDel = 0;
            model.F_IsTimeOut = 0;
            return model;
        }


        /// <summary>
        /// 添加工单记录
        /// </summary>
        //public long AddLog(int woid, int wostate, string content, int itemtype, int opttype, string nextuser, int nextdept, Model.T_Sys_UserAccount nowUser, int F_IsUsed = 0)
        //{

        //    Model.T_Con_WorkOrderItem itemModel = new Model.T_Con_WorkOrderItem();
        //    #region 
        //    //处理当前工单的记录之前的记录过期
        //    var itemlast = itembll.GetModelList(" isnull(F_IsUsed,'0')='0' and F_ItemType=" + itemtype + " and  F_WoID=" + woid + " ");
        //    if (F_IsUsed == 0)
        //    {

        //        if (itemlast.Count > 0)
        //        {
        //            foreach (var it in itemlast)
        //            {
        //                it.F_IsUsed = 1;
        //                itembll.Update(it);
        //            }
        //        }
        //    }
        //    #endregion
        //    itemModel.F_WoID = woid;
        //    itemModel.F_WoState = wostate;
        //    itemModel.F_ItemType = itemtype;
        //    itemModel.F_OptType = opttype;
        //    itemModel.F_OptContent = content;
        //    itemModel.F_NextUser = nextuser;
        //    itemModel.F_NextDept = nextdept;
        //    itemModel.F_IsSMS = 0;
        //    itemModel.F_IsUsed = F_IsUsed;
        //    itemModel.F_CreateTime = DateTime.Now;
        //    itemModel.F_CreateUser = nowUser.F_UserCode;
        //    var res = itembll.Add(itemModel);
        //    return res;
        //}

        /// <summary>
        /// 根据model返回Input对象
        /// </summary>
        private List<Con_WorkOrderInput> modeltoopi(List<Model.T_Con_WorkOrder> modellist)
        {
            if (modellist != null && modellist.Count > 0)

            {
                List<Con_WorkOrderInput> Inputlist = new List<Con_WorkOrderInput>();
                foreach (var item in modellist)
                {
                    Con_WorkOrderInput Inputmodel = new Con_WorkOrderInput();
                    Inputmodel.F_ID = item.F_ID;
                    Inputmodel.F_WorkOrderCode = item.F_WorkOrderCode;//工单编号
                    Inputmodel.F_Source = item.F_Source;//工单来源

                    Inputmodel.F_Type1 = item.F_type1;//工单来源
                    if (item.F_type1 == 1001)
                    {
                        Inputmodel.F_TypeName1 = "健康咨询";//工单类别最高
                    }
                    else if (item.F_type1 == 1002)
                    {
                        Inputmodel.F_TypeName1 = "投诉建议";
                    }
                    else if (item.F_type1 == 1003)
                    {
                        Inputmodel.F_TypeName1 = "外聘专家咨询";
                    }
                    else if (item.F_type1 == 1004)
                    {
                        Inputmodel.F_TypeName1 = "家庭预约上门";
                    }
                    else
                    {
                        Inputmodel.F_TypeName1 = "静脉置管维护";
                    }
                    if (item.F_type2 != null && item.F_type2 > 0) //工单级别二级
                    {
                        int num = (int)(item.F_type2);
                        Model.T_Sys_GongDan gd = new Bll.T_Sys_GongDan().GetModel(num);
                        if (gd != null)
                        {
                            Inputmodel.F_TypeName2 = gd.F_Name;
                            Inputmodel.F_Type2 = gd.F_GDId;
                        }
                    }

                    if (item.F_type3 != null && item.F_type3 > 0) //工单级别三级
                    {
                        int num = (int)(item.F_type3);
                        Model.T_Sys_GongDan gdmin = new Bll.T_Sys_GongDan().GetModel(num);
                        if (gdmin != null)
                        {
                            Inputmodel.F_TypeName3 = gdmin.F_Name;
                            Inputmodel.F_Type3 = gdmin.F_GDId;
                        }
                    }
                    Inputmodel.F_State = item.F_State;
                    #region 工单状态
                    if (item.F_State == 0)//工单状态
                    {
                        Inputmodel.F_StateName = "待指派";
                    }
                    else if (item.F_State == 1)
                    {
                        Inputmodel.F_StateName = "待接单";
                    }
                    else if (item.F_State == 2)
                    {
                        Inputmodel.F_StateName = "待处理";
                    }
                    else if (item.F_State == 3)
                    {
                        Inputmodel.F_StateName = "已退回";
                    }
                    else if (item.F_State == 4)
                    {
                        Inputmodel.F_StateName = "异常退回";
                    }
                    else if (item.F_State == 5)
                    {
                        Inputmodel.F_StateName = "处理中";
                    }
                    else if (item.F_State == 6)
                    {
                        Inputmodel.F_StateName = "待审核";
                    }
                    else if (item.F_State == 10)
                    {
                        Inputmodel.F_StateName = "已完结";
                    }
                    #endregion
                    Inputmodel.F_Customer = item.F_Customer;//来电人姓名
                    Inputmodel.F_Sex = item.F_Sex;//性别
                    Inputmodel.F_CusAddress = item.F_CusAddress;//地址
                    Inputmodel.F_Phon = item.F_Phon;//电话
                    Inputmodel.F_IdCard = item.F_IdCard;//身份证号
                    if (item.F_type1 == 1004)
                    {
                        Inputmodel.F_ServiceItems = item.F_ServiceItems;//服务项目
                    }
                    if (item.F_type1 == 1003)
                    {
                        Inputmodel.F_Address = item.F_Address;//地区
                        Inputmodel.F_FirstCheckHospital = item.F_FirstCheckHospital;//首次检查医院
                        Inputmodel.F_NoduleSize = item.F_NoduleSize;//肺结节大小
                        Inputmodel.F_FirstFindTime = item.F_FirstFindTime;//首次发现肺结节时间
                        Inputmodel.F_Urgency = item.F_Urgency;//紧急程度
                    }
                    if (item.F_type1 == 1005)
                    {
                        Inputmodel.F_Cathetertype = item.F_Cathetertype;//置管类型
                        Inputmodel.F_Catheterdept = item.F_Catheterdept;//置管科室
                        Inputmodel.F_Cathetertime = item.F_Cathetertime;//置管时间
                        Inputmodel.F_BedNum = item.F_BedNum;//床号
                        Inputmodel.F_InpatientNum = item.F_InpatientNum;//住院号
                    }
                    Inputmodel.F_DealOpinions = item.F_DealOpinions;//处理意见
                    Inputmodel.F_DealType = item.F_DealType;//处理方式：立即办理，提交审核，转派部门
                    Inputmodel.F_DealResult = item.F_DealResult;//处理结果
                    Inputmodel.F_HandleBy = item.F_HandleBy;//处理人
                    Inputmodel.F_HandleTime = item.F_HandleTime.ToString();
                    //if (item.F_HandleTime != null)
                    //{
                    //    Inputmodel.F_HandleTime = ((DateTime)item.F_HandleTime).ToString("yyyy-MM-dd  hh:mm:ss");//处理时间
                    //}
                    Inputmodel.F_NotHandleReasons = item.F_NotHandleReasons;//未处理原因
                    Inputmodel.F_WorkOrderContents = item.F_WorkOrderContents;//工单内容
                    Inputmodel.F_ResponDept = item.F_ResponDept;//责任部门
                    Inputmodel.F_ResponPerson = item.F_ResponPerson;//责任人
                    Inputmodel.F_CallID = item.F_CallID;//通话记录ID
                    Inputmodel.F_IsReturnBak = item.F_IsReturnBak;//沟通情况
                   // Inputmodel.F_ReturnBakTime = item.F_ReturnBakTime;//回访时间
                    Inputmodel.F_IsTimeOut = item.F_IsTimeOut;//是否超时
                    Inputmodel.F_CreateUserID = item.F_CreateUserID;//创建人
                    Inputmodel.F_CreateUser = item.F_CreateUser;
                    Inputmodel.F_CreateTime = item.F_CreateTime;//创建时间
                    Inputmodel.F_CreateUserName = item.F_CreateUserName;
                    Inputmodel.F_IsAudit = item.F_IsAudit;
                    if (item.F_IsAudit != 0 && item.F_IsAudit != null)
                    {
                        if (item.F_AuditState == 0)
                        {
                            Inputmodel.F_AuditState = "提交审核";
                        }
                        else if (item.F_AuditState == 1)
                        {
                            Inputmodel.F_AuditState = "同意上报";
                        }
                        else if (item.F_AuditState == 2)
                        {
                            Inputmodel.F_AuditState = "驳回修改";
                        }
                    }
                    else
                    {
                        Inputmodel.F_AuditState = "";
                    }
                    Inputmodel.F_AuditUser = item.F_AuditUser;//审核人
                    Inputmodel.F_AuditTime = item.F_AuditTime;//审核时间
                    Inputmodel.F_AuditCont = item.F_AuditCont;//审核内容
                    Inputmodel.F_AppointTime = item.F_AppointTime;//派单时间
                    Inputmodel.F_Answer = item.F_Answer;//回复内容
                    Inputmodel.F_DealContents = item.F_DealContents;//处理内容
                    Inputmodel.F_File = "0";
                    //Inputmodel.F_Satisfaction = item.F_Satisfaction;//满意度
                    Inputmodel.F_FullName = item.F_FullName;
                    Inputmodel.F_IDNumber = item.F_IDNumber;
                    Inputmodel.F_ComplaintDept = item.F_ComplaintDept;
                    Inputmodel.F_ComplaintUser = item.F_ComplaintUser;

                    Inputmodel.F_ComplaintSource = item.F_ComplaintSource;

                    Inputmodel.ComplaintDept = GetDeptModel(item.F_ComplaintDept == null ? 0 : item.F_ComplaintDept);
                    Inputlist.Add(Inputmodel);
                }
                return Inputlist;
            }
            else { return null; }
        }
        /// <summary>
        /// 转派工单
        /// </summary>

        private bool AssignWO(Model.T_Sys_UserAccount nowUser, Model.T_Con_WorkOrder wokerModel, string cont, string clid = "", int clbm = 0)
        {

            string touser = ""; string tousername = "";
            int deptid = 0;string  handle = "";
            var dicvalue =new  Model.T_Sys_GongDan();
            if (wokerModel.F_type2!=null )
             dicvalue = new Bll.T_Sys_GongDan().GetModel((int )wokerModel.F_type2);
            string message = "";
            if (dicvalue!=null )
            {
                message = "\n工单类型:" + dicvalue.F_Name;
            }
            #region 获取接收人
            if (!string .IsNullOrEmpty (clid))
            {
                Model.T_Sys_UserAccount clus = userbll.GetModel(clid);
                handle = clus.F_UserCode ;
                deptid = clus.F_DeptId;
                clbm = clus.F_DeptId;
                if (clus != null)
                {
                    touser = clus.F_UserCode;
                    tousername = clus.F_UserName + "(" + clus.F_UserCode + ")";
                    msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + wokerModel.F_WorkOrderCode+ message, touser, nowUser.F_UserCode, (int)EnumSmsType.consulting
                        , 0, wokerModel.F_WorkOrderCode);
                }
            }
            else
            {
                string users = string.Empty;
                deptid = clbm;
                string sql = " and F_RoleId=(select F_RoleId from T_Sys_Role where F_RoleCode='BZ')";
                var list = userbll.GetModelList(" F_DeptId='" + clbm + "' and F_DeleteFlag=0 " + sql);
                foreach (var l in list)
                {
                    if (string.IsNullOrEmpty(users))
                    {
                        users = l.F_UserCode;
                        tousername = l.F_UserName + "(" + l.F_UserCode + ")";
                    }
                    else
                    {
                        users = users + "," + l.F_UserCode;
                        tousername = tousername + "," + l.F_UserName + "(" + l.F_UserCode + ")";
                    }
                    msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + wokerModel.F_WorkOrderCode + message, l.F_UserCode, nowUser.F_UserCode, (int)EnumSmsType.consulting
                        , 0, wokerModel.F_WorkOrderCode);
                }
                touser = users;
            }

            #endregion
            if (touser != "")
            {
                #region 工单处理
                var opt = "指派";
                int optbut = (int)EnumItemOpt.assign;
                int wostate = (int)EnumWorkOrderState.assign;//已指派待接单
                string deptname = "";
                var deptmodel = deptbll.GetModel(nowUser.F_DeptId);
                if (deptmodel != null)
                {
                    deptname = deptmodel.F_DeptName + "-";
                }
                var optcont = "";
                if (!string.IsNullOrEmpty(cont))
                    optcont = "，说明：" + cont;
                var content = deptname + nowUser.F_UserName + "(" + nowUser.F_UserCode + ")" + opt + "工单给 " + tousername + optcont;
                var itemid =logbll.AddLog(wokerModel.F_ID, wostate,(int)wokerModel.F_type1, content, (int)EnumItemType.deal, optbut, touser, clbm, nowUser.F_UserCode);
                int n = DbHelperSQL.ExecuteSql($"update T_Wo_CommonBase set F_DealDept='{clbm}',F_DealUser='{handle}' where F_WoCode='{wokerModel.F_WorkOrderCode}'");
                #endregion
                if (itemid > 0)
                {
                    wokerModel.F_State = wostate;
                    if (!string.IsNullOrEmpty(cont))
                        wokerModel.F_DealContents += cont + "；";
                    orderbll.Update(wokerModel);

                   
                    return true;
                }
                else return false;
            }
            else
                return false;

        }


        /// <summary>
        /// 审核工单
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="AuditCont"></param>
        /// <param name="IsAudit"></param>
        /// <returns></returns>
        public ActionResult GetApproval(int orderid, string AuditCont, int IsAudit = 0, int AuditState = 1)
        {
            long res = 0;
            long clbm = 3016; //行风办部门编号
            if (User != null)
            {
                Model.T_Sys_UserAccount ua = userbll.GetModel(User.F_UserId);
                Model.T_Con_WorkOrder wmodel = orderbll.GetModel(orderid);
                if (wmodel != null)
                {
                    string deptname = "";
                    var deptmodel = deptbll.GetModel(ua.F_DeptId);
                    if (deptmodel != null)
                    {
                        deptname = deptmodel.F_DeptName + "-";
                    }
                    if (IsAudit == 1)
                    {
                        if (AuditState == 1)
                        {
                            res =logbll.AddLog(wmodel.F_ID, wmodel.F_State.Value,(int)wmodel.F_type1, deptname + ua.F_UserName + "(" + ua.F_UserCode + ")" + "工单审批：已同意审批" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.reaudit, ua.F_UserCode, ua.F_DeptId, ua.F_UserCode);
                            AssignWO(User, wmodel, "", "", (int)clbm);
                            wmodel.F_State = (int)EnumWorkOrderState.assign;//待处理
                            wmodel.F_AuditState = 1;
                        }
                        if (AuditState == 2)
                        {
                            res =logbll.AddLog(wmodel.F_ID, wmodel.F_State.Value,(int)wmodel.F_type1, ua.F_UserName + "(" + ua.F_UserCode + ")" + "工单审批：未同意审批" + AuditCont, (int)EnumItemType.audit, (int)EnumItemOpt.reback, ua.F_UserCode, ua.F_DeptId, ua.F_UserCode);
                            wmodel.F_State = (int)EnumWorkOrderState.audit;//待审批
                            wmodel.F_AuditState = 2;
                        }
                        if (res > 0)
                        {
                            if (!string.IsNullOrEmpty(AuditCont))
                            wmodel.F_AuditCont += AuditCont + "；";
                            wmodel.F_IsAudit = IsAudit;
                            wmodel.F_AuditUser = ua.F_UserCode;
                            wmodel.F_AuditTime = DateTime.Now;
                            orderbll.Update(wmodel);
                            return Success("审批成功！");
                        }
                        else
                            return Error("审批失败！");
                    }

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

        }

        /// <summary>
        /// 处理工单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cont"></param>
        /// <param name="F_Files"></param>
        /// <param name="isover"></param>
        /// <returns></returns>
        public ActionResult DealWorkOrder(string WorkOrderCode, string cont, int isover=0,int isvisit=0,int communicate=-1)
        {
            if (User!=null)
            {
                if (string.IsNullOrEmpty(cont))
                    return Error("请输入内容");
 
                    Model.T_Con_WorkOrder wmodel = orderbll.GetModelByCode(WorkOrderCode);
                    if (wmodel != null)
                    {
                        if (wmodel.F_State == 10)
                            return Error("工单已处理请勿重复操作");
                        else
                        {
                            var res = DealWO(User, wmodel, cont, "", isover, isvisit, communicate);
                            if (res)
                                return Success("处理成功");
                            else
                                return Error("处理失败！");
                        }
                    }
                    else
                        return Error("工单不存在！");

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

        }


        /// <summary>
        /// 处理工单
        /// </summary>
        /// <param name="nowUser"></param>
        /// <param name="model"></param>
        /// <param name="cont"></param>
        /// <param name="F_Files"></param>
        /// <param name="isover"></param>
        /// <returns></returns>
        public bool DealWO(Model.T_Sys_UserAccount nowUser, Model.T_Con_WorkOrder model, string cont, string F_Files = "", int isover = 0, int isvisit = 0, int communicate = -1)
        {
            #region 工单处理
            var opt = "处理";
            int optbut = (int)EnumItemOpt.deal;
            int wostate = (int)EnumWorkOrderState.dealing;
            if (isover == 1)
            {
                model.F_DealResult = "已处理";//处理结果
                opt = "处理完结";
                optbut = (int)EnumItemOpt.end;
                
                 
                wostate = (int)EnumWorkOrderState.finish;
                model.F_HandleBy = nowUser.F_UserCode;
            }
            else
            {
                model.F_DealResult = "处理中";//处理结果
            }
            //if (isvisit > 0)  //1 是，0 否
                wostate = (int)EnumWorkOrderState.dealed;
            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = deptbll.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var optcont = "";
            if (!string.IsNullOrEmpty(cont))
                optcont = "，处理内容：" + cont;
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_UserCode + ")" + opt + "工单" + optcont;
            var itemid =logbll.AddLog(model.F_ID, wostate,(int)model.F_type1, content, (int)EnumItemType.deal, optbut, "", 0, nowUser.F_UserCode);
            if (itemid > 0)
            {
                #region 处理工单
                model.F_State = wostate;
                //处理内容
                if (!string.IsNullOrEmpty(model.F_DealContents))
                    model.F_DealContents += "；" + cont;
                else
                    model.F_DealContents += cont;
                model.F_HandleTime = DateTime.Now;
                model.F_IsReturnBak = communicate;
                
                model.F_IsVisit = isvisit;
                orderbll.Update(model);
              //  msg.AddInternalMessagesInfo("您提交的工单已处理完毕", "工单编号:" + model.F_WorkOrderCode , model.F_CreateUser , nowUser.F_UserCode, (int)EnumSmsType.consulting
                      //  , 0, model.F_WorkOrderCode);
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }

       


        #region  nouser
        ///// <summary>
        ///// 转派工单
        ///// </summary>
        ///// <param name="orderid">工单id</param>
        ///// <param name="cont">指派说明</param>
        ///// <param name="overtime"></param>
        ///// <param name="clbm">指派部门</param>
        ///// <param name="clid">指派人</param>
        ///// <returns></returns>
        //public ActionResult AssignWorkOrder(int orderid,string cont,int clbm=0,int clid=0)
        //{
        //    var userId =1 ;
        //    string usercode = "8000";
        //    if (userId != 0)
        //    {
        //        Model.T_Sys_UserAccount ua = userbll.GetModel(userId);
        //        Model.T_Con_WorkOrder wmodel = orderbll.GetModel(orderid);
        //        if (wmodel == null)
        //            return Error("工单不存在！");
        //        if(wmodel.F_State==1 && wmodel.F_CreateUser==ua.F_UserCode)
        //            return Error("工单已转派请勿重复操作！");
        //        if (clbm == 0 && clid == 0)
        //            return Error("请选择接收部门！");
        //        #region 判断条件
        //        //if (wmodel.F_State != 0)
        //        //{
        //        //    var modellist = itembll.GetModelList("F_WoID=" + wmodel.F_ID + " and F_IsUsed=0 order by   F_ID desc ").FirstOrDefault();
        //        //    if (modellist != null)
        //        //    {
        //        //        if (modellist.F_NextUser != ua.F_UserCode)
        //        //            return Error("非接单人不可操作此工单！");
        //        //    }
        //        //}
        //        #endregion
        //        var res = AssignWO(ua, wmodel, cont, clbm, clid);
        //        if (res)
        //            return Success("转派成功");
        //        else
        //            return Error("转派失败！");
        //    }
        //    return Error("无操作权限！");
        //}
        /// <summary>
        /// 转派工单
        /// </summary>
        /// <param name="orderid">工单id</param>
        /// <param name="cont">指派说明</param>
        /// <param name="overtime"></param>
        /// <param name="clbm">指派部门</param>
        /// <param name="clid">指派人</param>
        /// <returns></returns>
        //public ActionResult AssignWorkOrder(int orderid)
        //{
        //    if (User != null)
        //    {
        //        Model.T_Con_WorkOrder wmodel = orderbll.GetModel(orderid);
        //        if (wmodel == null)
        //            return Error("工单不存在！");
        //        if (wmodel.F_State == (int)EnumWorkOrderState.receive)
        //            return Error("工单已转派请勿重复操作！");
        //        long clbm = 3016; //行风办部门编号
        //        var res = AssignWO(User, wmodel, "",0, (int)clbm);
        //        if (res)
        //            return Success("转派成功");
        //        else
        //            return Error("转派失败！");
        //    }
        //    return Error("无操作权限！");
        //}
        /// <summary>
        /// 接单 - 确认工单
        /// </summary>
        /// <param name = "id" ></ param >
        /// < returns ></ returns >
        public ActionResult SureWorkOrder(string WorkOrderCode)
        {
            if (User != null)
            {

                Model.T_Con_WorkOrder wmodel = orderbll.GetModelByCode(WorkOrderCode);
                if (wmodel != null)
                {
                    if (wmodel.F_State != (int)EnumWorkOrderState.assign)
                        return Error("工单已接单无需重复操作");
                    var Common = new Model.T_Wo_CommonBase();
                    var CommonBase = new BLL.T_Wo_CommonBase().GetModelList($"F_WoCode='{wmodel.F_WorkOrderCode }' and F_IsDelete=0");
                    if (CommonBase != null && CommonBase.Count > 0)
                    {
                        Common = CommonBase.FirstOrDefault();
                      if (!string .IsNullOrEmpty (Common.F_DealUser))
                        {
                            if (Common.F_DealUser !=User.F_UserCode )
                                return Error("非接单人不可接单");
                        }
                        else if (Common.F_DealDept  != null && Common.F_DealDept > 0)
                        {
                            if (Common.F_DealDept != User.F_DeptId )
                                return Error("非接单部门不可接单");

                        }
                       
                    }

                    var res = OrdeReceive(User, wmodel, Common);
                    if (res)
                        return Success("接单成功");
                    else
                        return Error("接单失败");

                   
                }
                else
                    return Error("工单不存在");
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 接单
        /// </summary>
        /// <param name = "nowUser" ></ param >
        /// < param name="model"></param>
        /// <returns></returns>
        public bool OrdeReceive(Model.T_Sys_UserAccount nowUser, Model.T_Con_WorkOrder model,Model .T_Wo_CommonBase CommonBase)
        {
            #region 工单处理
            var opt = "接单";
            int optbut = (int)EnumItemOpt.receive;
            int wostate = (int)EnumWorkOrderState.receive;

            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = deptbll.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_UserCode + ")" + opt;
            var itemid = logbll.AddLog((int)model.F_ID, (int)model.F_type1, wostate, content, (int)EnumItemType.deal, optbut, nowUser.F_UserCode, 0, nowUser.F_UserCode);
            if (itemid > 0)
            {
                #region 处理工单
                model.F_State = wostate;//已接单待处理
                model.F_AcceptTime = DateTime.Now;
                model.F_HandleBy = nowUser.F_UserCode;//已接单待处理
                orderbll.Update(model);
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        #endregion nouser  nouser

        /// <summary>
        ///已完成
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult CompleteWo(int woid)
        {
            if (User != null)
            {               
                if (woid <= 0)
                    return Error("工单编号错误！");
                var omodel = orderbll.GetModel(woid);
                if (omodel != null)
                {
                    if (DealWO(User, omodel, "", "", 1))
                        return Success("操作成功！");
                    else return Error("工单操作失败！");
                }
            }
            return Error("操作失败,不存在此工单编号！");
        }

        public string GetDeptModel(int?  deptId = 0)
        {
            string sql = " 1=1 ";

            if (deptId>0)
            {
                sql += " and F_DeptId='" + deptId + "'";
            }
            else
            {
                return "";
            }
            var role = new Bll .T_Sys_Department ().GetModelList(sql).FirstOrDefault();
            string name = role.F_DeptName;

            return name;
        }
        /// <summary>
        /// 回访工单
        /// </summary>
        /// <param name="WorkOrderCode"></param>
        /// <param name="callid"></param>
        /// <param name="callResult"></param>
        /// <param name="phone"></param>
        /// <param name="result"></param>
        /// <param name="satisfaction"></param>
        /// <param name="isover"></param>
        /// <returns></returns>
        public ActionResult VisitWorkOrder(string WorkOrderCode,string callid,string callResult,string phone,string result,int satisfaction=-1
            ,int isover=0)
        {
            Model.T_Con_WorkOrder wmodel = orderbll.GetModelByCode(WorkOrderCode);
            if (wmodel!=null )
            {
                if(wmodel.F_State !=7)
                {
                    return Error("工单已回访");

                }
                Model.T_Wo_VisitResult visit = new Model.T_Wo_VisitResult();
                if (!string.IsNullOrEmpty(callid))
                {
                    var rd = new Bll.T_Call_CallRecords().GetModelByCallId(callid);
                    if (rd != null)
                    {
                        visit.F_Callid  = rd.CallRecordsId;
                    }
                }
                visit.F_CallResult = callResult;
                visit.F_CreateTime = DateTime.Now;
                visit.F_CreateUser = User.F_UserCode;
                visit.F_IsDelete = 0;
                visit.F_Phone = phone;
                visit.F_Result = result;
                visit.F_Satisfaction = satisfaction;
                visit.F_WorkOrderCode = wmodel.F_WorkOrderCode;
                int n = new BLL.T_Wo_VisitResult().Add(visit);
                if (n > 0)
                {
                    wmodel.F_Satisfaction = satisfaction;
                    wmodel.F_ReturnBakTime = DateTime.Now;
                    if (isover > 0)
                        wmodel.F_State = 10;
                    string satisfie = "";
                    if (satisfaction > -1)
                    {
                        satisfie = "，结果：满意";
                        if (satisfaction == 0)
                            satisfie = "，结果：满意";
                        else if (satisfaction == 1)
                            satisfie = "，结果：基本满意";
                        else
                            satisfie = "，结果：不满意";
                    }
                    var itemid = logbll.AddLog((int)wmodel.F_ID, 
                        (int)wmodel.F_type1, 7, "", (int)EnumItemType.deal, 13, User.F_UserName + "(" + User.F_UserCode + ")" + "回访工单"+ satisfie
                        , 0, User.F_UserCode);
                     if(new Bll .T_Con_WorkOrder().Update (wmodel))
                    {
                        return Success("回访成功");
                    }
                     else
                        return Error("回访失败");
                }
                else
                    return Error("回访失败");
            }
            else
            {
                return Error("工单不存在");
            }
        }

        /// <summary>
        /// 撤回工单
        /// </summary>
        /// <param name="WorkOrderCode"></param>
        /// <returns></returns>
        public ActionResult WithdrawWorkOrder(string WorkOrderCode)
        {
            if (User != null)
            {

                Model.T_Con_WorkOrder wmodel = orderbll.GetModelByCode(WorkOrderCode);
                if (wmodel != null)
                {
                    if (wmodel.F_State != (int)EnumWorkOrderState.assign)
                        return Error("工单已接单不能撤回");
                    var Common = new Model.T_Wo_CommonBase();
                    var opt = "撤单";
                    int optbut = (int)EnumItemOpt.reback;
                    int wostate = (int)EnumWorkOrderState.neworder;

                    #region 读取当前登录人部门
                    string deptname = "";
                    var deptmodel = deptbll.GetModel(User .F_DeptId);
                    if (deptmodel != null)
                    {
                        deptname = deptmodel.F_DeptName + "-";
                    }
                    #endregion
                    var content = deptname + User.F_UserName + "(" + User.F_UserCode + ")" + opt;
                    var itemid = logbll.AddLog((int)wmodel.F_ID, (int)wmodel.F_type1, wostate, content, (int)EnumItemType.deal, optbut, "", 0, User .F_UserCode);
                    if (itemid > 0)
                    {
                        #region 处理工单
                        wmodel.F_State = wostate;
                        #endregion
                        if (orderbll.Update(wmodel))
                        {
                            int n = DbHelperSQL.ExecuteSql($"update T_Wo_CommonBase set F_DealDept='',F_DealUser='' where F_WoCode='{wmodel.F_WorkOrderCode}'");
                            return Success("撤单成功");
                        }
                           
                    }
                    else
                        return Error("撤单失败");


                }
                else
                    return Error("工单不存在");
            }
            return Error("无操作权限！");
        }


        /// <summary>
        /// 退回工单
        /// </summary>
        /// <param name="WorkOrderCode"></param>
        /// <returns></returns>
        public ActionResult BackWorkOrder(string WorkOrderCode,string reason,int key,string value)
        {
            if (User != null)
            {

                Model.T_Con_WorkOrder wmodel = orderbll.GetModelByCode (WorkOrderCode);
                if (wmodel != null)
                {
                    if (wmodel.F_State != (int)EnumWorkOrderState.assign)
                        return Error("工单已接单不能退回");
                    var Common = new Model.T_Wo_CommonBase();
                    var CommonBase = new BLL.T_Wo_CommonBase().GetModelList($"F_WoCode='{wmodel.F_WorkOrderCode }' and F_IsDelete=0");
                    if (CommonBase != null && CommonBase.Count > 0)
                    {
                        Common = CommonBase.FirstOrDefault();
                        if (!string.IsNullOrEmpty(Common.F_DealUser))
                        {
                            if (Common.F_DealUser != User.F_UserCode )
                                return Error("非接单人不可退单");
                        }
                        else if (Common.F_DealDept != null && Common.F_DealDept > 0)
                        {
                            if (Common.F_DealDept != User.F_DeptId)
                                return Error("非接单部门不可退单");

                        }

                    }

                    var res = BackWO(User, wmodel, reason,key,value);
                    if (res)
                        return Success("退单成功");
                    else
                        return Error("退单失败");


                }
                else
                    return Error("工单不存在");
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 退回工单
        /// </summary>
        public bool BackWO(Model.T_Sys_UserAccount nowUser, Model.T_Con_WorkOrder model,string reason,int key, string value)
        {
            #region 工单处理
            var opt = "退单";
            int optbut = (int)EnumItemOpt.reback;
            int wostate = (int)EnumWorkOrderState.reback;

            #region 读取当前登录人部门
            string deptname = "";
            var deptmodel = deptbll.GetModel(nowUser.F_DeptId);
            if (deptmodel != null)
            {
                deptname = deptmodel.F_DeptName + "-";
            }
            #endregion
            string reasonmessage = "";
            if (!string .IsNullOrEmpty (reason))
            {
                reasonmessage = ",原因:" + reason;
            }
            var content = deptname + nowUser.F_UserName + "(" + nowUser.F_UserCode + ")" + opt+ reasonmessage;
            var itemid = logbll.AddLogAboutKey((int)model.F_ID, (int)model.F_type1, wostate, content, (int)EnumItemType.deal, optbut, "", 0, nowUser.F_UserCode,key,value,reason);
            if (itemid > 0)
            {
                #region 处理工单
                model.F_State = wostate;//已退回
                orderbll.Update(model);
                int n = DbHelperSQL.ExecuteSql($"update T_Wo_CommonBase set F_DealDept='',F_DealUser='' where F_WoCode='{model.F_WorkOrderCode}'");
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }
        private class ItemListLog
        {
            /// <summary>
            /// 工单记录ID
            /// </summary>
            public long F_ID
            {
                set;
                get;
            }
            /// <summary>
            /// 工单ID
            /// </summary>
            public string F_WoID
            {
                set;
                get;
            }
            /// <summary>
            /// 工单状态
            /// </summary>
            public int? F_WoState
            {
                set;
                get;
            }
            /// <summary>
            /// 记录类型 1工单处理，2工单催办
            /// </summary>
            public int? F_ItemType
            {
                set;
                get;
            }
            /// <summary>
            /// 操作类型
            /// </summary>
            public int? F_OptType
            {
                set;
                get;
            }
            /// <summary>
            /// 操作内容
            /// </summary>
            public string F_OptContent
            {
                set;
                get;
            }
            /// <summary>
            /// 下一步操作人
            /// </summary>
            public string F_NextUser
            {
                set;
                get;
            }
            /// <summary>
            /// 下一步操作部门
            /// </summary>
            public string F_NextDept
            {
                set;
                get;
            }
            /// <summary>
            /// 是否在用，0是 1否
            /// </summary>
            public int? F_IsUsed
            {
                set;
                get;
            }
            /// <summary>
            /// 时限
            /// </summary>
            public string F_LimitTime
            {
                set;
                get;
            }
            /// <summary>
            /// 是否短信提醒
            /// </summary>
            public int? F_IsSMS
            {
                set;
                get;
            }
            /// <summary>
            /// 短信提醒人
            /// </summary>
            public string F_SMSToUser
            {
                set;
                get;
            }
            /// <summary>
            /// 短信提醒电话
            /// </summary>
            public string F_SMSToPhone
            {
                set;
                get;
            }
            /// <summary>
            /// 短信提醒内容
            /// </summary>
            public string F_SMSContent
            {
                set;
                get;
            }
            /// <summary>
            /// 创建人
            /// </summary>
            public string F_CreateUser
            {
                set;
                get;
            }
            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime? F_CreateTime
            {
                set;
                get;
            }
        }


    }
}