using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Model;
using RMYY_CallCenter_Api.Models;
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.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers
{
    public class FaultRepairController : BaseController
    {
        private Bll.T_Sys_GroupClass gcBll = new Bll.T_Sys_GroupClass();

        private BLL.T_IntegratedScheduling_Base basescheBll = new BLL.T_IntegratedScheduling_Base();
        private BLL.T_FaultRepair_Base baseBll = new BLL.T_FaultRepair_Base();
        private BLL.T_FaultRepair_Evaluate evaBll = new BLL.T_FaultRepair_Evaluate();
        private BLL.T_FaultRepair_OperationLog logBll = new BLL.T_FaultRepair_OperationLog();
        private BLL.T_FaultRepair_Process dealBll = new BLL.T_FaultRepair_Process();
        Bll.T_Sys_GongDan gdbll = new Bll.T_Sys_GongDan();
        private Bll.T_Sys_SystemConfig configBll = new Bll.T_Sys_SystemConfig();
        private Bll.T_Sys_DictionaryValue dictionaryValueBLL = new Bll.T_Sys_DictionaryValue();
        private Bll.T_Sys_Department departmentBLL = new Bll.T_Sys_Department();

        private Bll.T_InvolvedEquip_RepairProcess equipbll = new Bll.T_InvolvedEquip_RepairProcess();
        private BLL.T_Wo_CommonBase cbbll = new BLL.T_Wo_CommonBase();
        private Bll.T_Con_WorkOrder cwbll = new Bll.T_Con_WorkOrder();
        private Bll.AddLogBll Addlogbll = new Bll.AddLogBll();


        private BLL.T_IntegratedScheduling_Base isbll = new BLL.T_IntegratedScheduling_Base();

        private static InternalMessagesController msg = new InternalMessagesController();

        private static SchedulingController schcon = new SchedulingController();

        #region 获取工单详情相关的接口
        public DataTable GetFileData(string ids,string prefix)
        {
            DataTable dt = DbHelperSQL.Query("select * from T_Sys_Accessories WITH(NOLOCK) where F_FileId in (" + ids + ")").Tables[0];

            foreach (DataRow dr in dt.Rows)
            {
                if (FileHelper.Exists(FileHelper.GetPath() + dr["F_FileUrl"].ToString()))
                {
                    dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
                }
                else
                {
                    string url =HomeController . Upload(dr["F_FileUrl"].ToString(), dr["F_FileName"].ToString(), "/" + dr["F_FileUrl"].ToString().Replace(dr["F_FileName"].ToString(), ""));
                    if (url == "1")
                        dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
                    else
                        dr["F_FileUrl"] = url;
                }
            }

            return dt;
        }

        /// <summary>
        /// 工单详情获取设备信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public DataTable GetEquipsData(string ids)
        {
            DataTable dt = DbHelperSQL.Query("select * from T_InvolvedEquip_RepairProcess WITH(NOLOCK) where F_ID in (SELECT COL FROM DBO.SplitToNvarchar('" + ids + "',','))").Tables[0];

            return dt;
        }


        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult UploadFile()
        {
            #region 多个上传
            HttpFileCollectionBase files = Request.Files;
            if (files.Count > 0)
            {
                List<Model.T_Sys_Accessories> acs = new List<Model.T_Sys_Accessories>();
                string path = "/Upload/Files/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFileBase file = files[i];
                    string name = FileHelper.Upload(file, path);

                    Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                    model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                    model_T_Sys_Accessories.F_FileName = name;//附件名称
                    model_T_Sys_Accessories.F_FileType = Path.GetExtension(file.FileName);//附件类型
                    model_T_Sys_Accessories.F_FileUrl = path + name;//附件地址
                    model_T_Sys_Accessories.F_Size = file.ContentLength;
                    model_T_Sys_Accessories.F_UserCode = User.F_UserCode;//上传人  
                    int id = new Bll.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    model_T_Sys_Accessories.F_FileId = id;
                    acs.Add(model_T_Sys_Accessories);
                }
                return Success("成功", acs);
            }
            else
            {
                return Error("请选择要上传的文件");
            }
            #endregion

        }
        private string fileurlpath = ConfigHelper.GetValue("fileurlpath");

        public ActionResult GetWorkOrder()
        {

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

            string strworkorderid = HttpUtility.UrlDecode(RequestString.GetQueryString("WorkOrderCode"));
            Model.T_FaultRepair_Base model = baseBll.GetModel(strworkorderid);
            int type = RequestString.GetInt("type", 0);//0基本信息1处理结果2协作工单3工单流程4维修记录5评价
            if (!string.IsNullOrEmpty(strworkorderid))
            {
                switch (type)
                {

                    case 6:
                        //string sqlfx = " select top 1 F_ReturnReason from T_FaultRepair_Process where F_ReturnReason is not null and  F_WorkOrderCode='" + strworkorderid + "' order by F_ProcessingTime desc";
                        int operationtype =(int) EnumOperatorType.submitreturn;
                        string sqlfx = "  select top 1  F_LogContent from T_FaultRepair_OperationLog where F_WorkOrderCode= '" + strworkorderid + "'and F_OperationType='"+ operationtype + "' order by F_OperationTime desc";

                         

                        object dtfx = DbHelperSQL.GetSingle(sqlfx);
                        if (dtfx != null && !string.IsNullOrEmpty(dtfx.ToString()))
                        {
                            string reason = dtfx.ToString();
                            string strreason = reason.Substring(9, reason.Length-9);

                            return Success("是返修", strreason);
                        }

                        return Success("不是返修");

                    case 0:
                        //基本信息
                        #region
                        string sql = "select *,[dbo].[GetUserName](F_Applicant) applicantname ,(case when F_Endtime= null then '' else dbo.GetConvertSecond(DATEDIFF(s,F_accepttime,F_endtime)) end) SpendTime,[dbo].[GetPhoneByUserCode](F_Maintenancer) MaintenancerPhone,[dbo].[GetUserName](F_Maintenancer) MaintenancerName, (select F_urgecount from [T_Wo_CommonBase] where F_WoCode='" + strworkorderid + "') F_UrgeCount from T_FaultRepair_Base where F_WorkOrderCode='" + strworkorderid + "'";
                        DataTable dtbase = DbHelperSQL.Query(sql).Tables[0];
                        dtbase.Columns.Add("FileUrl", typeof(object));
                        dtbase.Columns.Add("StateName");
                        dtbase.Columns.Add("TypeName");

                        dtbase.Columns.Add("GapTime");



                        foreach (DataRow dr in dtbase.Rows)
                        {
                            dr["TypeName"] = "故障报修";
                            if (!string.IsNullOrEmpty(fileurlpath) &&!string.IsNullOrEmpty(dr["F_File"].ToString()))
                            {
                                dr["FileUrl"] = GetFileData(dr["F_File"].ToString(), fileurlpath);
                            }

                            dr["StateName"] = GetWorkOrderStateStr(User.F_RoleCode, Convert.ToInt32(dr["F_WorkOrderState"]));

                            #region 超时时限处理
                            if (!string.IsNullOrEmpty(dr["F_Deadline"].ToString()))
                            {
                                DateTime deadline = Convert.ToDateTime(dr["F_Deadline"]);
                                DateTime thisDate = DateTime.Now;
                                if (dr["F_Endtime"] != null && !string.IsNullOrEmpty(dr["F_Endtime"].ToString()))
                                {
                                    thisDate = Convert.ToDateTime(dr["F_Endtime"].ToString());

                                    if (thisDate < deadline)
                                    {
                                        dr["GapTime"] = "-";
                                    }
                                }

                                if (dr["GapTime"].ToString() != "-")
                                {
                                    TimeSpan ts = deadline.Subtract(thisDate);
                                    double tss = double.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
                                    if (tss < 0) { tss = -tss; }
                                    string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);

                                    if (deadline > thisDate)
                                    {

                                        dr["GapTime"] = "剩余" + gshsj;
                                    }
                                    else
                                    {

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


                            }
                            else
                            {
                                dr["GapTime"] = "-";
                            }
                            #endregion
                        }


                        return Success("获取成功", dtbase);
                    #endregion
                    case 1://处理结果
                        #region
                        string sqlcl = "select top 1 *,[dbo].[GetUserName](F_Maintenancer) username,[dbo].[GetPhoneByUserCode](F_Maintenancer) usertel ,dbo.GetDictionaryName(F_ExceptionType) F_ExceptionTypeName ,case F_DealType when 0 then '正常完成' when 1 then '异常完成' when 2 then '自行解决' else '' end  dealtype  from T_FaultRepair_Process where F_WorkOrderCode='" + strworkorderid + "' " + " order by F_ProcessingTime desc";
                        DataTable dtcl = DbHelperSQL.Query(sqlcl).Tables[0];

                        dtcl.Columns.Add("FileUrl", typeof(object));

                        dtcl.Columns.Add("Equips", typeof(object));


                        foreach (DataRow dr in dtcl.Rows)
                        {
                            if (!string .IsNullOrEmpty (fileurlpath) && !string.IsNullOrEmpty(dr["F_File"].ToString()))
                            {
                                dr["FileUrl"] = GetFileData(dr["F_File"].ToString(), fileurlpath);
                            }
                            if (!string.IsNullOrEmpty(dr["F_EquipDetail"].ToString()))
                            {
                                dr["Equips"] = GetEquipsData(dr["F_EquipDetail"].ToString());

                            }


                        }
                        return Success("获取处理结果成功", dtcl);
                    #endregion
                    case 2://协作工单

                        string internalsql = " select     F_WorkOrderCode,F_Content,F_MaintenanceDept,F_CreateTime,F_WorkOrderState from T_FaultRepair_Base where F_WorkOrderCode in " +
                        "(select col from [dbo].[SplitToNvarchar]('" + model.F_InternalWorkOrderCode + "',',' )) ";

                        DataTable internaldt = DbHelperSQL.Query(internalsql).Tables[0];



                        string externalsql = " select  F_WorkOrderCode,F_Content,F_MaintenanceDept,F_CreateTime,F_WorkOrderState from T_FaultRepair_Base where F_WorkOrderCode in " +
                       "(select col from [dbo].[SplitToNvarchar]('" + model.F_ExternalWorkOrderCode + "',',' )) ";

                        DataTable externaldt = DbHelperSQL.Query(externalsql).Tables[0];



                        if (internaldt != null && internaldt.Rows.Count > 0)
                        {
                            internaldt.Columns.Add("StateName", typeof(String));
                            internaldt.Columns.Add("Mode", typeof(String));

                            foreach (DataRow item in internaldt.Rows)
                            {
                                if (Convert.ToInt32(item["F_WorkOrderState"]) < 3 || Convert.ToInt32(item["F_WorkOrderState"]) == 6 || Convert.ToInt32(item["F_WorkOrderState"]) == 7)
                                {
                                    item["StateName"] = "未完成";
                                }
                                else
                                {
                                    item["StateName"] = "已完成";
                                }
                                item["Mode"] = "内部协作";
                            }
                        }

                        if (externaldt != null && externaldt.Rows.Count > 0)
                        {
                            externaldt.Columns.Add("StateName", typeof(String));
                            externaldt.Columns.Add("Mode", typeof(String));
                            foreach (DataRow item in externaldt.Rows)
                            {
                                if (Convert.ToInt32(item["F_WorkOrderState"]) < 3 || Convert.ToInt32(item["F_WorkOrderState"]) == 6 || Convert.ToInt32(item["F_WorkOrderState"]) == 7)
                                {
                                    item["StateName"] = "未完成";
                                }
                                else
                                {
                                    item["StateName"] = "已完成";
                                }
                                item["Mode"] = "外部协作";
                            }
                        }
                        DataTable dtt = new DataTable();
                        dtt.Columns.Add("F_WorkOrderCode", typeof(String));
                        dtt.Columns.Add("F_Content", typeof(String));
                        dtt.Columns.Add("F_MaintenanceDept", typeof(String));

                        dtt.Columns.Add("F_WorkOrderState", typeof(String));


                        dtt.Columns.Add("F_CreateTime", typeof(DateTime));
                        dtt.Columns.Add("StateName", typeof(String));
                        dtt.Columns.Add("Mode", typeof(String));
                        if (internaldt != null && internaldt.Rows.Count > 0)
                        {
                            foreach (DataRow row in internaldt.Rows)
                            {
                                dtt.ImportRow(row);
                            }
                        }
                        if (externaldt != null && externaldt.Rows.Count > 0)
                        {
                            foreach (DataRow row in externaldt.Rows)
                            {
                                dtt.ImportRow(row);
                            }
                        }

                        var obj3 = new
                        {
                            data = dtt,



                        };
                        return Success("获取协作工单成功", obj3);


                    case 3://工单流程
                        var sqllog = "select *,[dbo].[GetUserNameUserCode](F_Operator) username from T_FaultRepair_OperationLog where F_WorkOrderCode = '" + strworkorderid + "' " + " order by F_OperationId desc";

                        DataTable dtlog = DbHelperSQL.Query(sqllog).Tables[0];

                        return Success("获取工单流程成功", dtlog);




                    case 4://维修记录
                        string sqlcl2 = "select *,[dbo].[GetUserName](F_Maintenancer) username,[dbo].[GetPhoneByUserCode](F_Maintenancer) usertel,(case F_DealType when 0 then '正常完成' when 1 then '异常完成' when 2 then '自行解决' else '' end ) dealtype  from T_FaultRepair_Process where F_WorkOrderCode='" + strworkorderid + "' order by F_ProcessingTime desc";
                        DataTable dtcl2 = DbHelperSQL.Query(sqlcl2).Tables[0];


                        dtcl2.Columns.Add("Equips", typeof(object));
                        dtcl2.Columns.Add("FileUrl", typeof(object));


                        foreach (DataRow dr in dtcl2.Rows)
                        {
                            if ( !string .IsNullOrEmpty (fileurlpath )&& !string.IsNullOrEmpty(dr["F_File"].ToString()))
                            {
                                dr["FileUrl"] = GetFileData(dr["F_File"].ToString(), fileurlpath);
                            }
                            if (!string.IsNullOrEmpty(dr["F_EquipDetail"].ToString()))
                            {
                                dr["Equips"] = GetEquipsData(dr["F_EquipDetail"].ToString());

                            }
                        }


                        return Success("获取处理结果成功", dtcl2);

                    case 5://评价
                        string sqle = "select top 1 * from T_FaultRepair_Evaluate where F_WorkOrderCode='" + strworkorderid + "'" + " order by F_EvaluationTime desc";
                        DataTable dte = DbHelperSQL.Query(sqle).Tables[0];

                        return Success("获取处理结果成功", dte);
                }

            }

            return Error("没传参数");

        }

        public static string GetWorkOrderStateStr(string userrole, int state)
        {
            List<int> typeIdArray = null;
            typeIdArray = new List<int> { -1, 0, 1, 2, 3, 4, 5, 6,7 };
            List<string> strArr = null;

            switch (userrole)
            {
                case "DDZX":
                    strArr = new List<string> { "-", "待派单", "待查收", "待完成", "已处理", "异常完结", "已完结", "待完成","确认耗材中" };
                    break;
                case "GLY":
                    strArr = new List<string> { "-", "待派单", "待查收", "待完成", "已处理", "异常完结", "已完结", "待完成", "确认耗材中" };
                    break;

                case "WXY":
                    strArr = new List<string> { "-", "待接单", "待接单", "待完成", "已完成", "已完成", "已完成", "待完成", "确认耗材中" };
                    break;
                //报修人
                default:
                    strArr = new List<string> { "待提交", "待接单", "待接单", "已接单", "待评价", "已完成", "已完成", "待完成", "确认耗材中" };
                    break;
            }
            int index = typeIdArray.IndexOf(state);

            if (index < 0)
            {
                return "";
            }


            return strArr[index];

        }


        #endregion

        /// <summary>
        /// 获取该当前时间下，该部门的所有值班人员 
        /// </summary>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public List<T_Sys_GroupClass> GetWorkUser(int deptid=0)
        {
            List<T_Sys_GroupClass> worklist = new List<T_Sys_GroupClass>();
            if (deptid == 0)
            {
                return worklist;
            }

            var class1 = new Bll.T_Sys_Class().GetModelList("F_IsDelete=0 and  F_DeptId='" + deptid + "'  and F_InTime<=convert(varchar(10),getdate(),108)" +
            "and F_OutTime>=convert(varchar(10),getdate(),108) ");

            if (class1 != null && class1.Count > 0)
            {
                //获取值班人员
                worklist = new Bll.T_Sys_GroupClass().GetModelList($"F_IsDelete=0 and F_ClassCode in(" +
                    $"{string.Join(",", class1.Select(x => x.F_Id))})  and datediff(day , F_Date , getdate())= 0 " +
                      "  order by F_Id asc");

              
            }
            return worklist;
        }



        //添加工单
        /// <summary>
        ///添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult AddFaultRepairWorkOrder(T_FaultRepairBaseinput input)
        {
            Model.T_FaultRepair_Base model = new Model.T_FaultRepair_Base();
            model.F_Applicant = input.Applicant;

            if (string.IsNullOrEmpty(input.ApplicationDept))
            {
                return Error("申请科室是必填");
            }
            model.F_ApplicationDept = input.ApplicationDept.Trim();
            model.F_Phone = input.Phone;
            model.F_Applicantsphone = input.Applicantsphone;
            if (string.IsNullOrEmpty(input.WorkOrderCategory))
            {
                return Error("工单类别是必填");
            }
            model.F_WorkOrderCategory = input.WorkOrderCategory.Trim();
            model.F_Content = input.Content;
            model.F_PlaceOfRepair = input.PlaceOfRepair;
            model.F_File = input.File;
            model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号
            model.F_EmergencyTypes = input.EmergencyTypes;
            model.F_DeviceEncode = input.DeviceEncode;
            string message = "";
            var dicvalue = new Model.T_Sys_GongDan();
            dicvalue = new Bll.T_Sys_GongDan().GetModel(Convert.ToInt32(model.F_WorkOrderCategory));
            if (dicvalue != null)
            {
                message = "\n工单类型:故障报修/" + dicvalue.F_Name;
            }
            if (input.IsEnd == 1)
            {
                model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.finish;
                model.F_MaintenanceDept = User.F_DeptId.ToString();
                model.F_Maintenancer = User.F_UserCode;
                model.F_Endtime = DateTime.Now;
                model.F_Deadline = DateTime.Now;
            }

            else if (!string.IsNullOrEmpty(input.MaintenanceDept))
            {
                model.F_MaintenanceDept = input.MaintenanceDept;
                if (!string.IsNullOrEmpty(input.Maintenancer))
                {
                    model.F_Maintenancer = input.Maintenancer;
                    model.F_AssignTime = DateTime.Now;
                    model.F_AssignUser = User.F_UserCode;
                    List<Model.T_Sys_GongDan> listgd = gdbll.GetModelList(" F_GDId='" + model.F_WorkOrderCategory + "'");
                    double timeout = listgd.First().F_TimeOut;
                    model.F_Deadline = DateTime.Now.AddHours(timeout);
                   

                    msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + model.F_WorkOrderCode + message, model.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
                       , 0, model.F_WorkOrderCode);
                }
                else
                {
                    var user = GetBeOnDuty(input.MaintenanceDept);
                    if (user != null && user.Count > 1)
                    {
                        model.F_Maintenancer = user[0];
                        input.Maintenancer = user[0];
                        model.F_AssignTime = DateTime.Now;
                        model.F_AssignUser = User.F_UserCode;
                        List<Model.T_Sys_GongDan> listgd = gdbll.GetModelList(" F_GDId='" + model.F_WorkOrderCategory + "'");
                        double timeout = listgd.First().F_TimeOut;
                        model.F_Deadline = DateTime.Now.AddHours(timeout);

                        msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + model.F_WorkOrderCode + message, model.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
                      , 0, model.F_WorkOrderCode);
                    }
                    else
                    {
                        return Error("请选择指派人员");
                    }
                }
                model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;




            }
            else
            {
                model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.neworder;
            }

            model.F_CreateTime = DateTime.Now;
            model.F_CreateUser = User.F_UserCode;
            model.F_CreateUserDept = User.F_DeptId.ToString();

            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 = 3000;
                    new Bll.T_Call_LeaveRecord().Update(ld);
                    model.F_LeaveRecordId = input.LeaveRecordId;
                }
            }



            //if (input.CallRecordsId!=null && input.CallRecordsId>0)
            //{
            //    var rd = new Bll.T_Call_CallRecords().GetModelByRecordId(input.CallRecordsId.ToString());
            //    if (rd != null)
            //    {
            //        model.F_CallId = rd.CallId;
            //        rd.WorkOrderId = model.F_WorkOrderCode;//.F_WorkOrderId;
            //        rd.IsExitWorkOrder = true;
            //        new Bll.T_Call_CallRecords().Update(rd);
            //        model.F_CallRecordId = rd.CallRecordsId;
            //    }
            //}
            //else 
            if (!string.IsNullOrEmpty(input.CallId))
            {
                model.F_CallId = input.CallId;
                var rd = new Bll.T_Call_CallRecords().GetModelByCallId(input.CallId);
                if (rd != null)
                {
                    rd.WorkOrderId = model.F_WorkOrderCode;//.F_WorkOrderId;
                    rd.IsExitWorkOrder = true;
                    new Bll.T_Call_CallRecords().Update(rd);

                    model.F_CallRecordId = rd.CallRecordsId;
                }
            }
            model.F_ReplayCount = 0;
            int returnid = baseBll.Add(model);
            if (User.F_RoleCode != "DDZX" && model.F_WorkOrderState == 0)
            {
                //新工单提醒发给调度中心值班的人
                // 根据排班信息 获取当前调度中心值班的人
              List<string>   touserlist= GetDDZXBeOnDuty();

                if(touserlist!=null && touserlist.Count>0)

                    foreach (var item in touserlist)
                    {
                        msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + model.F_WorkOrderCode + message, item, User.F_UserCode, EnumSmsType.repair
                                              , 0, model.F_WorkOrderCode);
                    }
                    
                 

            }

            if (returnid > 0)
            {
                AddAddlog(model.F_WorkOrderCode);

                if (input.IsEnd != 1&&!string.IsNullOrEmpty(input.MaintenanceDept))
                {
                    AddAssignlog(model.F_WorkOrderCode, input.MaintenanceDept, input.Maintenancer);

                }
                if (input.IsEnd == 1)
                {
                    AddOperatorLog("完结了工单", (int)EnumOperatorType.dealed, model.F_WorkOrderCode);
                }
                return Success("添加成功！", returnid);
            }
            else return Error("添加失败！");

        }

        /// <summary>
        /// 获取调度中心值班的人，有新工单给值班人员发消息
        /// </summary>
        /// <returns></returns>
        private List<string>   GetDDZXBeOnDuty()
        {
            List<string> userlist = new List<string>();
        

            var GroupClass = new Bll.T_Sys_GroupClass().GetModelList("F_IsDelete=0   and datediff(day , F_Date , getdate())= 0 " +
                       "and F_DeptId= ( select F_DeptId from T_Sys_Department where F_deptcode='ZHDDZX')  order by F_Id asc");
            if (GroupClass != null && GroupClass.Count > 0)
            {
                userlist = GroupClass.Select(x => x.F_UserCode).ToList();
                   
            }
            return userlist;


        }



        #region 调度中心相关的操作 转派  编辑 删除 退回到提交人 撤回 
        /// <summary>
        ///编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult UpdateFaultRepairWorkOrder(T_FaultRepairBaseinput input)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(input.WorkOrderCode);


            model.F_Applicant = input.Applicant;
            model.F_ApplicationDept = input.ApplicationDept;
            model.F_Phone = input.Phone;
            model.F_Applicantsphone = input.Applicantsphone;
            model.F_WorkOrderCategory = input.WorkOrderCategory;
            model.F_Content = input.Content;
            model.F_PlaceOfRepair = input.PlaceOfRepair;
            model.F_File = input.File;
            model.F_EmergencyTypes = input.EmergencyTypes;
            //  bool addassignlog = false;

            //综合保障中心没有直接结束的按钮
            #region  综合保障中心 编辑时 没有转派的操作，只修改基础的信息
            //if (input.IsEnd == 1)
            //{
            //    model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.finish;
            //    model.F_MaintenanceDept = User.F_DeptId.ToString();
            //    model.F_Endtime = DateTime.Now;
            //    model.F_Maintenancer = User.F_UserCode;
            //}

            //else if (!string.IsNullOrEmpty(input.MaintenanceDept))
            //{
            //    if (   string.IsNullOrEmpty(model.F_MaintenanceDept))  
            //    {
            //        model.F_AssignTime = DateTime.Now;
            //        model.F_AssignUser = User.F_UserCode;
            //        List<Model.T_Sys_GongDan> listgd = gdbll.GetModelList(" F_GDId='" + model.F_WorkOrderCategory + "'");
            //        int timeout = listgd.First().F_TimeOut;
            //        model.F_Deadline = DateTime.Now.AddHours(timeout);
            //        model.F_MaintenanceDept = input.MaintenanceDept;
            //        if (!string .IsNullOrEmpty(input.Maintenancer))
            //        model.F_Maintenancer = input.Maintenancer;
            //        else
            //        {
            //            var user = GetBeOnDuty(input.MaintenanceDept);
            //            if (user != null && user.Count > 1)
            //            {
            //                model.F_Maintenancer = user[0];
            //            }
            //            else
            //            {
            //                return Error("请选择指派人员");
            //            }
            //        }
            //        model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;
            //        addassignlog = true;
            //    }

            //}
            //else
            //{
            //    model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.neworder;
            //}


            #endregion


            model.F_UpdateTime = DateTime.Now;


            if (baseBll.Update(model))
            {
                //if (addassignlog)
                //{
                //    AddAssignlog(model.F_WorkOrderCode, input.MaintenanceDept,  input.Maintenancer);
                //}
                //if (input.IsEnd == 1)
                //{
                //    AddOperatorLog("完结了工单", (int)EnumOperatorType.dealed, model.F_WorkOrderCode);
                //}

                AddOperatorLog(User.F_UserName + "编辑了工单", (int)EnumOperatorType.update, model.F_WorkOrderCode);

                return Success("编辑成功！");
            }
            else return Error("编辑失败！");

        }

        //调度中心转派
        public ActionResult DDZXTransfer(string WorkOrderCode, string ToUserCode, string ToDept)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(WorkOrderCode);
            if (model != null)// && !string.IsNullOrEmpty(ToUserCode) && !string.IsNullOrEmpty(ToDept))
            {
                string mes = "";
                var dicvalue = new Model.T_Sys_GongDan();
                dicvalue = new Bll.T_Sys_GongDan().GetModel(Convert.ToInt32(model.F_WorkOrderCategory));
                if (dicvalue != null)
                {
                    mes = "\n工单类型:故障报修/" + dicvalue.F_Name;
                }

                model.F_AssignUser = User.F_UserCode;
                model.F_AssignTime = DateTime.Now;

                List<Model.T_Sys_GongDan> listgd = gdbll.GetModelList(" F_GDId='" + model.F_WorkOrderCategory + "'");
                double timeout = listgd.First().F_TimeOut;
                model.F_Deadline = DateTime.Now.AddHours(timeout);
                string message = "";

                //当工单没有选择指派部门的时候，当前工单类型shezhi指派部门，该工单默认到这个指派的部门
                if (string.IsNullOrEmpty(ToDept) || ToDept == "0")
                {
                    //根据工单类别判断 是否有指派部门
                    List<Model.T_Sys_GongDan> gd = gdbll.GetModelList(" F_GDId='" + model.F_WorkOrderCategory + "'");
                    int deptid = listgd.First().F_AutoDept != null ? listgd.First().F_AutoDept.Value : 0;
                    if (deptid == 0)
                    {
                        return Error("当前工单类型没有设置指派部门，请前往设置或者选择指派部门");
                    }
                    else
                        ToDept = deptid.ToString();
                }

                if (!string.IsNullOrEmpty(ToUserCode))
                {
                    model.F_Maintenancer = ToUserCode;
                    message = "转派工单给" + GetDeptModel(ToDept) + "部门" + GetUserModel(ToUserCode);
                    msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + model.F_WorkOrderCode + mes, model.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
                   , 0, model.F_WorkOrderCode);
                }
                else
                {




                    //部门下没有人员不可进行转派
                    var usercount = new Bll.T_Sys_UserAccount().GetModelList("F_DeptId='" + ToDept + "' and F_DeleteFlag=0 ");
                    if (usercount == null || usercount.Count == 0)
                    {
                        return Error("当前部门没有人员 ，不可进行转派");
                    }


                    var user = GetBeOnDuty(ToDept);
                    if (user != null && user.Count > 1)
                    {
                        model.F_Maintenancer = user[0];
                        message = "转派工单给" + GetDeptModel(ToDept) + "部门" + GetUserModel(user[0]);
                        msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + model.F_WorkOrderCode + mes, model.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
                   , 0, model.F_WorkOrderCode);

                    }
                    else
                    {
                        return Error("请选择指派人员");
                    }
                }
                model.F_MaintenanceDept = ToDept;
                model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;


                model.F_UpdateTime = DateTime.Now;
                AddOperatorLog(message, (int)EnumOperatorType.assign, WorkOrderCode);

                baseBll.Update(model);
                return Success("转派成功");

            }
            return Error("暂时没有权限操作");

        }

        //删除工单
        public ActionResult DeleteWorkOrder(string WorkOrderCode)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(WorkOrderCode);
            model.F_IsDelete = 1;
            if (baseBll.Update(model))
            {
                AddOperatorLog("删除了工单", (int)EnumOperatorType.delete, WorkOrderCode);
                return Success("删除成功");
            }

            else
                return Error("删除失败");
        }


        // 撤回（已指派未接单的可进行撤回，工单状态为“新工单0”）
        public ActionResult Retract(string workordercode, string BackReason)
        {

            Model.T_FaultRepair_Base model = baseBll.GetModel(workordercode);
            if (model == null)
            {
                return Error("没有获取到工单号");
            }
            string s = "";
            if (!string.IsNullOrEmpty(BackReason))
            {
                s += ",撤回原因:" + BackReason;
            }
            model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.neworder;
            model.F_Maintenancer = "";
            model.F_MaintenanceDept = "";
            model.F_AssignTime = null;
            model.F_AssignUser = "";
            model.F_UpdateTime = DateTime.Now;
            model.F_Deadline = null;

            baseBll.Update(model);

            ////催办次数改成0 
            //BLL.T_Wo_CommonBase wcbll = new BLL.T_Wo_CommonBase();
            //Model.T_Wo_CommonBase wcmodel = wcbll.GetModel(workordercode);
            //wcmodel.F_UrgeCount = 0;
            //wcmodel.F_UpdateTime = DateTime.Now;
            //wcbll.Update(wcmodel);

            AddOperatorLog(User.F_UserName + "撤回了工单" + s, (int)EnumOperatorType.retract, model.F_WorkOrderCode);
            return Success("撤回操作成功");
        }


        //综合保障中心里 指派（撤回之后可重新转派），同时需要记录操作流程
        public ActionResult Assign(string workordercode, string maintenancer, string maintenanceDept)
        {

            Model.T_FaultRepair_Base model = baseBll.GetModel(workordercode);
            if (model == null)
            {
                return Error("没有获取到工单号");
            }

            if (!string.IsNullOrEmpty(maintenanceDept))
            {
                model.F_AssignTime = DateTime.Now;
                model.F_AssignUser = User.F_UserCode;
                List<Model.T_Sys_GongDan> listgd = gdbll.GetModelList(" F_GDId='" + model.F_WorkOrderCategory + "'");
                double timeout = listgd.First().F_TimeOut;
                model.F_Deadline = DateTime.Now.AddHours(timeout);
                model.F_MaintenanceDept = maintenanceDept;
                if (!string.IsNullOrEmpty(maintenancer))
                    model.F_Maintenancer = maintenancer;
                else
                {
                    var user = GetBeOnDuty(maintenancer);
                    if (user != null && user.Count > 1)
                    {
                        model.F_Maintenancer = user[0];
                    }
                    else
                    {
                        return Error("请选择指派人员");
                    }
                }
                model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;

            }
            baseBll.Update(model);
            AddAssignlog(model.F_WorkOrderCode, maintenanceDept, maintenancer);

            return Success("指派操作成功");
        }


        //调度中心 退回到提交人（工单状态gai为“待提交”）
        public ActionResult ReBack(string workordercode, string BackReason)
        {

            Model.T_FaultRepair_Base model = baseBll.GetModel(workordercode);
            if (model == null)
            {
                return Error("没有获取到工单号");
            }
            model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.waitsubmit;


            string s = "";
            if (!string.IsNullOrEmpty(BackReason))
            {
                s += "\n退回原因:" + BackReason;
            }
            baseBll.Update(model);
            msg.AddInternalMessagesInfo("您有工单被退回", "您有工单被退回\n" + "工单编号:" + model.F_WorkOrderCode + s, model.F_Applicant
      , User.F_UserCode, EnumSmsType.repair
, 0, model.F_WorkOrderCode);

            AddOperatorLog(User.F_UserName + "退回了工单" + s, (int)EnumOperatorType.reback, model.F_WorkOrderCode);
            return Success("退回操作成功");
        }


        #endregion


        #region 处理人相关的操作 ： 查收 退单 到达 处理  内外协助  挂起 转派（给同事，转值班），转其他部门

        //处理人查收
        public ActionResult CheckWorkOrder(string WorkOrderCode)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(WorkOrderCode);
            if (model != null)
            {
                if (model.F_MaintenanceDept == User.F_DeptId.ToString())
                {
                    //同一部门的人都可以接单

                    //if (!string.IsNullOrEmpty(model.F_Maintenancer) && User.F_UserCode!=model.F_Maintenancer)
                    //{
                    //    return Error("你没有权限查收！");
                    //}

                    model.F_UpdateTime = DateTime.Now;

                    if (string.IsNullOrEmpty(model.F_Maintenancer))
                    {
                        model.F_Maintenancer = User.F_UserCode;
                    }
                    model.F_AcceptTime = DateTime.Now;
                    model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.dealing;
                    baseBll.Update(model);
                    AddOperatorLog("查收了工单", (int)EnumOperatorType.check, model.F_WorkOrderCode);

                    return Success(" 查收成功！");
                }
                else
                {
                    return Error("你没有权限查收！");
                }
            }
            return Error("工单不存在！");
        }

        //处理人退单  ,有内外协作的 不能退单
        public ActionResult BackWorkOrder(string WorkOrderCode, string BackReason ,int key, string value)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(WorkOrderCode);
            string s = "\n退回原因:" + value  ;
            if (!string.IsNullOrEmpty(BackReason))
            {
                s =s+ "，" + BackReason;
            }

            if (model != null)
            {
                if (model.F_MaintenanceDept == User.F_DeptId.ToString() && string.IsNullOrEmpty(model.F_InternalWorkOrderCode) && string.IsNullOrEmpty(model.F_ExternalWorkOrderCode))
                {
                    string assignuser = model.F_AssignUser;
                    model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.neworder;
                    model.F_Maintenancer = "";
                    model.F_MaintenanceDept = "";
                    model.F_AssignTime = null;
                    model.F_AssignUser = "";
                    model.F_UpdateTime = DateTime.Now;
                    model.F_Deadline = null;
                    model.F_AcceptTime = null;
                    baseBll.Update(model);
                    

                    
                    AddOperatorLogAboutKey("退回了工单" + s, (int)EnumOperatorType.back, model.F_WorkOrderCode,value,key,BackReason);
                    msg.AddInternalMessagesInfo("您有工单被退回", "您有工单被退回\n" + "工单编号:" + model.F_WorkOrderCode+s, assignuser
                                 , User.F_UserCode, EnumSmsType.repair
                   , 0, model.F_WorkOrderCode);


                    return Success(" 退回成功！");
                }
                else
                {
                    return Error("退回失败，有协作工单不能退单！");
                }
            }
            return Error("工单不存在！");
        }


        //到达操作  arrive
        public ActionResult Arrive(string workordercode)
        {

            Model.T_FaultRepair_Base model = baseBll.GetModel(workordercode);
            if (model == null)
            {
                return Error("没有获取到工单号");
            }
            model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.arrive;
            model.F_ArriveTime = DateTime.Now;
            baseBll.Update(model);
            AddOperatorLog(User.F_UserName + "已到达", (int)EnumOperatorType.arrive, model.F_WorkOrderCode);
            return Success("到达操作成功");
        }



        //维修员能看见当前部门的所有的工单 ，对于所有的工单都能去处理
        //处理完成 、异常完结  Type=0 正常完成  Type=1异常完结  判断是不是返修的工单
        //点击正常完成的时候添加“是否涉及设备，是否涉及设备点击是，出现下拉框可多选设备，选择之后可输入对应的数量和价格
        public ActionResult DealWorkOrder(string WorkOrderCode, int Type, string Result, string File, string finishtype,List<Model.T_InvolvedEquip_RepairProcess> equipmodellist, int ExceptionType = 0, int IsInvolvedEquip = 0)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(WorkOrderCode);

            if (Type == 0 && model.F_WorkOrderState != 6)
            {
                return Error("没有到达之前不能处理工单");

            }
            //判断是不是返修的，
            //20221213注释的，不判断了直接加处理记录算了
            //string sql = "select * from T_FaultRepair_Process where  F_WorkOrderCode='" + WorkOrderCode + "' and F_ReturnReason is not null    and F_Maintenancer='" + User.F_UserCode + "'";
            //DataTable dt = DbHelperSQL.Query(sql).Tables[0];
            DataTable dt = new DataTable();


            if (model != null)
            {
                //正常完成 
                if (Type == 0)
                {
                    model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.dealed;
                   
                    //是返修的工单
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        int procid = Convert.ToInt32(dt.Rows[0]["F_ProcessId"].ToString());
                        string updatesql = "UPDATE T_FaultRepair_Process set  F_ProcessingTime=GETDATE() ,  F_FinishType='"+finishtype+"',F_Result='" + Result + "' ,F_File='" + File + "',F_Maintenancer='" + User.F_UserCode + "',F_MaintenanceDept='" + User.F_DeptId + "',F_DealType='" + (int)EnumFaultRepairDealType.normal + "', F_IsInvolvedEquip='" + IsInvolvedEquip + "'  where F_ProcessId='" + procid + "'";
                        int updateid = DbHelperSQL.ExecuteSql(updatesql);
                        if (IsInvolvedEquip == 1)
                        {
                            string ids = "";
                            foreach (Model.T_InvolvedEquip_RepairProcess item in equipmodellist)
                            {
                                item.F_CreateTime = DateTime.Now;
                                item.F_IsDelete = 0;
                                item.F_RepairProcessId = procid;
                                item.F_WorkOrderCode = WorkOrderCode;
                                int equipid = equipbll.Add(item);

                                ids += equipid + ",";
                            }
                            Model.T_FaultRepair_Process promodelnew = dealBll.GetModel(procid);


                            model.F_ConfirmEquip = 1;
                            model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.confirm;
                            promodelnew.F_EquipDetail = ids.Substring(0, ids.LastIndexOf(','));

                       
                            dealBll.Update(promodelnew);

                        }


                        if (updateid > 0)
                        {
                            if (model.F_IsStop != 1)
                            { model.F_Endtime = DateTime.Now; }

                            model.F_IsStop = 0;
                            baseBll.Update(model);
                            msg.AddInternalMessagesInfo("您提交的工单已处理完毕，请及时进行评价", "您提交的工单已处理完毕，请及时进行评价\n" + "工单编号:" + model.F_WorkOrderCode, model.F_Applicant, User.F_UserCode, EnumSmsType.repair
               , 0, model.F_WorkOrderCode);
                            AddOperatorLog("完结了工单", (int)EnumOperatorType.dealed, WorkOrderCode);
                            return Success("处理完成");
                        }

                        else
                            return Error("处理失败");
                    }


                    Model.T_FaultRepair_Process promodel = new Model.T_FaultRepair_Process();
                    promodel.F_Isdelete = 0;
                    promodel.F_MaintenanceDept = User.F_DeptId.ToString();// model.F_MaintenanceDept;
                    promodel.F_Maintenancer = User.F_UserCode;// model.F_Maintenancer;
                    promodel.F_ProcessingTime = DateTime.Now;
                    promodel.F_Result = Result;
                    promodel.F_File = File;
                    promodel.F_WorkOrderCode = WorkOrderCode;
                    promodel.F_IsInvolvedEquip = IsInvolvedEquip;//0 否 1 是
                    promodel.F_FinishType = finishtype; //报修工单完工时增加处理方式：“远程”、“现场”，默认现场，另外工单详情中需要显示该字段信息

                    promodel.F_DealType = (int)EnumFaultRepairDealType.normal;

                    int id = dealBll.Add(promodel);
                    //是否涉及设备点击是，出现下拉框可多选设备，选择之后可输入对应的数量和价格
                    if (id > 0 && IsInvolvedEquip == 1)
                    {
                        string ids = "";
                        foreach (Model.T_InvolvedEquip_RepairProcess item in equipmodellist)
                        {
                            item.F_CreateTime = DateTime.Now;
                            item.F_IsDelete = 0;
                            item.F_RepairProcessId = id;
                            item.F_WorkOrderCode = WorkOrderCode;
                            int equipid = equipbll.Add(item);

                            ids += equipid + ",";
                        }
                        model.F_ConfirmEquip = 1;
                        model.F_WorkOrderState =(int) EnumFaultRepairWorkOrderState.confirm;
                        Model.T_FaultRepair_Process promodelnew = dealBll.GetModel(id);

                        promodelnew.F_EquipDetail = ids.Substring(0, ids.LastIndexOf(','));
                        dealBll.Update(promodelnew);

                    }
                    if (id > 0)
                    {
                        if (model.F_IsStop != 1)
                        { model.F_Endtime = DateTime.Now; }
                        model.F_IsStop = 0;
                        baseBll.Update(model);
                        msg.AddInternalMessagesInfo("您提交的工单已处理完毕，请及时进行评价", "您提交的工单已处理完毕，请及时进行评价\n" + "工单编号:" + model.F_WorkOrderCode, model.F_Applicant, User.F_UserCode, EnumSmsType.repair
               , 0, model.F_WorkOrderCode);
                        AddOperatorLog("完结了工单", (int)EnumOperatorType.dealed, WorkOrderCode);
                        return Success("处理完成");
                    }
                    else
                        return Error("处理失败");
                }
                else
                {

                    int dealtype = 0;

                    // "自行解决";
                    if (User.F_DeptId.ToString() == model.F_ApplicationDept.Trim())//创建工单的人是处理人，存自行解决
                    {
                        dealtype = (int)EnumFaultRepairDealType.resolve;// "自行解决";

                    }
                    else
                    {
                        dealtype = (int)EnumFaultRepairDealType.abnormal;
                    }



                    model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.exceptionended;
                  //  model.F_Endtime = DateTime.Now;
                    //是返修的工单
                    if (dt != null && dt.Rows.Count > 0)
                    {

                        //  promodel.F_ExceptionType = ExceptionType;
                        int procid = Convert.ToInt32(dt.Rows[0]["F_ProcessId"].ToString());
                        string updatesql = "UPDATE T_FaultRepair_Process set  F_ProcessingTime=GETDATE() , F_FinishType='"+finishtype+"',F_Result='" + Result + "' ,F_File='" + File + "',F_UpdateTime= GETDATE(),dealtype='" + dealtype + "' ,F_ExceptionType='" + ExceptionType + "'  where F_ProcessId='" + procid + "'";
                        if (DbHelperSQL.ExecuteSql(updatesql) > 0)
                        {
                            if (model.F_IsStop != 1)
                            { model.F_Endtime = DateTime.Now; }
                            model.F_IsStop = 0;
                            baseBll.Update(model);
                            AddOperatorLog("异常完结了工单", (int)EnumOperatorType.exceptionended, WorkOrderCode);
                            return Success("异常完结");
                        }
                        else
                            return Error("异常完结失败");
                    }
                    //异常完结工单
                    Model.T_FaultRepair_Process promodel = new Model.T_FaultRepair_Process();
                    promodel.F_Isdelete = 0;
                    promodel.F_MaintenanceDept = User.F_DeptId.ToString();//  model.F_MaintenanceDept;
                    promodel.F_Maintenancer = User.F_UserCode;// model.F_Maintenancer;
                    promodel.F_ProcessingTime = DateTime.Now;
                    promodel.F_Result = Result;
                    promodel.F_File = File;
                    promodel.F_WorkOrderCode = WorkOrderCode;
                    promodel.F_ExceptionType = ExceptionType;
                    promodel.F_DealType = dealtype;
                    promodel.F_FinishType = finishtype;
                    if (dealBll.Add(promodel) > 0)
                    {
                        if (model.F_IsStop != 1)
                        { model.F_Endtime = DateTime.Now; }

                        model.F_IsStop = 0;
                        baseBll.Update(model);
                        AddOperatorLog("异常完结了工单", (int)EnumOperatorType.exceptionended, WorkOrderCode);
                        return Success("异常完结");
                    }
                    else
                        return Error("异常完结失败");
                }

            }
            return Error("工单不存在");
        }



        //操作：挂起（挂起的工单超时时限不记录到超时时限中，只有处理中未完结的工单可挂起），另外列表显示一列“是否挂起”字段
        //挂起
        public ActionResult HangUp(string workordercode, int key, string value, string reason)
        {

            Model.T_FaultRepair_Base model = baseBll.GetModel(workordercode);
            if (model != null && model.F_WorkOrderState != 2 && model.F_WorkOrderState != 6)
            {
                return Error("挂起失败");
            }
            model.F_IsStop = 1;
            model.F_StopTime = DateTime.Now;
            model.F_Endtime = DateTime.Now;
            baseBll.Update(model);
            string str = "";
            if (!string.IsNullOrEmpty(reason))
            {
                str = "," + reason;
            }
            AddOperatorLogAboutKey(User.F_UserCode + "挂起了工单,原因:" + value + str, (int)EnumOperatorType.hangup, model.F_WorkOrderCode, value, key, reason);
            return Success("挂起成功");
        }



        /// <summary>
        /// 协助.内外协助都生成新工单 Type 0是内部协助 1是外部协助，外部协助增加字段“是否调度协调”，如果是跟现在流程一样，如果否，直接转派给其他部门和人员同时生成新工单
        /// </summary>
        /// <param name="WorkOrderCode"></param>
        /// <param name="WorkOrderCategory"></param>
        /// <param name="Maintenancer"></param>
        /// <param name="Content"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        public ActionResult AssistWorkOrder(string WorkOrderCode, string WorkOrderCategory, string Maintenancer, int Type,int needharmony=1, string Content = "",string wbmaintenancer="",string  wbmaintenancerdept="")
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(WorkOrderCode);
            Model.T_FaultRepair_Base newmodel = new Model.T_FaultRepair_Base();

            string mes = "";
            var dicvalue = new Model.T_Sys_GongDan();
            dicvalue = new Bll.T_Sys_GongDan().GetModel(Convert.ToInt32(WorkOrderCategory));
            if (dicvalue != null)
            {
                mes = "\n工单类型:故障报修/" + dicvalue.F_Name;
            }

            List<Model.T_Sys_GongDan> listgd = gdbll.GetModelList(" F_GDId='" + WorkOrderCategory + "'");
            double timeout = listgd.First().F_TimeOut;

            //string message = "";

            if (Type == 0)
            {
                if (string.IsNullOrEmpty(Maintenancer))
                {
                    return Error("请选择维修人");
                }
                newmodel.F_Applicant = model.F_Applicant;
                newmodel.F_Applicantsphone = model.F_Applicantsphone;
                newmodel.F_ApplicationDept = string.IsNullOrEmpty(model.F_ApplicationDept) ? "" : model.F_ApplicationDept.Trim();
                newmodel.F_Phone = model.F_Phone;
                newmodel.F_WorkOrderCategory = WorkOrderCategory;
                newmodel.F_Content = Content==""?model.F_Content:Content;
                newmodel.F_PlaceOfRepair = model.F_PlaceOfRepair;

                newmodel.F_Maintenancer = Maintenancer;
                newmodel.F_MaintenanceDept = model.F_MaintenanceDept;
                newmodel.F_AssignTime = DateTime.Now;
                newmodel.F_AssignUser = User.F_UserCode;
                newmodel.F_File = model.F_File;

             
                newmodel.F_Deadline = DateTime.Now.AddHours(timeout);

                newmodel.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;
                newmodel.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号

                newmodel.F_CreateTime = DateTime.Now;
                newmodel.F_CreateUser = User.F_UserCode;
                newmodel.F_CreateUserDept = User.F_DeptId.ToString();

                

                newmodel.F_AssignUser = User.F_UserCode;
                newmodel.F_AssignTime = DateTime.Now;

               
              

                if (baseBll.Add(newmodel) > 0)
                {
                    AddAddlog(newmodel.F_WorkOrderCode);

                    if (!string.IsNullOrEmpty(Maintenancer))
                    {
                        
                        msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + newmodel.F_WorkOrderCode + mes, Maintenancer, User.F_UserCode, EnumSmsType.repair
                       , 0, newmodel.F_WorkOrderCode);
                        AddAssignlog(newmodel.F_WorkOrderCode, model.F_MaintenanceDept, Maintenancer);
                    }
                    //更新model

                    if (!string.IsNullOrEmpty(model.F_InternalWorkOrderCode))
                    {
                        model.F_InternalWorkOrderCode += "," + newmodel.F_WorkOrderCode;
                    }
                    else
                    {
                        model.F_InternalWorkOrderCode = newmodel.F_WorkOrderCode;

                    }
                    model.F_UpdateTime = DateTime.Now;
                    if (model.F_IsStop != 1)
                    { model.F_Endtime = DateTime.Now; }
                    baseBll.Update(model);

                    AddInternalasslog(model.F_WorkOrderCode, newmodel.F_WorkOrderCode);

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




            }
            //外协作
            else
            {
                if (needharmony == 1) //需要调度协调
                {
                    newmodel.F_Applicant = model.F_Applicant;
                    newmodel.F_Applicantsphone = model.F_Applicantsphone;
                    newmodel.F_ApplicationDept = string.IsNullOrEmpty(model.F_ApplicationDept) ? "" : model.F_ApplicationDept.Trim();
                    newmodel.F_Phone = model.F_Phone;

                    newmodel.F_WorkOrderCategory = WorkOrderCategory;
                    newmodel.F_Content = Content == "" ? model.F_Content : Content;
                    newmodel.F_PlaceOfRepair = model.F_PlaceOfRepair;


                    newmodel.F_File = model.F_File;

                    newmodel.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.neworder;
                    newmodel.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号

                    newmodel.F_CreateTime = DateTime.Now;
                    newmodel.F_CreateUser = User.F_UserCode;
                    newmodel.F_CreateUserDept = User.F_DeptId.ToString();
                    if (baseBll.Add(newmodel) > 0)
                    {
                        AddOperatorLog("创建了工单", (int)EnumOperatorType.add, newmodel.F_WorkOrderCode);

                        //更新原来的工单model
                        if (!string.IsNullOrEmpty(model.F_ExternalWorkOrderCode))
                        {
                            model.F_ExternalWorkOrderCode += "," + newmodel.F_WorkOrderCode;
                        }
                        else
                        {
                            model.F_ExternalWorkOrderCode = newmodel.F_WorkOrderCode;
                        }
                        model.F_UpdateTime = DateTime.Now;
                        baseBll.Update(model);

                        AddExternalasslog(model.F_WorkOrderCode, newmodel.F_WorkOrderCode);

                        return Success("添加成功！");
                    }
                    else return Error("添加失败！");
                }
                else
                {
                    newmodel.F_Applicant = model.F_Applicant;
                    newmodel.F_Applicantsphone = model.F_Applicantsphone;
                    newmodel.F_ApplicationDept = string.IsNullOrEmpty(model.F_ApplicationDept) ? "" : model.F_ApplicationDept.Trim();
                    newmodel.F_Phone = model.F_Phone;

                    newmodel.F_WorkOrderCategory = WorkOrderCategory;
                    newmodel.F_Content = Content==""?model.F_Content:Content;
                    newmodel.F_PlaceOfRepair = model.F_PlaceOfRepair;

                     newmodel.F_Maintenancer = wbmaintenancer;
                    newmodel.F_MaintenanceDept = wbmaintenancerdept;

                    newmodel.F_File = model.F_File;

                    newmodel.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;
                    newmodel.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号

                    newmodel.F_CreateTime = DateTime.Now;
                    newmodel.F_CreateUser = User.F_UserCode;
                    newmodel.F_CreateUserDept = User.F_DeptId.ToString();


                    newmodel.F_Deadline = DateTime.Now.AddHours(timeout);
                    newmodel.F_AssignUser = User.F_UserCode;
                    newmodel.F_AssignTime = DateTime.Now;


                    if (baseBll.Add(newmodel) > 0)
                    {
                        AddOperatorLog("创建了工单", (int)EnumOperatorType.add, newmodel.F_WorkOrderCode);

                        AddAssignlog(newmodel.F_WorkOrderCode,wbmaintenancerdept,wbmaintenancer);

                         
                        msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + newmodel.F_WorkOrderCode + mes, newmodel.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
                       , 0, newmodel.F_WorkOrderCode);


                        //更新原来的工单model
                        if (!string.IsNullOrEmpty(model.F_ExternalWorkOrderCode))
                        {
                            model.F_ExternalWorkOrderCode += "," + newmodel.F_WorkOrderCode;
                        }
                        else
                        {
                            model.F_ExternalWorkOrderCode = newmodel.F_WorkOrderCode;
                        }
                        model.F_UpdateTime = DateTime.Now;
                        baseBll.Update(model);

                        AddExternalasslog(model.F_WorkOrderCode, newmodel.F_WorkOrderCode);

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


        }


        //转派 ，派给自己的工单 转给同部门的别的人
        //0 是转同事 1 是转组长(暂时不用了这个)  2 是转值班的人
        public ActionResult Transfer(string WorkOrderCode, string ToUserCode, int type = 0)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(WorkOrderCode);
            if (model != null && model.F_MaintenanceDept == User.F_DeptId.ToString())
            {
                if (type == 0)
                {
                    //转同事
                    model.F_Maintenancer = ToUserCode;
                    model.F_UpdateTime = DateTime.Now;

                    model.F_AssignTime = DateTime.Now;
                    model.F_AssignUser = User.F_UserCode;
                    model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;
                    AddOperatorLog("转派工单给" + GetDeptModel(model.F_MaintenanceDept) + "部门" + GetUserModel(ToUserCode), (int)EnumOperatorType.transfer, WorkOrderCode);

                    baseBll.Update(model);


                    return Success("转派成功");
                }
                else if (type == 1)
                {
                    //是转组长
                    var role = new Bll.T_Sys_Role().GetModelList("F_RoleCode='WXBZZ' and F_State =1");
                    var userzz = new Bll.T_Sys_UserAccount().GetModelList("F_DeptId='" + model.F_MaintenanceDept + "' and F_DeleteFlag=0 " +
                     "and F_RoleId = '" + role.FirstOrDefault().F_RoleId + "'");

                    if (userzz != null && userzz.Count > 0)
                    {
                       
                        model.F_Maintenancer = userzz.First().F_UserCode;
                        model.F_UpdateTime = DateTime.Now;
                        model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;
                        AddOperatorLog("转派工单给" + GetDeptModel(model.F_MaintenanceDept) + "部门" + GetUserModel(userzz.First().F_UserCode), (int)EnumOperatorType.transfer, WorkOrderCode);

                        baseBll.Update(model);
                        return Success("转派成功");
                    }
                    else
                    {
                        return Error("没有维修部组长");
                    }

                }
                else
                {
                    //  是转值班的人,没有值班的人 提示转派失败
                   List<T_Sys_GroupClass> listwork=    GetWorkUser(User.F_DeptId);
                    if (listwork!=null&& listwork.Count>0)
                    {
                        string touser= listwork.First().F_UserCode;
                        model.F_Maintenancer= touser;
                        model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;
                        model.F_AssignTime = DateTime.Now;
                        model.F_AssignUser = User.F_UserCode;

                        model.F_UpdateTime = DateTime.Now;
                        AddOperatorLog("转派工单给" + GetDeptModel(model.F_MaintenanceDept) + "部门" + GetUserModel(touser), (int)EnumOperatorType.transfer, WorkOrderCode);

                        baseBll.Update(model);
                        return Success("转值班成功！");
                    }
                    return Error("转派失败，没有值班人员！");

                }

            }
            return Error("暂时没有权限操作");

        }

        /// <summary>
        /// 处理人转给其他部门其他人
        /// </summary>
        /// <param name="WorkOrderCode"></param>
        /// <param name="ToUserCode"></param>
        /// <param name="ToDept"></param>
        /// <returns></returns>
        public ActionResult DealManTransfer(string WorkOrderCode, string ToUserCode, string ToDept)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(WorkOrderCode);
            if (model != null) 
            {
                string mes = "";
                var dicvalue = new Model.T_Sys_GongDan();
                dicvalue = new Bll.T_Sys_GongDan().GetModel(Convert.ToInt32(model.F_WorkOrderCategory));
                if (dicvalue != null)
                {
                    mes = "\n工单类型:故障报修/" + dicvalue.F_Name;
                }

               

                List<Model.T_Sys_GongDan> listgd = gdbll.GetModelList(" F_GDId='" + model.F_WorkOrderCategory + "'");
                //int timeout = listgd.First().F_TimeOut;
                //model.F_Deadline = DateTime.Now.AddHours(timeout);
                string message = "";

                //当工单没有选择指派部门的时候，当前工单类型shezhi指派部门，该工单默认到这个指派的部门
                if (string.IsNullOrEmpty(ToDept) || ToDept == "0")
                {
                    //根据工单类别判断 是否有指派部门
                    List<Model.T_Sys_GongDan> gd = gdbll.GetModelList(" F_GDId='" + model.F_WorkOrderCategory + "'");
                    int deptid = listgd.First().F_AutoDept != null ? listgd.First().F_AutoDept.Value : 0;
                    if (deptid == 0)
                    {
                        return Error("当前工单类型没有设置指派部门，请前往设置或者选择指派部门");
                    }
                    else
                        ToDept = deptid.ToString();
                }

                if (!string.IsNullOrEmpty(ToUserCode))
                {
                    model.F_Maintenancer = ToUserCode;
               
                    message = "转派工单给" + GetDeptModel(ToDept) + "部门" + GetUserModel(ToUserCode);
                    msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + model.F_WorkOrderCode + mes, model.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
                   , 0, model.F_WorkOrderCode);
                }
                else
                {
                    //部门下没有人员不可进行转派
                    var usercount = new Bll.T_Sys_UserAccount().GetModelList("F_DeptId='" + ToDept + "' and F_DeleteFlag=0 ");
                    if (usercount == null || usercount.Count == 0)
                    {
                        return Error("当前部门没有人员 ，不可进行转派");
                    }


                    var user = GetBeOnDuty(ToDept);
                    if (user != null && user.Count > 1)
                    {
                        model.F_Maintenancer = user[0];
                        message = "转派工单给" + GetDeptModel(ToDept) + "部门" + GetUserModel(user[0]);
                        msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + model.F_WorkOrderCode + mes, model.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
                   , 0, model.F_WorkOrderCode);

                    }
                    else
                    {
                        return Error("请选择指派人员");
                    }
                }
                model.F_MaintenanceDept = ToDept;
                model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;

                model.F_AssignUser = User.F_UserCode;
                model.F_AssignTime = DateTime.Now;

                model.F_UpdateTime = DateTime.Now;
                AddOperatorLog(message, (int)EnumOperatorType.assign, WorkOrderCode);

                baseBll.Update(model);
                return Success("转派成功");

            }
            return Error("转派失败");

        }


        #endregion


        /// <summary>
        /// 维修员的列表 待接单 待完成 已完成
        /// </summary>
        /// <returns></returns>
        public ActionResult MaintenancerList()
        {
            string sql = " and F_IsDelete=0 ";
            //待接单1  待完成 2 已完成 3

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

            int strstate = RequestString.GetInt("state", -1);
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));

            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));

            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strworkcode = HttpUtility.UrlDecode(RequestString.GetQueryString("workordercode"));

            //获取部门表中设置的，当前部门是转组长还是转值班
            //  0 是转值班 1 是转组长 默认0
            Model.T_Sys_Department depmodel = departmentBLL.GetModel(User.F_DeptId);
            int transfertype = 0;
            if (depmodel != null && depmodel.F_TransferType != null)
            {
                transfertype = depmodel.F_TransferType.Value;
            }

            //  判断当前登录人是不是部门主管角色   ,部门主管可以看到部门下所有的处理工单            

            int isbuzg = 0;

            if (User.F_RoleCode == "BMZG")
            {
                isbuzg = 1;
            }

            #region  部门表中设置的转值班，值班人员 可看到部门工单； 设置转组长 ，组长可以看见部门工单；其他人员看到个人工单


            int workuser = 0;
            if (transfertype == 0)
            {
                List<T_Sys_GroupClass> GroupClass = GetWorkUser(User.F_DeptId);
                if (GroupClass != null && GroupClass.Count > 0)
                {
                    var iszhibanrenyuan = GroupClass.Where(x => x.F_UserCode.Contains(User.F_UserCode)).ToList();

                    if (iszhibanrenyuan != null && iszhibanrenyuan.Count > 0)
                    {
                        workuser = 1;//当前登录人是值班人员
                        sql += " and F_MaintenanceDept='" + User.F_DeptId + "'";
                    }
                    else
                    {
                        if (isbuzg==1)
                        {
                           
                            sql += " and F_MaintenanceDept  in(select F_DeptId from[dbo].[GetDeptid] ('"+User.F_DeptId+"'))";
                        }
                        else
                        {
                        sql += " and F_Maintenancer='" + User.F_UserCode + "'";

                        }

                    }
                }
                else
                {
                    if (isbuzg == 1)
                    {
                        sql += " and F_MaintenanceDept  in(select F_DeptId from[dbo].[GetDeptid] ('" + User.F_DeptId + "'))";
                    }
                    else
                    {
                        sql += " and F_Maintenancer='" + User.F_UserCode + "'";
                    }
                }
            }

            else
            {
                //  判断当前登录人是不是组长角色               
                var user = new Bll.T_Sys_UserAccount().GetModelList(" F_UserCode='"+User.F_UserCode+ "' and F_RoleId in ( select F_RoleId from T_Sys_Role where F_RoleCode='WXBZZ' and F_State =1)");
                if (user!=null && user.Count>0)
                {
                    sql += " and F_MaintenanceDept='" + User.F_DeptId + "'";
                    workuser = 1;
                }
                else
                {
                    if (isbuzg == 1)
                    {
                        sql += " and F_MaintenanceDept  in(select F_DeptId from[dbo].[GetDeptid] ('" + User.F_DeptId + "'))";
                    }
                    else
                    {
                        sql += " and F_Maintenancer='" + User.F_UserCode + "'";
                    }
                }
            }
            #endregion




            #region 搜索条件
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

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


            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_Applicant = '" + strname + "' ";
            }
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and (F_Applicantsphone  like '%" + strtel + "%' or F_Phone like '%" + strtel + "%') ";
            }
            if (strworkcode.Trim() != "" && strworkcode != "undefined")
            {
                sql += " and F_WorkOrderCode like'%" + strworkcode + "%'";
            }

            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                if (strendtime.Trim() != "" && strendtime != "undefined")
                {
                    sql += " and F_CreateTime  between   '" + strstarttime +
                             "' AND  '" + strendtime + "'";
                }
                else
                {
                    sql += " and F_CreateTime>='" + strstarttime + "' ";
                }
            }
            else
            {
                if (strendtime.Trim() != "" && strendtime != "undefined")
                {
                    sql += " and F_CreateTime<='" + strendtime + "' ";
                }
            }
            #endregion

            switch (strstate)
            {
                case 1:
                    sql += " and F_WorkOrderState=1";
                    break;
                case 2:
                    sql += " and (F_WorkOrderState=2 or F_WorkOrderState=6)";
                    break;
                case 3:
                    sql += " and (F_WorkOrderState>=3 and F_WorkOrderState!=6 )";
                    break;

            }
            int recordCount = 0;
            DataTable datatable = Bll.PagerBll.GetListPager
                                            ("T_FaultRepair_Base ",
                                              "F_WorkOrderId",
                                              "*,[dbo].[GetUserName](F_Maintenancer) Maintenancer,[dbo].[GetUserName](F_Applicant) Applicant,[dbo].[GetAssistanceState](F_WorkOrderCode) AssistanceState,(case  F_isstop when  1 then '是' when 0 then '否' else '' end ) ishangup",
                                              sql,
                                              "order by F_WorkOrderId desc",
                                              pagesize,
                                              pageindex,
                                              true,
                                              out recordCount
                                            );


            datatable = WorkOrderBase.SetOtherField(datatable, MENUENUM.报修列表, User.F_UserCode, User.F_RoleId, 3000,0,workuser, transfertype);

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



        }


    
        /// <summary>
        /// 自动评价
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Evaluate()
        {
            string evaluatecontent = "自动评价了工单";
            var dicvalue = new Bll.T_Sys_DictionaryValue().
               GetModelList("F_DictionaryFlag='PJSX' and F_State=1");
            int SX = 2;
            try
            {
                if (dicvalue != null && dicvalue.Count > 0)
                {
                    SX = int.Parse(dicvalue.FirstOrDefault().F_Name);
                }
            }
            catch
            {
                SX = 2;
            }

           
                var IntegratedScheduling_Base = new BLL.T_IntegratedScheduling_Base().GetModelList(" F_WorkOrderState=3 and F_IsDelete=0 " +
                 "and datediff(minute , F_Endtime , getdate())>'" + SX * 60 + "'");
            if (IntegratedScheduling_Base != null && IntegratedScheduling_Base.Count > 0)
            {
                foreach (var model in IntegratedScheduling_Base)
                {
                    Model.T_IntegratedScheduling_Evaluate evamodel = new Model.T_IntegratedScheduling_Evaluate();
                    if (model != null)
                    {

                        evamodel.F_EvaluateContent = SX + "小时未评价自动评价满意";
                        // evamodel.F_Quality = 5;
                        evamodel.F_Attitude = 5;

                      //  evamodel.F_Efficiency = 5;
                        evamodel.F_Evaluator = "";
                        evamodel.F_EvaluationTime = DateTime.Now;
                        evamodel.F_Isdelete = 0;
                        evamodel.F_WorkOrderCode = model.F_WorkOrderCode;
                        BLL.T_IntegratedScheduling_Evaluate evabll = new BLL.T_IntegratedScheduling_Evaluate();
                        if (evabll.Add(evamodel) > 0)
                        {
                            model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.finish;
                            model.F_UpdateTime = DateTime.Now;
                            model.F_Score = 5;
                            model.MYD = 0;

                            basescheBll.Update(model);
                            var conre = DependencyResolver.Current.GetService<SchedulingController>();
                            conre.AddEvaluateOperatorLog(evaluatecontent, (int)EnumOperatorType.evaluate, model.F_WorkOrderCode);

                        }
                        else
                            continue;

                    }
                }
            }







            var FaultRepair_Base = new BLL.T_FaultRepair_Base().GetModelList(" F_WorkOrderState=3 and F_IsDelete=0 " +
             "and datediff(minute , F_Endtime , getdate())>'" + SX * 60 + "'");
            if (FaultRepair_Base != null && FaultRepair_Base.Count > 0)
            {
                foreach (var model in FaultRepair_Base)
                {
                    Model.T_FaultRepair_Evaluate evamodel = new Model.T_FaultRepair_Evaluate();
                    if (model != null)
                    {

                        evamodel.F_EvaluateContent = SX + "小时未评价自动评价满意";
                        evamodel.F_Quality = 5;
                        evamodel.F_Attitude = 5;

                        evamodel.F_Efficiency = 5;
                        evamodel.F_Evaluator = "";
                        evamodel.F_EvaluationTime = DateTime.Now;
                        evamodel.F_Isdelete = 0;
                        evamodel.F_WorkOrderCode = model.F_WorkOrderCode;
                        BLL.T_FaultRepair_Evaluate evabll = new BLL.T_FaultRepair_Evaluate();
                        if (evabll.Add(evamodel) > 0)
                        {
                            model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.finish;
                            model.F_UpdateTime = DateTime.Now;
                            model.F_Score = 15;
                            model.MYD = 0;
                            if (model.F_ConfirmEquip == 1)
                            {
                                model.F_ConfirmEquip = 2;
                            }

                            baseBll.Update(model);
                            AddEvaluateOperatorLog(evaluatecontent, (int)EnumOperatorType.evaluate, model.F_WorkOrderCode);

                            #region 评价的时候如果有协作工单，协作工单评价数据和主工单保持一致，同时需要记录操作流程
                            if (!string.IsNullOrEmpty(model.F_InternalWorkOrderCode))
                            {

                                string[] codes = model.F_InternalWorkOrderCode.Split(',');
                                foreach (string item in codes)
                                {
                                    Model.T_FaultRepair_Evaluate evamodel1 = new Model.T_FaultRepair_Evaluate();
                                    evamodel1 = evamodel;
                                    evamodel.F_WorkOrderCode = item;
                                    evabll.Add(evamodel1);
                                    AddEvaluateOperatorLog(evaluatecontent, (int)EnumOperatorType.evaluate, item);
                                    var intermodel = baseBll.GetModel(item);
                                    intermodel.F_Score = 15;
                                    intermodel.MYD = 0;
                                    if (intermodel.F_ConfirmEquip == 1)
                                    {
                                        intermodel.F_ConfirmEquip = 2;
                                    }

                                    baseBll.Update(intermodel);
                                }
                            }
                            if (!string.IsNullOrEmpty(model.F_ExternalWorkOrderCode))
                            {

                                string[] codes = model.F_ExternalWorkOrderCode.Split(',');
                                foreach (string item in codes)
                                {
                                    Model.T_FaultRepair_Evaluate evamodel1 = new Model.T_FaultRepair_Evaluate();
                                    evamodel1 = evamodel;
                                    evamodel.F_WorkOrderCode = item;
                                    evabll.Add(evamodel1);
                                    AddEvaluateOperatorLog(evaluatecontent, (int)EnumOperatorType.evaluate, item);

                                    var extermodel = baseBll.GetModel(item);

                                    if (extermodel.F_ConfirmEquip == 1)
                                    {
                                        extermodel.F_ConfirmEquip = 2;
                                    }
                                    extermodel.F_Score = 15;
                                    extermodel.MYD = 0;
                                    baseBll.Update(extermodel);
                                }
                            }
                            #endregion


                        }
                        else
                            continue;

                    }
                }
            }
            return Success("评价完成");

        }
    
        /// <summary>
        /// 自动流转
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Automatic()
        {

            var dicvalue = new Bll.T_Sys_DictionaryValue().
                GetModelList("F_DictionaryFlag='JDSX' and F_State=1");
            string SX = "10";
            if (dicvalue != null && dicvalue.Count > 0)
            {
                SX = dicvalue.FirstOrDefault().F_Name;
            }
            var FaultRepair_Base = new BLL.T_FaultRepair_Base().GetModelList(" F_WorkOrderState=1 and F_IsDelete=0 " +
               "and datediff(minute , F_AssignTime , getdate())>'" + SX + "'");
            var class1 = new Bll.T_Sys_Class().GetModelList("F_IsDelete=0 and F_IsAutomatic=1  and F_InTime<= convert(varchar(10),getdate(),108) " +
                "and F_OutTime>=convert(varchar(10),getdate(),108) ");

            if (class1!=null && class1.Count >0)
            {
                var GroupClass1 = new Bll.T_Sys_GroupClass().GetModelList($"F_IsDelete=0 and F_ClassCode in(" +
                    $"{string.Join(",", class1.Select(x => x.F_Id))})  and datediff(day , F_Date , getdate())= 0 " +
                      "  order by F_Id asc");
                if (FaultRepair_Base != null && FaultRepair_Base.Count > 0)
                {
                    foreach (var model in FaultRepair_Base)
                    {
                        model.F_AssignTime = DateTime.Now;
                        model.F_AssignUser = "系统流转";
                        List<Model.T_Sys_GongDan> listgd = gdbll.GetModelList(" F_GDId='" + model.F_WorkOrderCategory + "'");
                        double timeout = listgd.First().F_TimeOut;
                        model.F_Deadline = DateTime.Now.AddHours(timeout);
                        string user = "";
                        var GroupClass = GroupClass1.Where(x => x.F_DeptId.ToString() == model.F_MaintenanceDept)
                            .OrderBy(x => x.F_Id);
                        if (GroupClass != null && GroupClass.Count() > 1)
                        {
                            var Class = GroupClass.Where(x => x.F_State == 1);
                            if (Class != null && Class.Count() > 0)
                            {
                                var Class1 = GroupClass.Where(x => x.F_State == 0 && x.F_Id > Class.LastOrDefault().F_Id);
                                if (Class1 != null && Class1.Count() > 0)
                                {
                                    user = Class1.FirstOrDefault().F_UserCode;
                                    Class1.FirstOrDefault().F_State = 1;
                                    new Bll.T_Sys_GroupClass().Update(GroupClass.FirstOrDefault());
                                    Class.LastOrDefault().F_State = 0;
                                    new Bll.T_Sys_GroupClass().Update(Class.LastOrDefault());
                                }
                                else
                                {
                                    user = GroupClass.FirstOrDefault().F_UserCode;
                                    GroupClass.FirstOrDefault().F_State = 1;
                                    new Bll.T_Sys_GroupClass().Update(GroupClass.FirstOrDefault());
                                    Class.LastOrDefault().F_State = 0;
                                    new Bll.T_Sys_GroupClass().Update(Class.LastOrDefault());
                                }
                            }
                            else
                            {
                                user = GroupClass.FirstOrDefault().F_UserCode;
                                GroupClass.FirstOrDefault().F_State = 1;
                                new Bll.T_Sys_GroupClass().Update(GroupClass.FirstOrDefault());
                            }
                        }
                        else
                        {
                            continue;
                        }
                        model.F_Maintenancer = user;
                        model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;
                        model.F_UpdateTime = DateTime.Now;
                        AddOperatorLog("超十分钟未接单,自动流转给" + GetDeptModel(model.F_MaintenanceDept) + "部门" + GetUserModel(user), (int)EnumOperatorType.assign, model.F_WorkOrderCode);
                        baseBll.Update(model);
                    }
                }
            }
           
            return Success("");
        }

        /// <summary>
        /// 获取值班人员
        /// </summary>
        /// <param name="ToDept"></param>
        /// <returns></returns>
        private List<string> GetBeOnDuty(string ToDept)
        {
            List<string> user = new List<string>();
            //获取班组长
            var role = new Bll.T_Sys_Role().GetModelList("F_RoleCode='WXBZZ' and F_State =1");
            //当前时间的班别
            var class1 = new Bll.T_Sys_Class().GetModelList("F_IsDelete=0   and F_InTime<= convert(varchar(10),getdate(),108) " +
              "and F_OutTime>=convert(varchar(10),getdate(),108) ");

            if (class1!=null && class1.Count >0)
            {
                //获取值班人员
                var GroupClass = new Bll.T_Sys_GroupClass().GetModelList($"F_IsDelete=0 and F_ClassCode in(" +
                    $"{string.Join(",", class1.Select(x => x.F_Id))})  and datediff(day , F_Date , getdate())= 0 " +
                      "and F_DeptId='" + ToDept + "'  order by F_Id asc");

                if (GroupClass != null && GroupClass.Count > 0)
                {
                    if (GroupClass.Count == 1)
                    {
                        user.Add(GroupClass[0].F_UserCode);
                        user.Add("有值班人员,自动流转给" + GetDeptModel(ToDept) + "部门" + GetUserModel(GroupClass[0].F_UserCode));
                    }
                    else
                    {
                        //Class  是轮值过的人  F_State=1轮过了
                        var Class = GroupClass.Where(x => x.F_State == 1);
                        if (Class != null && Class.Count() > 0)
                        {
                           //Class1 是没轮过的
                            var Class1 = GroupClass.Where(x => x.F_State == 0 && x.F_Id > Class.LastOrDefault().F_Id);
                            if (Class1 != null && Class1.Count() > 0)
                            {
                                user.Add(Class1.FirstOrDefault().F_UserCode);
                                user.Add("有值班人员,自动流转给" + GetDeptModel(ToDept) + "部门" + GetUserModel(Class1.FirstOrDefault().F_UserCode));
                                Class1.FirstOrDefault().F_State = 1;
                                new Bll.T_Sys_GroupClass().Update(GroupClass[0]);
                                Class.LastOrDefault().F_State = 0;
                                new Bll.T_Sys_GroupClass().Update(Class.LastOrDefault());
                            }
                            else
                            {
                                //已经轮到最后一个人了，从第一个人开始
                                user.Add(GroupClass[0].F_UserCode);
                                user.Add("有值班人员,自动流转给" + GetDeptModel(ToDept) + "部门" + GetUserModel(GroupClass[0].F_UserCode));
                                GroupClass[0].F_State = 1;
                                new Bll.T_Sys_GroupClass().Update(GroupClass[0]);
                                Class.LastOrDefault().F_State = 0;
                                new Bll.T_Sys_GroupClass().Update(Class.LastOrDefault());
                            }
                        }
                        else
                        {//第一次轮值从第一个人开始轮

                            user.Add(GroupClass[0].F_UserCode);
                            user.Add("有值班人员,自动流转给" + GetDeptModel(ToDept) + "部门" + GetUserModel(GroupClass[0].F_UserCode));
                            GroupClass[0].F_State = 1;
                            new Bll.T_Sys_GroupClass().Update(GroupClass[0]);
                        }
                    }
                }
                else
                {
                    //，没有值班人员
                    if (role != null && role.Count > 0)
                    {
                        var userzz = new Bll.T_Sys_UserAccount().GetModelList("F_DeptId='" + ToDept + "' and F_DeleteFlag=0 " +
                            "and F_RoleId = '" + role.FirstOrDefault().F_RoleId + "'");
                        if (userzz != null && userzz.Count > 0)
                        {
                            user.Add(userzz.FirstOrDefault().F_UserCode);
                            user.Add("无值班人员,派送给" + GetDeptModel(ToDept) + "部门" + userzz.FirstOrDefault().F_UserName);
                        }
                        else
                        {
                            //无值班人员无班组长,随机派送
                            var userww = new Bll.T_Sys_UserAccount().GetModelList("F_DeptId='" + ToDept + "' and F_DeleteFlag=0 ");
                            if (userww != null && userww.Count > 0)
                            {
                                user.Add(userww.FirstOrDefault().F_UserCode);
                                user.Add("无值班人员无班组长,随机派送给" + GetDeptModel(ToDept) + "部门" + userww.FirstOrDefault().F_UserName);
                            }

                        }
                    }
                }
            }
            else
            {
                //没有班别
                if (role != null && role.Count > 0)
                {
                    var userzz = new Bll.T_Sys_UserAccount().GetModelList("F_DeptId='" + ToDept + "' and F_DeleteFlag=0 " +
                        "and F_RoleId = '" + role.FirstOrDefault().F_RoleId + "'");
                    if (userzz != null && userzz.Count > 0)
                    {
                        user.Add(userzz.FirstOrDefault().F_UserCode);
                        user.Add("无值班人员,派送给" + GetDeptModel(ToDept) + "部门" + userzz.FirstOrDefault().F_UserName);
                    }
                    else
                    {
                        //无值班人员无班组长,随机派送
                        var userww = new Bll.T_Sys_UserAccount().GetModelList("F_DeptId='" + ToDept + "' and F_DeleteFlag=0 ");
                        if (userww != null && userww.Count > 0)
                        {
                            user.Add(userww.FirstOrDefault().F_UserCode);
                            user.Add("无值班人员无班组长,随机派送给" + GetDeptModel(ToDept) + "部门" + userww.FirstOrDefault().F_UserName);
                        }

                    }
                }
            }

            return user;
        }

 

        // 返修 是申请人提交的返修
        //退回至维修部门班组长（角色），如果没有该角色退回到原来的处理人
        public ActionResult ReturnWorkOrder(string WorkOrderCode, string ReturnReason,int key,string value)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(WorkOrderCode);

            string str = "";
            if (!string.IsNullOrEmpty(ReturnReason))
            {
                str = "," + ReturnReason;
            }
            if (model != null && model.F_ApplicationDept.Trim() == User.F_DeptId.ToString())
            {
                //判断返工是不是规定的时间内，工单状态是已完结的工单

                List<Model.T_Sys_GongDan> listgd = gdbll.GetModelList(" F_GDId='" + model.F_WorkOrderCategory + "'");
                double limittime = listgd.First().F_RepairTimeLimit;
                if (model.F_Endtime.Value.AddHours(limittime) >= DateTime.Now)
                {
                    //提交返修，不新增处理记录了，20221213
                    //Model.T_FaultRepair_Process promodel = new Model.T_FaultRepair_Process();
                    //promodel.F_Isdelete = 0;
                    //promodel.F_MaintenanceDept = model.F_MaintenanceDept;//User.F_DeptId.ToString(); 
                    //promodel.F_Maintenancer = model.F_Maintenancer; //User.F_UserCode;
                    //promodel.F_ReturnReason =value+ ReturnReason;
                    //promodel.F_WorkOrderCode = WorkOrderCode;
                    //int proid = dealBll.Add(promodel);
    
                        AddOperatorLogAboutKey("提交了返修,原因："+value+ str, (int)EnumOperatorType.submitreturn, WorkOrderCode,value,key,ReturnReason);

                        //string sql = " select top 1 F_UserCode from T_Sys_UserAccount where F_RoleId in (select F_RoleId from T_Sys_Role where F_RoleCode = 'WXBZZ')";
                        try
                        {
                            string sql = "  select top 1 F_UserCode from T_Sys_UserAccount  where F_DeptId = '" + model.F_MaintenanceDept + "' and F_RoleId in (select F_RoleId from T_Sys_Role where F_RoleCode = 'WXBZZ')";
                            string usercode = DbHelperSQL.GetSingle(sql).ToString();
                            if (!string.IsNullOrEmpty(usercode))
                            {
                                model.F_Maintenancer = usercode;
                            }

                        }
                        catch 
                        {

                            
                        }
                        //提交返修，不新增处理记录了，20221213
                        //Model.T_FaultRepair_Process updatemodel = dealBll.GetModel(proid);
                        //updatemodel.F_Maintenancer = model.F_Maintenancer;
                        //dealBll.Update(updatemodel);

                        string s  = "\n返修原因：" + value+ str;                        

                        model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.receive;
                        model.F_ReturnNum += model.F_ReturnNum + 1;
                        model.F_UpdateTime = DateTime.Now;
                        baseBll.Update(model);

                        msg.AddInternalMessagesInfo("您有需要返修的工单，请及时处理", "您有需要返修的工单，请及时处理\n" + "工单编号:" + model.F_WorkOrderCode+s, model.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
            , 0, model.F_WorkOrderCode);
                        return Success("提交返修成功");
                
                }
                else
                {

                    return Error("已超出提交返修期限");
                }
            }
            return Error("暂时没有权限操作");
        }

        //申请人评价
        public ActionResult EvaluateWorkOrder(string WorkOrderCode, string EvaluateContent, int Attitude= 0, int Quality = 0, int Efficiency = 0)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(WorkOrderCode);
            Model.T_FaultRepair_Evaluate evamodel = new Model.T_FaultRepair_Evaluate();
            if (model != null)
            {
                if (model.F_ApplicationDept.Trim() == User.F_DeptId.ToString())
                {

                    evamodel.F_EvaluateContent = EvaluateContent;
                    evamodel.F_Quality = Quality;
                    evamodel.F_Attitude = Attitude;

                    evamodel.F_Efficiency = Efficiency;
                    evamodel.F_Evaluator = User.F_UserCode;
                    evamodel.F_EvaluationTime = DateTime.Now;
                    evamodel.F_Isdelete = 0;
                    evamodel.F_WorkOrderCode = WorkOrderCode;
                    BLL.T_FaultRepair_Evaluate evabll = new BLL.T_FaultRepair_Evaluate();
                    if (evabll.Add(evamodel) > 0)
                    {
                        model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.finish;
                        model.F_UpdateTime = DateTime.Now;
                        //评价=自动确认耗材
                        if (model.F_ConfirmEquip == 1)
                        {
                            model.F_ConfirmEquip = 2;
                        }
                 
                        model.F_Score = Attitude + Quality + Efficiency;                       
                        AddOperatorLog("评价了工单", (int)EnumOperatorType.evaluate, model.F_WorkOrderCode);

                        if (Attitude < 3 || Quality < 3 || Efficiency < 3)
                        {
                            model.MYD = 2;
                            msg.AddInternalMessagesInfo("您有工单被差评", "您有工单被差评\n" + "工单编号:" + model.F_WorkOrderCode + "\n差评原因:" + EvaluateContent, model.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
                       , 0, model.F_WorkOrderCode);
                        }
                        else if (Attitude == 3 || Quality == 3 || Efficiency == 3)
                        {
                            model.MYD = 1;
                        }
                        else
                        {
                            model.MYD = 0;
                        }
                        baseBll.Update(model);
                        #region 评价的时候如果有协作工单，协作工单评价数据和主工单保持一致，同时需要记录操作流程
                        if (!string.IsNullOrEmpty(model.F_InternalWorkOrderCode))
                        {

                            string[] codes = model.F_InternalWorkOrderCode.Split(',');
                            foreach (string item in codes)
                            {
                                var intermodel = baseBll.GetModel(item);
                                Model.T_FaultRepair_Evaluate evamodel1 = new Model.T_FaultRepair_Evaluate();
                                evamodel1 = evamodel;
                                evamodel.F_WorkOrderCode = item;
                                evabll.Add(evamodel1);
                                if (Attitude < 3 || Quality < 3 || Efficiency < 3)
                                {
                                    intermodel.MYD = 2;
                                    msg.AddInternalMessagesInfo("您有工单被差评", "您有工单被差评\n" + "工单编号:" + item + "\n差评原因:" + EvaluateContent, intermodel.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
                   , 0, item);
                                }
                                else if (Attitude == 3 || Quality == 3 || Efficiency == 3)
                                {
                                    model.MYD = 1;
                                }
                                else
                                {
                                    model.MYD = 0;
                                }
                                intermodel.F_Score = Attitude + Quality + Efficiency;
                                //评价=自动确认耗材
                                if (intermodel.F_ConfirmEquip == 1)
                                {
                                    intermodel.F_ConfirmEquip = 2;
                                }


                                baseBll.Update(intermodel);
                            
                                AddOperatorLog("评价了工单", (int)EnumOperatorType.evaluate, item);
                            }
                        }
                        if (!string.IsNullOrEmpty(model.F_ExternalWorkOrderCode))
                        {

                            string[] codes = model.F_ExternalWorkOrderCode.Split(',');
                            foreach (string item in codes)
                            {
                                var extmodel = baseBll.GetModel(item);
                                Model.T_FaultRepair_Evaluate evamodel1 = new Model.T_FaultRepair_Evaluate();
                                evamodel1 = evamodel;
                                evamodel.F_WorkOrderCode = item;
                                evabll.Add(evamodel1);
                                if (Attitude < 3 || Quality < 3 || Efficiency < 3)
                                {
                                    extmodel.MYD = 2;
                                    msg.AddInternalMessagesInfo("您有工单被差评", "您有工单被差评\n" + "工单编号:" + item + "\n差评原因:" + EvaluateContent, extmodel.F_Maintenancer, User.F_UserCode, EnumSmsType.repair
                   , 0, item);
                                }
                                else if (Attitude == 3 || Quality == 3 || Efficiency == 3)
                                {
                                    model.MYD = 1;
                                }
                                else
                                {
                                    model.MYD = 0;
                                }
                                extmodel.F_Score = Attitude + Quality + Efficiency;
                                //评价=自动确认耗材
                                if (extmodel.F_ConfirmEquip == 1)
                                {
                                    extmodel.F_ConfirmEquip = 2;
                                }

                                baseBll.Update(extmodel);
                                AddOperatorLog("评价了工单", (int)EnumOperatorType.evaluate, item);
                            }
                        }
                        #endregion

                        return Success("评价成功");
                    }
                    return Error("评价失败");
                }
                else
                {
                    return Error("没有权限评价");
                }
            }
            return Error("评价失败");

        }


        /// <summary>
        /// 获取枚举值的描述属性
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        private string GetEnumDescription(Enum enumValue)
        {
            string value = enumValue.ToString();
            FieldInfo field = enumValue.GetType().GetField(value);
            object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);  //获取描述属性
            if (objs == null || objs.Length == 0)  //当描述属性没有时，直接返回名称
                return value;
            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
            return descriptionAttribute.Description;

        }


        #region 添加操作记录
        public bool AddOperatorLogNew(string content, int type, string workordercode,string usercode)
        {
            Model.T_FaultRepair_OperationLog model = new Model.T_FaultRepair_OperationLog();
            model.F_LogContent = content;
            model.F_OperationTime = DateTime.Now;
            model.F_OperationType = type;
            model.F_Operator = usercode;
            model.F_WorkOrderCode = workordercode;
            logBll.Add(model);
            return true;
        }
        public bool AddOperatorLog(string content, int type, string workordercode)
        {
            Model.T_FaultRepair_OperationLog model = new Model.T_FaultRepair_OperationLog();
            model.F_LogContent = content;
            model.F_OperationTime = DateTime.Now;
            model.F_OperationType = type;
            model.F_Operator = User.F_UserCode;
            model.F_WorkOrderCode = workordercode;
            logBll.Add(model);
            return true;
        }

        public bool AddEvaluateOperatorLog(string content, int type, string workordercode)
        {
            Model.T_FaultRepair_OperationLog model = new Model.T_FaultRepair_OperationLog();
            model.F_LogContent = content;
            model.F_OperationTime = DateTime.Now;
            model.F_OperationType = type;
            model.F_Operator = "";
            model.F_WorkOrderCode = workordercode;
            logBll.Add(model);
            return true;
        }
        public bool AddOperatorLogAboutKey(string content, int type, string workordercode,string value,int key,string enterreason)
        {
            Model.T_FaultRepair_OperationLog model = new Model.T_FaultRepair_OperationLog();
            model.F_LogContent = content;
            model.F_OperationTime = DateTime.Now;
            model.F_OperationType = type;
            model.F_Operator = User.F_UserCode;
            model.F_WorkOrderCode = workordercode;
            model.F_AboutKey = key;
            model.F_AboutReason = value;
            model.F_EnterReason = enterreason;
            logBll.Add(model);
            return true;
        }


        public void AddAddlog(string workordercode)
        {
            AddOperatorLog("创建报修工单", (int)EnumOperatorType.add, workordercode);
        }

        public void AddAssignlog(string workordercode, string dept, string maintenancer)
        {
            AddOperatorLog("指派工单给" + GetDeptModel(dept) + "部门" + GetUserModel(maintenancer), (int)EnumOperatorType.assign, workordercode);

        }
        public void AddInternalasslog(string workordercode, string newworkordercode)
        {

            AddOperatorLog("创建内协作工单" + newworkordercode, (int)EnumOperatorType.internalassistance, workordercode);
        }
        public void AddExternalasslog(string workordercode, string newworkordercode)
        {
            AddOperatorLog("创建外协作工单" + newworkordercode, (int)EnumOperatorType.externalassistance, workordercode);

        }

        [AllowAnonymous]
        public bool AddAutoAssignlog(string workordercode, string dept, string maintenancer)
        {
            Model.T_FaultRepair_OperationLog model = new Model.T_FaultRepair_OperationLog();
            model.F_LogContent = "超过十分钟未接单，自动指派工单给" + GetDeptModel(dept) + "部门" + GetUserModel(maintenancer);
            model.F_OperationTime = DateTime.Now;
            model.F_OperationType = (int)EnumOperatorType.assign;
            model.F_Operator = "";
            model.F_WorkOrderCode = workordercode;
            logBll.Add(model);
            return true;
        }

   
        #endregion


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

            if (!string.IsNullOrWhiteSpace(deptId))
            {
                sql += " and F_DeptId='" + deptId + "'";
            }
            if (string.IsNullOrWhiteSpace(sql))
                return "";

            var role = departmentBLL.GetModelList(sql).FirstOrDefault();
            string name = role.F_DeptName;

            return name;
        }

        public string GetUserModel(string usercode = "")
        {
            string sql = " 1=1 ";

            if (!string.IsNullOrWhiteSpace(usercode))
            {
                sql += " and F_UserCode='" + usercode + "'";
            }
            if (string.IsNullOrEmpty(usercode))
                return "";

            Model.T_Sys_UserAccount ua = new Bll.T_Sys_UserAccount().GetModelList(sql).FirstOrDefault();
            if (ua != null)
            {
                return ua.F_UserName + "(" + usercode + ")";

            }

            return "";

        }



      
      
       
       

      
     

        #region 我的提交页面的操作

        //申请人撤回（未指派的工单可撤回，工单状态“待提交”）
        public ActionResult MyRetract(string workordercode,string BackReason)
        {

            Model.T_FaultRepair_Base model = baseBll.GetModel(workordercode);
            if (model == null)
            {
                return Error("没有获取到工单号");
            }
            if (model.F_WorkOrderState == 0)
            {
                string s = "";
                if (!string.IsNullOrEmpty(BackReason))
                {
                    s += ",撤回原因:" + BackReason;
                }
                model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.waitsubmit;
                baseBll.Update(model);
                AddOperatorLog(User.F_UserName + "撤回了工单"+s, (int)EnumOperatorType.myretract, model.F_WorkOrderCode);
                return Success("撤回操作成功");

            }
            else
            {
                return Error("不能撤回");
            }

        }

        //我的提交里编辑工单
        /// <summary>
        ///编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult MyUpdateFaultRepairWorkOrder(T_FaultRepairBaseinput input)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(input.WorkOrderCode);
            if (string.IsNullOrEmpty(input.WorkOrderCategory))
            {
                return Error("工单类别不能为空！");
            }


            model.F_WorkOrderCategory = input.WorkOrderCategory;
            model.F_Content = input.Content;
            model.F_PlaceOfRepair = input.PlaceOfRepair;
            model.F_File = input.File;
            model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.neworder;

            model.F_UpdateTime = DateTime.Now;

            if (baseBll.Update(model))
            {

                AddOperatorLog(User.F_UserName + "编辑了工单", (int)EnumOperatorType.update, model.F_WorkOrderCode);

                return Success("编辑成功！");
            }
            else return Error("编辑失败！");

        }


        #endregion

        //延期 只有业务咨询和故障报修有延期按钮
        //接单人在接单之后，如果该工单类型上设置的“可延期次数”大于0显示“延期”按钮；点击延期按钮进行验证是否超过设定的延期次数，超过提醒“已超过规定延迟次数”
        //操作流程记录延期
        public ActionResult frReplay(string workordercode, string days, string type, string workordercategory,string reason,int key, string value)
        {
            Model.T_Sys_GongDan gdmodel = gdbll.GetModel(Convert.ToInt32(workordercategory));
            Model.T_Wo_CommonBase model = cbbll.GetModel(workordercode);

            //if (!string.IsNullOrEmpty(reason))
            //{
            //    reason = "," + reason;
            //}
            //string strreason  = ",原因："+value+  reason;

            string strreason = ",原因:" + value;
            if (!string.IsNullOrEmpty(reason))
            {
                strreason = strreason + "，" + reason;
            }




            if (gdmodel.F_CanReplayCount > 0)
            {

                if (gdmodel.F_CanReplayCount >= model.F_ReplayCount + 1)
                {

                    //业务咨询流程延期
                    if (type == "1000")
                    {
                        Model.T_Con_WorkOrder cwmodel = cwbll.GetModelByCode(workordercode);

                        cwmodel.F_ReplayCount = cwmodel.F_ReplayCount + 1;
                        cwbll.Update(cwmodel);
                       

                        var itemid = Addlogbll.AddLogAboutKey(cwmodel.F_ID, 0, 0, User.F_UserName + "(" + User.F_UserCode + ")" + "给工单延期" + days + "h"+ strreason, (int)EnumItemType.Delay, 14, "", 0, User.F_UserCode,key,value, reason);
                    }
                    //故障报工单延期修
                    if (type == "3000")
                    {
                        Model.T_FaultRepair_Base fbmodel = baseBll.GetModel(workordercode);
                        fbmodel.F_ReplayCount = fbmodel.F_ReplayCount + 1;
                        baseBll.Update(fbmodel);

                        AddOperatorLogAboutKey("给工单延期" + days+"h"+ strreason, (int)EnumOperatorType.replay, workordercode, value, key, reason);

                        //AddOperatorLogAboutKey("退回了工单" + s, (int)EnumOperatorType.back, model.F_WorkOrderCode, value, key, BackReason);

                    }

                    ////综合调度延期
                    //if (type == "2000")
                    //{
                    //    Model.T_IntegratedScheduling_Base ismodel = isbll.GetModel(workordercode);
                    //    ismodel.F_ReplayCount = ismodel.F_ReplayCount + 1;
                    //    isbll.Update(ismodel);

                    //    schcon.AddOperatorLogAboutKey("给工单延期" + days + "h" + strreason, (int)EnumOperatorType.replay, workordercode,key, value, reason);


                    //}


                    return Success("成功延期");

                }
                else
                {
                    return Error("已超过设定延迟次数");
                }

            }
            return Error("已超过设定延期次数");

        }


        /// <summary>
        /// 申请人确认耗材
        /// </summary>
        /// <returns></returns>
        public ActionResult ConfirmEquips(string workordercode,string reason, int confirmtype = 1)
        {
            Model.T_FaultRepair_Base model = baseBll.GetModel(workordercode);
            string logs = "";
            if (!string.IsNullOrEmpty(reason))
            {
                logs = "，原因：" + reason;
            }
            if (confirmtype == 0)
            {
               
                model.F_ConfirmEquip = 0;
                model.F_WorkOrderState = (int)EnumFaultRepairWorkOrderState.dealing;
                AddOperatorLog("耗材确认有误"+logs, (int)EnumOperatorType.confirm, workordercode);
            }
            else
            {
                model.F_ConfirmEquip = 2;
                model.F_WorkOrderState =(int) EnumFaultRepairWorkOrderState.dealed;
                AddOperatorLog("确认耗材无误" + logs, (int)EnumOperatorType.confirm, workordercode);
            }
            baseBll.Update(model);           

            return Success("确认耗材接口");

        }


        //发送超时未接单的消
        //20222031更正为：即将超时 距离截止日期还有十分钟 还未接单的发消息给组长
        public ActionResult AutoSendOverTimeMsg()
        {
            string sql = "  select F_Deadline,F_WorkOrderState, * from T_FaultRepair_Base where F_WorkOrderState=1  and DATEDIFF(mi, GETDATE(), F_Deadline)< 10 and DATEDIFF(mi, GETDATE(), F_Deadline)> 0";
            DataTable dt = DbHelperSQL.Query(sql).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    //根据处理部门获取班组长 WXBZZ
                    var dtuser = DbHelperSQL.Query(" select  top 1 F_usercode from T_Sys_UserAccount where F_DeptId='' and   F_RoleId=(select F_roleid from T_Sys_Role where F_RoleCode='WXBZZ')").Tables[0];

                    if (dtuser != null && dtuser.Rows.Count > 0)
                    {
                        string message = "";
                        var dicvalue = new Model.T_Sys_GongDan();
                        dicvalue = new Bll.T_Sys_GongDan().GetModel(Convert.ToInt32(item["F_WorkOrderCategory"].ToString()));
                        if (dicvalue != null)
                        {
                            message = ",工单类型:故障报修/" + dicvalue.F_Name;
                        }
                        message += ",报修科室：" + GetParentDeptName(Convert.ToInt32( item["F_ApplicationDept"].ToString()));
                        message += ",工单内容：" + item["F_Content"].ToString();
                        message += ",相关人员：" + GetUserModel(item["F_Maintenancer"].ToString());

                        msg.AddInternalMessagesInfo("您部门下有工单即将超时未接单", "您部门下有工单即将超时未接单\n" + "工单编号:" + item["F_WorkOrderCode"].ToString(), dtuser.Rows[0]["F_usercode"].ToString(), User.F_UserCode, EnumSmsType.repair
                 , 0, item["F_WorkOrderCode"].ToString());
                    }
               }



            }

            return Success("发送超时未接单的消息成功");
        }
 

        StringBuilder returnname = new StringBuilder();
     
        [AllowAnonymous]
      
        public string GetParentDeptName(int deptid)
        {
            var model = departmentBLL.GetModel(deptid);
            if (model != null)
            {
                returnname.Insert(0, model.F_DeptName);
                returnname.Insert(0, "/");
                if (model.F_ParentId != 0)
                {
                    GetParentDeptName(model.F_ParentId.Value);
                }
                if (model.F_ParentId == 0)
                {
                    string sql = " select T_Woname from T_Wowo_repairyq where T_Woid='" + model.T_Woid + "'";
                  string yqname=  DbHelperSQL.GetSingle(sql).ToString();
                    returnname.Insert(0, yqname);                   
                }


            }
            return returnname.ToString();
        }


        /// <summary>
        /// 基建后勤类型,10分钟内未接单转派给基建和后勤保障部的值班人员（根据排班表）
        /// </summary>
        /// <returns></returns>
        public ActionResult AutoChangeDealMan()
        {
            string sql = " select F_GDId from T_Sys_GongDan where F_Name='基建后勤类'";
            int gdid =Convert.ToInt32( DbHelperSQL.GetSingle(sql));


         
            if (gdid > 0)
            {
                string allgd = "  select * from T_FaultRepair_Base where F_accepttime is null and   DATEDIFF(MINUTE, F_AssignTime, GETDATE()) > 10 and        F_WorkOrderCategory in (select * from dbo.getvalueid('" + gdid + "'))";

                DataTable dt = DbHelperSQL.Query(allgd).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    string sqldept = " select F_DeptId from T_Sys_Department where F_DeptCode='HQBZ'";

                    int deptid = Convert.ToInt32(DbHelperSQL.GetSingle(sqldept));
                    List<Model.T_Sys_GroupClass> modellist = new List<Model.T_Sys_GroupClass>();
                    if (deptid > 0)
                    {
                          modellist = gcBll.GetModelList("F_IsDelete = 0   and F_Date = CONVERT(varchar, GETDATE(), 120)  and F_ClassCode in (select F_Id from t_sys_class where F_IsDelete = 0 and CONVERT(varchar, GETDATE(), 108) between F_InTime and F_OutTime and F_DeptId = '" + deptid + "')");                 
                    }

                    foreach (DataRow item in dt.Rows)
                    {
                     Model.T_FaultRepair_Base frmodel=    baseBll.GetModel(item["F_WorkOrderCode"].ToString());
                        if (modellist.Count > 0)
                        {
                           var  shaixuanlist = modellist.Where(x => x.F_UserCode != frmodel.F_Maintenancer).ToList();
                            if (shaixuanlist.Count > 0)
                            {
                                frmodel.F_AssignTime = DateTime.Now;
                                frmodel.F_Maintenancer = shaixuanlist.First().F_UserCode;
                                frmodel.F_MaintenanceDept = deptid.ToString();
                                baseBll.Update(frmodel);

                                AddAutoAssignlog(item["F_WorkOrderCode"].ToString(), deptid.ToString(), frmodel.F_Maintenancer);

                            }

                        }

                    }
                }
                return Success("执行成功");

            }
            return Error("基建后勤类型不存在");
        }


        //报修人的列表  已上报 待评价 已完结


        //public ActionResult MyCreateList()
        //{

        //    DataTable dt = new DataTable();
        //    string sql = " and F_IsDelete=0 and F_CreateUser='" + User.F_UserCode + "'";


        //    string strpageindex = RequestString.GetQueryString("page");
        //    int pageindex = 1;
        //    string strpagesize = RequestString.GetQueryString("pagesize");
        //    int pagesize = 10;
        //    //待处理传2    已处理传3
        //    int strstate = RequestString.GetInt("state", -1);
        //    string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));

        //    string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));

        //    string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
        //    string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
        //    string strworkcode = HttpUtility.UrlDecode(RequestString.GetQueryString("workordercode"));


        //    #region 搜索条件
        //    if (strpageindex.Trim() != "")
        //    {
        //        pageindex = Convert.ToInt32(strpageindex);
        //    }

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


        //    if (strname.Trim() != "" && strname != "undefined")
        //    {
        //        sql += " and F_Applicant = '" + strname + "' ";
        //    }
        //    if (strtel.Trim() != "" && strtel != "undefined")
        //    {
        //        sql += " and (F_Applicantsphone  like '%" + strtel + "%' or F_Phone like '%" + strtel + "%') ";
        //    }
        //    if (strworkcode.Trim() != "" && strworkcode != "undefined")
        //    {
        //        sql += " and F_WorkOrderCode like'%" + strworkcode + "%'";
        //    }

        //    if (strstarttime.Trim() != "" && strstarttime != "undefined")
        //    {
        //        if (strendtime.Trim() != "" && strendtime != "undefined")
        //        {
        //            sql += " and F_CreateTime  between   '" + strstarttime +
        //                     "' AND  '" + strendtime + "'";
        //        }
        //        else
        //        {
        //            sql += " and F_CreateTime>='" + strstarttime + "' ";
        //        }
        //    }
        //    else
        //    {
        //        if (strendtime.Trim() != "" && strendtime != "undefined")
        //        {
        //            sql += " and F_CreateTime<='" + strendtime + "' ";
        //        }
        //    }
        //    #endregion
        //    //报修人 待处理2 已处理3 
        //    switch (strstate)
        //    {
        //        case 2:
        //            sql += " and F_WorkOrderState<=3";
        //            break;

        //        case 3:
        //            sql += " and F_WorkOrderState>3";
        //            break;

        //    }
        //    int recordCount = 0;
        //    dt = Bll.PagerBll.GetListPager
        //                                    ("T_FaultRepair_Base ",
        //                                      "F_WorkOrderId",
        //                                      "*,[dbo].[GetUserName](F_Maintenancer) Maintenancer,[dbo].[GetUserName](F_Applicant) Applicant",
        //                                      sql,
        //                                      "order by F_WorkOrderId desc",
        //                                      pagesize,
        //                                      pageindex,
        //                                      true,
        //                                      out recordCount
        //                                    );
        //    dt.Columns.Add("GapTime", typeof(string));//执行时限

        //    dt.Columns.Add("AssistanceState", typeof(string));//协作工单的状态
        //    dt.Columns.Add("StateName", typeof(object));//展示的工单状态值

        //    dt.Columns.Add("Buttons", typeof(object));//操作按钮
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        #region 执行时限 不是已完成的工单 展示这个字段 
        //        if (Convert.ToInt32(dr["F_WorkOrderState"]) < 3)
        //        {
        //            if (!string.IsNullOrEmpty(dr["F_Deadline"].ToString()))
        //            {
        //                DateTime deadline = Convert.ToDateTime(dr["F_Deadline"]);
        //                TimeSpan ts = deadline.Subtract(DateTime.Now);
        //                double tss = double.Parse(Math.Round(ts.TotalSeconds, 0).ToString());
        //                if (tss < 0) { tss = -tss; }
        //                string gshsj = DateTimeConvert.parseTimeSeconds(tss, 1);
        //                if (deadline > DateTime.Now)
        //                {
        //                    dr["GapTime"] = "剩余" + gshsj;
        //                }
        //                else
        //                {
        //                    dr["GapTime"] = "超时" + gshsj;
        //                }
        //            }
        //        }
        //        #endregion


        //        #region  展示的工单状态
        //        if (Convert.ToInt32(dr["F_WorkOrderState"]) == (int)EnumFaultRepairWorkOrderState.neworder || Convert.ToInt32(dr["F_WorkOrderState"]) == (int)EnumFaultRepairWorkOrderState.receive)
        //        {
        //            dr["StateName"] = "待接单";
        //        }
        //        else if (Convert.ToInt32(dr["F_WorkOrderState"]) == (int)EnumFaultRepairWorkOrderState.dealing)
        //        {
        //            dr["StateName"] = "已接单";
        //        }
        //        else if (Convert.ToInt32(dr["F_WorkOrderState"]) == (int)EnumFaultRepairWorkOrderState.dealed)
        //        {
        //            dr["StateName"] = "待评价";
        //        }
        //        else {

        //            dr["StateName"] = "已完成";
        //        }
        //        #endregion

        //        #region 操作按钮
        //        var btns = new List<FaultButtonGroup.button>();

        //        //待接单 已接单 -自行解决

        //        if (Convert.ToInt32(dr["F_WorkOrderState"]) == (int)EnumFaultRepairWorkOrderState.neworder ||
        //            Convert.ToInt32(dr["F_WorkOrderState"]) == (int)EnumFaultRepairWorkOrderState.receive ||
        //             Convert.ToInt32(dr["F_WorkOrderState"]) == (int)EnumFaultRepairWorkOrderState.dealing
        //            )
        //        {
        //            btns.Add(FaultButtonGroup.solve());
        //        }
        //        //待评价  评价
        //      else  if (Convert.ToInt32(dr["F_WorkOrderState"]) == (int)EnumFaultRepairWorkOrderState.dealed)
        //        {
        //            btns.Add(FaultButtonGroup.evaluate());
        //        }
        //       else if (Convert.ToInt32(dr["F_WorkOrderState"]) == (int)EnumFaultRepairWorkOrderState.exceptionended ||
        //            Convert.ToInt32(dr["F_WorkOrderState"]) == (int)EnumFaultRepairWorkOrderState.finish
        //            )
        //        {
        //            btns.Add(FaultButtonGroup.returndeal());
        //        }


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


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



        //}




        //工单详情



        #region

        //故障报修综合报表

        public ActionResult ExportList()
        {
            string sql = " and F_IsDelete=0 ";

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


            //创建时间 报修人 工单类别 工单状态 维修人 调度人
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

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

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

            string applicant = HttpUtility.UrlDecode(RequestString.GetQueryString("applicant"));
            string maintenancer = HttpUtility.UrlDecode(RequestString.GetQueryString("maintenancer"));

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

            Bll.T_Sys_UserAccount blluser = new Bll.T_Sys_UserAccount();

            List<Model.T_Sys_UserAccount> listuser = blluser.GetModelList("F_DeleteFlag=0");

            if (!string.IsNullOrEmpty(createuser))
            {
                try
                {
                    int usercode = Convert.ToInt32(createuser);
                    sql += " and F_AssignUser='" + usercode + "'";
                }
                catch (Exception)
                {

                    Model.T_Sys_UserAccount model = listuser.Find(x => x.F_UserName == createuser);
                    if (model != null)
                    {
                        sql += " and F_AssignUser='" + model.F_UserCode + "'";

                    }
                }
            }

            if (!string.IsNullOrEmpty(maintenancer))
            {
                try
                {
                    int usercode = Convert.ToInt32(maintenancer);
                    sql += " and F_Maintenancer='" + usercode + "'";
                }
                catch (Exception)
                {

                    Model.T_Sys_UserAccount model = listuser.Find(x => x.F_UserName == maintenancer);
                    if (model != null)
                    {
                        sql += " and F_Maintenancer='" + model.F_UserCode + "'";

                    }
                }
            }

            if (!string.IsNullOrEmpty(applicant))
            {
                try
                {
                    int usercode = Convert.ToInt32(applicant);
                    sql += " and F_Applicant='" + usercode + "'";
                }
                catch (Exception)
                {

                    Model.T_Sys_UserAccount model = listuser.Find(x => x.F_UserName == applicant);
                    if (model != null)
                    {
                        sql += " and F_Applicant='" + model.F_UserCode + "'";

                    }
                }
            }


            #region 搜索条件
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

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


            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                if (strendtime.Trim() != "" && strendtime != "undefined")
                {
                    sql += " and F_CreateTime  between   '" + strstarttime +
                             "' AND  '" + strendtime + "'";
                }
                else
                {
                    sql += " and F_CreateTime>='" + strstarttime + "' ";
                }
            }
            else
            {
                if (strendtime.Trim() != "" && strendtime != "undefined")
                {
                    sql += " and F_CreateTime<='" + strendtime + "' ";
                }
            }
            #endregion

            if (strstate > 0)
            {
                sql += " and F_WorkOrderState='" + strstate + "'";
            }

            if (applicantdept > 0)
            {
                sql += " and F_ApplicationDept='" + applicantdept + "'";
            }

            if (category > 0)
            {
                sql += " and F_WorkOrderCategory='" + category + "'";

            }
            int recordCount = 0;

            if (isexport == 1)
            {
                //执行时限 服务评价
                string exportsql = "select F_WorkOrderCode 工单编号,F_CreateTime 创建时间,dbo.GetDepName (F_ApplicationDept) 报工科室,[dbo].[GetUserName](F_Applicant) 报修人,[dbo].[GetGongDanNameByID](F_WorkOrderCategory) 工单类别, F_Content 工单内容,(case  F_WorkOrderState when 0 then '新工单' when 1 then '待查收'when 2 then '待完成'when 3 then '已处理'when 4 then '异常完结'when 5 then '已完结' when 6 then '已到达'  else '' end ) 工单状态,[dbo].[GetUserName](F_Maintenancer) 维修员,F_Endtime 维修时间,dbo.[GetConvertSecond](DATEDIFF(ss,F_CreateTime,F_Endtime))   工单耗时,[dbo].[GetGapTime](F_Deadline,F_Endtime) 执行时限, F_Score 服务评价,dbo.GetUserName(F_AssignUser) 调度人 from T_FaultRepair_Base where 1=1" + sql;

                var dtdc = DbHelperSQL.Query(exportsql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("故障报修综合报表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }

            }
            DataTable datatable = Bll.PagerBll.GetListPager
                                            ("T_FaultRepair_Base ",
                                              "F_WorkOrderId",
                                              "F_WorkOrderId,F_WorkOrderCode ,F_CreateTime  ,dbo.GetDepName(F_ApplicationDept) deptname ,[dbo].[GetUserName](F_Applicant) applicantname  ,F_WorkOrderCategory  , F_Content  ,(case  F_WorkOrderState when 0 then '新工单' when 1 then '待查收'when 2 then '待完成'when 3 then '已处理'when 4 then '异常完结'when 5 then '已完结' when 6 then '已到达'  else '' end )  workorderstatename,[dbo].[GetUserName](F_Maintenancer) maintenancer,F_Endtime  ,dbo.[GetConvertSecond](DATEDIFF(ss,F_CreateTime,F_Endtime)) spendtime  ,[dbo].[GetGapTime](F_Deadline,F_Endtime) gaptime , F_Score  ,dbo.GetUserName(F_AssignUser)   createname",
                                              sql,
                                              "order by F_WorkOrderId desc",
                                              pagesize,
                                              pageindex,
                                              true,
                                              out recordCount
                                            );


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



        }

        //筛选项：申请科室，维修人，派单时间
        //        1	1269425	病理科 高低压配电   科教中心三楼病理科部分房间不通电 送电    已完成 牛明飞	1	2022-12-16 19:03:59
        //序号 工单编号    报工科室 工单类别    工单内容 工单状态    维修材料 规格型号    数量 单价  小计 维修员 分值 派出时间
        //故障报修工单 包括耗材
        [AllowAnonymous]
        public ActionResult AboutEquipExportList()
        {
            string sql = " and F_IsDelete=0 and F_Maintenancer is not null AND F_Maintenancer !='' and F_WorkOrderState=5 ";

            int isexport = RequestString.GetInt("isexport", -1);
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            int applicantdept = RequestString.GetInt("applicantdept", -1);
            string maintenancer = HttpUtility.UrlDecode(RequestString.GetQueryString("maintenancer"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

            if (!string.IsNullOrEmpty(maintenancer))
            {
                try
                {
                    int usercode = Convert.ToInt32(maintenancer);
                    sql += " and F_Maintenancer='" + usercode + "'";
                }
                catch (Exception)
                {                    
                }
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                if (strendtime.Trim() != "" && strendtime != "undefined")
                {
                    sql += " and F_AssignTime  between   '" + strstarttime +
                             "' AND  '" + strendtime + "'";
                }
                else
                {
                    sql += " and F_AssignTime>='" + strstarttime + "' ";
                }
            }
            else
            {
                if (strendtime.Trim() != "" && strendtime != "undefined")
                {
                    sql += " and F_AssignTime<='" + strendtime + "' ";
                }
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            if (isexport == 1)
            {
                
                string exportsql = "SELECT  ROW_NUMBER() OVER(ORDER BY F_CreateTime desc)  序号, F_WorkOrderCode ,dbo.GetDepName( F_ApplicationDept) ,[dbo].[GetGongDanNameByID](F_WorkOrderCategory) 工单类别,F_Content,'已完成' F_Status ," +
                    "dbo.GetUserName(F_Maintenancer), isnull(F_Score, '') ,F_AssignTime  ,F_ConfirmEquip   FROM [RMYY_CallCenter].[dbo].[T_FaultRepair_Base] where 1=1" + sql + "order by F_WorkOrderId desc";

                var dtdc = DbHelperSQL.Query(exportsql).Tables[0];
                string[] cols = { "序号", "工单编号", "报工科室", "工单类别", "工单内容", "工单状态", "维修材料", "规格型号", "数量", "单价", "小计", "维修员", "分值", "派出时间"};

                //'工单编号','报工科室','工单类别', '工单内容','工单状态','' '维修材料','' '规格型号','' '	数量','' '单价','' '小计' '维修员' '分值' '派出时间'

                dtdc.Columns.Add("Equips", typeof(object));

                foreach (DataRow dr in dtdc.Rows)
                {
                    if (dr["F_ConfirmEquip"].ToString() == "2")
                    {
                        dr["Equips"] = GetEquipData(dr["F_WorkOrderCode"].ToString());
                    }
                }
                dtdc.Columns.Remove("F_ConfirmEquip");
                var msg = new NPOIHelper().AboutEquipExportToExcel("故障报修综合报表", dtdc, cols);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }

            }
            DataTable datatable = Bll.PagerBll.GetListPager
                                            ("T_FaultRepair_Base ",
                                              "F_WorkOrderId",
                                              "F_WorkOrderCode ,dbo.GetDepName( F_ApplicationDept) ,[dbo].[GetGongDanNameByID](F_WorkOrderCategory) ,F_Content ,'已完成' F_Status,dbo.GetUserName(F_Maintenancer)  Maintenancer, isnull(F_Score, '')  Score,F_AssignTime   ,F_ConfirmEquip  ",
                                              sql,
                                              "order by F_WorkOrderId desc",
                                              pagesize,
                                              pageindex,
                                              true,
                                              out recordCount
                                            );

            datatable.Columns.Add("Equips", typeof(object));

            foreach (DataRow dr in datatable.Rows)
            {
                if (dr["F_ConfirmEquip"].ToString()=="2")
                {
                    dr["Equips"] = GetEquipData(dr["F_WorkOrderCode"].ToString());
                }
            }

            

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


        public DataTable GetEquipData(string workordercode)
        {
            string sql = " select  top 1 F_EquipDetail  from T_FaultRepair_Process  where F_WorkOrderCode = '"+workordercode+"'  order by F_ProcessingTime desc";

            var  obj1 = DbHelperSQL.GetSingle(sql);
            string obj = "";
            if (obj1 != null)
            {
                obj = obj1.ToString();
            }

            DataTable dt = new DataTable();
            if (string.IsNullOrEmpty(obj))
            {
                return dt;
            }


             dt = DbHelperSQL.Query("select F_EquipName, F_EquipNumber, F_EquipAmount,F_EquipPrice,F_EquipAmount*F_EquipPrice Allprice from T_InvolvedEquip_RepairProcess where F_ID in  (SELECT COL FROM DBO.SplitToNvarchar('" + obj+"', ','))").Tables[0];            

            return dt;
        }


        #endregion
    }
}
