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.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers
{
    public class SchedulingController : BaseController
    {
        private BLL.T_IntegratedScheduling_Base baseBll = new BLL.T_IntegratedScheduling_Base();
        Bll.T_Sys_GongDan gdbll = new Bll.T_Sys_GongDan();
        private Bll.T_Sys_Department departmentBLL = new Bll.T_Sys_Department();
        private static BLL.T_IntegratedScheduling_OperationLog logBll = new BLL.T_IntegratedScheduling_OperationLog();
        private BLL.T_IntegratedScheduling_Detail detailBll = new BLL.T_IntegratedScheduling_Detail();
        private Bll.T_Sys_SystemConfig configBll = new Bll.T_Sys_SystemConfig();
        private BLL.T_IntegratedScheduling_Process proBll = new BLL.T_IntegratedScheduling_Process();


        private static InternalMessagesController msg = new InternalMessagesController();
        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)
            {
                // dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
                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;
        }
        public DataTable GetPSInfo(string strworkorderid)
            {
            string pssql = "select * from T_IntegratedScheduling_Detail where F_WorkOrderCode='" + strworkorderid + "'";
            DataTable psdt = DbHelperSQL.Query(pssql).Tables[0];

            return psdt;
        }
        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_IntegratedScheduling_Base model = baseBll.GetModel(strworkorderid);
            int type = RequestString.GetInt("type", 0);//0基本信息1 工单流程2评价
            if (!string.IsNullOrEmpty(strworkorderid))
            {
                switch (type)
                {
                    case 0:
                        //基本信息
                        #region
                        string sql = "select *,  [dbo].[GetPhoneByUserCode](F_DealMan) DealManPhone ,[dbo].[GetUserName](F_DealMan) DealManName,(case when F_Endtime= null then '' else dbo.GetConvertSecond(DATEDIFF(s,F_accepttime,F_endtime)) end) SpendTime,(select F_File from T_IntegratedScheduling_Process where F_WorkOrderCode='" + strworkorderid + "') dealfile, [dbo].[GetUserName](F_Applicant) applicantname ,[dbo].[GetUserName](F_CreateUser) createname,(select F_urgecount from [T_Wo_CommonBase] where F_WoCode='" + strworkorderid + "') F_UrgeCount from T_IntegratedScheduling_Base where F_WorkOrderCode='" + strworkorderid + "'";
                        DataTable dtbase = DbHelperSQL.Query(sql).Tables[0];



                        dtbase.Columns.Add("CollectFile", typeof(object));
                        dtbase.Columns.Add("FileUrl", typeof(object));
                        dtbase.Columns.Add("StateName");
                        dtbase.Columns.Add("TypeName");
                        dtbase.Columns.Add("PSInfo", typeof(object));
                        dtbase.Columns.Add("GapTime"); //超时时限

                        dtbase.Columns.Add("DealFileUrl", typeof(object));

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

                            if (!string.IsNullOrEmpty(fileurlpath) && !string.IsNullOrEmpty(dr["F_CollectFile"].ToString()))
                            {
                                dr["CollectFile"] = GetFileData(dr["F_CollectFile"].ToString(), fileurlpath);
                            }

                            if (!string.IsNullOrEmpty(fileurlpath) && !string.IsNullOrEmpty(dr["dealfile"].ToString()))
                            {
                                dr["DealFileUrl"] = GetFileData(dr["dealfile"].ToString(), fileurlpath);
                            }

                            dr["StateName"] = WorkOrderBase. GetWorkOrderStateStr(MENUENUM.调度工单列表, int.Parse(dr["F_WorkOrderState"].ToString()), 2000);

                            dr["PSInfo"] = GetPSInfo(strworkorderid);
                            

                           

                            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)
                                {
                                  
                                }
                                else
                                {
                                    dr["GapTime"] = "超时" + gshsj;
                                }
                            }





                        }


                        return Success("获取成功", dtbase);
                    #endregion
                   

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

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

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

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

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



                }

            }

            return Error("没传参数");

        }




        /// <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

        }

        //添加工单
        /// <summary>
        ///添加：处理方式：立即办理，暂存，转派）（opt传参 0 是立即办理 1 是暂存 2 是转派）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult AddSchedulingWorkOrder(T_SchedulingBaseInput input, List<Model.T_IntegratedScheduling_Detail> detailists,int? cfnum)
        {
            if (string.IsNullOrEmpty(input.ApplicationDept))
            {
                return Error("申请科室是必填");
            }
            if (string.IsNullOrEmpty(input.WorkOrderCategory))
            {
                return Error("工单类别是必填");
            }
          
            Model.T_IntegratedScheduling_Base model = new Model.T_IntegratedScheduling_Base();
            model.F_Applicant = input.Applicant;
            model.F_CFNum = cfnum;
            model.F_EmergencyTypes = input.EmergencyTypes;
            model.F_ApplicationDept = input.ApplicationDept.Trim();
            model.F_Phone = input.Phone;


            model.F_WorkOrderCategory = input.WorkOrderCategory.Trim();
            model.F_Content = input.Content;
            model.F_Location = input.Location;

            model.F_ToPlace = input.ToPlace;
            model.F_File = input.File;
            model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号
            model.F_IsDelete = 0;

            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)EnumSchedullingWorkOrderState.finish;
            //    model.F_DealDept = User.F_DeptId.ToString();
            //    model.F_DealMan = User.F_UserCode;
            //    model.F_Endtime = DateTime.Now;
            //    model.F_Deadline = DateTime.Now;
            //}


            if (input.opt == 2 && !string.IsNullOrEmpty(input.DealDept))
            {

                if (!string.IsNullOrEmpty(input.DealMan))
                {
                    model.F_DealDept = input.DealDept;
                    model.F_DealMan = input.DealMan;
                    model.F_AssignTime = DateTime.Now;
                    model.F_AssignUser = User.F_UserCode;
                    model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.receive;
                    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_DealMan, User.F_UserCode, EnumSmsType.comprehensive
                     , 0, model.F_WorkOrderCode);

                }
                else
                {


                }


            }
            else if (input.opt == 2 && string.IsNullOrEmpty(input.DealDept))
            {
                model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.neworder;
            }
            else if(input.opt == 1)
            {
                model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.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 = 2000;
                    new Bll.T_Call_LeaveRecord().Update(ld);
                    model.F_LeaveRecordId = input.LeaveRecordId;
                }
            }

            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;



            if (input.opt == 0)
            {
                model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.dealed;
                model.F_Endtime = DateTime.Now;

                //msg.AddInternalMessagesInfo("您提交的工单已处理完毕，请及时进行评价", "您提交的工单已处理完毕，请及时进行评价" + "工单编号:" + model.F_WorkOrderCode, model.F_Applicant, User.F_UserCode, EnumSmsType.comprehensive
                //  , 0, model.F_WorkOrderCode);



             
             //   AddOperatorLog("立即办理了工单", (int)EnumOperatorType.dealed, model.F_WorkOrderCode);




             //   return Success("");

            }




            int returnid = baseBll.Add(model);

            if (returnid > 0)
            {

                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.comprehensive
                                                  , 0, model.F_WorkOrderCode);
                        }



                }


                //if (input.LeaveRecordId != null && input.LeaveRecordId > 0)
                //{
                //    var ld = new Bll.T_Call_LeaveRecord().GetModel(input.LeaveRecordId.Value);
                //    if (ld != null)
                //    {
                //        ld.F_WorkOrderId = model.F_WorkOrderCode;
                //    }
                //}
                if (cfnum != null && cfnum > 0)
                {
                    Model.T_IntegratedScheduling_Detail modelsch = new Model.T_IntegratedScheduling_Detail();
                    modelsch.F_Number = cfnum;
                    modelsch.F_WorkOrderCode = model.F_WorkOrderCode;
                   // modelsch.F_DicName = "红处方数量";
                    modelsch.F_UpdateTime = DateTime.Now;
                    modelsch.F_IsDelete = 0;
                    modelsch.F_CreateTime = DateTime.Now;
                    detailBll.Add(modelsch);
                }

                if (detailists != null && detailists.Count > 0)
                {
                    foreach (Model.T_IntegratedScheduling_Detail item in detailists)
                    {
                        //Model.T_IntegratedScheduling_Detail detailmodel = new Model.T_IntegratedScheduling_Detail();

                        //detailmodel.F_DicId = item.F_DicId;
                        //detailmodel.F_DicName = item.F_DicName;
                        //detailmodel.F_Number = item.F_Number;
                        item.F_WorkOrderCode = model.F_WorkOrderCode;
                        item.F_UpdateTime = DateTime.Now;
                        item.F_IsDelete = 0;
                        item.F_CreateTime = DateTime.Now;
                        detailBll.Add(item);
                    }

                }


                AddAddlog(model.F_WorkOrderCode);
                if (input.opt == 0)
                {

                    AddOperatorLog("立即办理了工单", (int)EnumOperatorType.dealed, model.F_WorkOrderCode);
                }
                if (!string.IsNullOrEmpty(input.DealDept))
                {
                    model.F_AssignTime = DateTime.Now;
                    model.F_AssignUser = User.F_UserCode;
                    AddAssignlog(model.F_WorkOrderCode, input.DealDept, input.DealMan);

                }

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

        }
        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>
        ///编辑 usertype 0是综合保障中心，1 是我的工单页面的编辑
        ///  2022 /11/25 调度中心编辑接口中不能指派工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult UpdateSchedulingWorkOrder(T_SchedulingBaseInput input, int usertype)
        {
            Model.T_IntegratedScheduling_Base model = baseBll.GetModel(input.WorkOrderCode);


            model.F_Applicant = input.Applicant;
            model.F_ApplicationDept = input.ApplicationDept;
            model.F_Phone = input.Phone;
            model.F_EmergencyTypes = input.EmergencyTypes;
            model.F_WorkOrderCategory = input.WorkOrderCategory;
            model.F_Content = input.Content;
            model.F_Location = input.Location;
            model.F_ToPlace = input.ToPlace;
            model.F_File = input.File;
            model.F_UpdateTime = DateTime.Now;
            bool addassignlog = false;


            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 = ",工单类型:综合调度/" + dicvalue.F_Name;
            }

            //调度中心 可以指派处理部门
            //2022 /11/25 调度中心编辑接口中不能指派工单
            if (usertype == 0)
            {
                if (model.F_WorkOrderState > (int)EnumSchedullingWorkOrderState.neworder)
                {
                    return Error("分配之后的工单 不可以编辑");
                }

                //else
                //{
                //    if (!string.IsNullOrEmpty(input.DealDept) && input.DealDept != model.F_DealDept)
                //    {
                //        model.F_DealDept = input.DealDept;

                //        model.F_DealMan = input.DealMan;

                //        model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.receive;
                //        model.F_AssignTime = DateTime.Now;
                //        model.F_AssignUser = User.F_UserCode;
                //        addassignlog = true;
                //        msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收" + "工单编号:" + model.F_WorkOrderCode + message, model.F_DealMan, User.F_UserCode, EnumSmsType.comprehensive
                //   , 0, model.F_WorkOrderCode);
                //    }
                //    if (!string.IsNullOrEmpty(input.DealDept) && input.DealDept == model.F_DealDept)
                //    {
                //        if (input.DealMan != model.F_DealMan)
                //        {
                //            model.F_DealMan = input.DealMan;
                //            model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.receive;
                //            addassignlog = true;
                //            model.F_AssignTime = DateTime.Now;
                //            model.F_AssignUser = User.F_UserCode;
                //            msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收" + "工单编号:" + model.F_WorkOrderCode + message, model.F_DealMan, User.F_UserCode, EnumSmsType.comprehensive
                //   , 0, model.F_WorkOrderCode);
                //        }

                //    }
                //}
            }
            else
            {
                // 我的工单列表 编辑完了之后 工单状态是新工单  待指派
                if (model.F_WorkOrderState > (int)EnumSchedullingWorkOrderState.neworder)
                {
                    return Error("分配之后的工单 不可以编辑");
                }
                model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.neworder;
            }


            if (baseBll.Update(model))
            {
                AddOperatorLog( "编辑了工单", (int)EnumOperatorType.update, model.F_WorkOrderCode);
                if (addassignlog)
                {
                    AddAssignlog(model.F_WorkOrderCode, input.DealDept, input.DealMan);
                }
                return Success("编辑成功！");
            }
            else return Error("编辑失败！");

        }


        //调度中心指派
        public ActionResult DDZXTransfer(string WorkOrderCode, string DealMan, string DealDept)
        {
            if (string.IsNullOrEmpty(DealMan))
            {
                return Error("请选择处理人");
            }

            Model.T_IntegratedScheduling_Base model = baseBll.GetModel(WorkOrderCode);
            if (model != null)
            {
                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;
                }

                model.F_DealDept = DealDept;

                model.F_DealMan = DealMan;

                model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.receive;
                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);
                baseBll.Update(model);
                AddAssignlog(model.F_WorkOrderCode, DealDept, DealMan);
                msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + model.F_WorkOrderCode + message, model.F_DealMan, User.F_UserCode, EnumSmsType.comprehensive
           , 0, model.F_WorkOrderCode);

                return Success("转派成功");
            }


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

        }



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

            Model.T_IntegratedScheduling_Base model = baseBll.GetModel(workordercode);
            if (model == null)
            {
                return Error("没有获取到工单号");
            }
            if (model.F_WorkOrderState >(int) EnumSchedullingWorkOrderState.neworder)
            { 
                return Error("工单已指派");
            }
            model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.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.comprehensive
, 0, model.F_WorkOrderCode);

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



        //综合保障中心 撤回（已指派未接单的可进行撤回，工单状态为“待指派”）
        public ActionResult Retract(string workordercode)
        {

            Model.T_IntegratedScheduling_Base model = baseBll.GetModel(workordercode);
            if (model == null)
            {
                return Error("没有获取到工单号");
            }
            if (model.F_WorkOrderState == (int)EnumSchedullingWorkOrderState.receive)
            {
                model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.neworder;
                model.F_DealDept = "";
                model.F_DealMan = "";
                model.F_Deadline = null;             
                model.F_AssignTime = null;
                model.F_AssignUser = "";
                model.F_UpdateTime = DateTime.Now;         


                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( "撤回了工单", (int)EnumOperatorType.retract, model.F_WorkOrderCode);
                return Success("撤回操作成功");
            }
            else
            {
                return Error("只能撤回未接单的工单");
            }
        }





        //综合保障中心删除工单
        public ActionResult DeleteSchedulingWorkOrder(string WorkOrderCode)
        {
            Model.T_IntegratedScheduling_Base model = baseBll.GetModel(WorkOrderCode);
            model.F_IsDelete = 1;
            if (baseBll.Update(model))
            {
                AddOperatorLog("删除了工单", (int)EnumOperatorType.delete, WorkOrderCode);
                return Success("删除成功");
            }

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

        #endregion


        #region 处理人用的是综合调度的工单列表 接单 退回 送达 （附件）,

        public ActionResult GetDealManWorkOrderList()
        {

            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 listtype = RequestString.GetInt("listtype", 0);
            int dept = RequestString.GetInt("dept", -1);

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

      
            int isbuzg = 0;

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

           
            if (isbuzg==1)
            {
                sql += " and F_DealDept  in(select F_DeptId from[dbo].[GetDeptid] ('" + User.F_DeptId + "'))";
                 

            }
            else
            { //当前登录人只能看到指派给自己的工单
                sql += " and F_DealMan='" + User.F_UserCode + "'";

            }

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            if (strcategory.Trim() != "" && strcategory != "undefined")
            {
                sql += " and F_WorkOrderCategory = '" + strcategory + "' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_Applicant = '" + strname + "' ";
            }
            if (dept > -1)
            {
                sql += " and F_ApplicationDept = '" + dept + "' ";
            }

            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 (listtype)
            {

                case 1:
                    sql += " and F_WorkOrderState in (1,2)";
                    break;
                case 2:
                    sql += " and  F_WorkOrderState>2 ";
                    break;

            }
            int recordCount = 0;
            DataTable datatable = Bll.PagerBll.GetListPager
                                            ("T_IntegratedScheduling_Base ",
                                              "F_WorkOrderId",
                                              "*, [dbo].[GetUserName](F_Applicant) Applicant , [dbo].[GetUrgeCount](F_WorkOrderCode) F_UrgeCount ",
                                              sql,
                                              "order by F_WorkOrderId desc",
                                              pagesize,
                                              pageindex,
                                              true,
                                              out recordCount
                                            );


            datatable = WorkOrderBase.SetOtherField(datatable, MENUENUM.调度工单列表, User.F_UserCode, User.F_RoleId, 2000);

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



        }


        //查收
        public ActionResult CheckWorkOrder(string WorkOrderCode)
        {
            Model.T_IntegratedScheduling_Base model = baseBll.GetModel(WorkOrderCode);
            if (model != null)
            {
                if (model.F_DealMan == User.F_UserCode.ToString())
                {                 
                    model.F_UpdateTime = DateTime.Now;                   

                    model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.dealing;
                    model.F_AcceptTime = DateTime.Now;
                    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_IntegratedScheduling_Base model = baseBll.GetModel(WorkOrderCode);
            string str = "";
            if (!string.IsNullOrEmpty(BackReason))
            {
                str = "，" + BackReason;
            }

            if (model != null)
            {
                if (model.F_DealMan == User.F_UserCode)
                {
                    string assignuser = model.F_AssignUser;
                    model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.neworder;
                    model.F_DealMan = "";
                    model.F_DealDept = "";
                    model.F_AssignTime = null;
                    model.F_AssignUser = "";
                    model.F_UpdateTime = DateTime.Now;
                    model.F_Deadline = null;
                    model.F_AcceptTime = null;
                    baseBll.Update(model);
                    string s = "\n退回原因:" + value + str;
                    AddOperatorLogAboutKey("退回了工单" + s, (int)EnumOperatorType.back, model.F_WorkOrderCode,key,value,BackReason);
                    msg.AddInternalMessagesInfo("您有工单被退回", "您有工单被退回\n" + "工单编号:" + model.F_WorkOrderCode+s, assignuser
                               , User.F_UserCode, EnumSmsType.comprehensive
                 , 0, model.F_WorkOrderCode);

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

        //chuliren收取急查标本
        public ActionResult CollectSpecimens(string WorkOrderCode, string file ,string remark)
        {
            if (string.IsNullOrEmpty(file))
            {
                return Error("急查类型必须上传附件");
            }

            Model.T_IntegratedScheduling_Base model = baseBll.GetModel(WorkOrderCode);
            if (model != null)
            {
                model.F_CollectFile = file;
                model.F_CollectTime = DateTime.Now;
                baseBll.Update(model);
                string stradd = "";
                if (!string.IsNullOrEmpty(remark))
                {
                    stradd = "," + remark;
                }
                AddOperatorLog("收取标本"+stradd, (int)EnumOperatorType.collect, model.F_WorkOrderCode);

                return Success("收取标本成功！");
            }
            return Error("工单不存在！");
        }



        //送达操作
        public ActionResult DealWorkOrder(string WorkOrderCode, string file,string remark
            )
        {
            Model.T_IntegratedScheduling_Base model = baseBll.GetModel(WorkOrderCode);
            model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.dealed;
            model.F_Endtime = DateTime.Now;
            

            baseBll.Update(model);
            msg.AddInternalMessagesInfo("您提交的工单已处理完毕，请及时进行评价", "您提交的工单已处理完毕，请及时进行评价\n" + "工单编号:" + model.F_WorkOrderCode, model.F_Applicant, User.F_UserCode, EnumSmsType.comprehensive
              , 0, model.F_WorkOrderCode);


            Model.T_IntegratedScheduling_Process promodel = new Model.T_IntegratedScheduling_Process();
            promodel.F_DealDept = User.F_DeptId.ToString();
            promodel.F_DealMan = User.F_UserCode;
            promodel.F_File = file;
            promodel.F_Isdelete = 0;
            promodel.F_ProcessingTime = DateTime.Now;
            promodel.F_WorkOrderCode = WorkOrderCode;
            proBll.Add(promodel);

            string stradd = "";
            if (!string.IsNullOrEmpty(remark))
            {
                stradd = "," + remark;
            }


            AddOperatorLog("已送达"+ stradd, (int)EnumOperatorType.dealed, WorkOrderCode);




            return Success("");

        }

        #endregion

        #region 申请人用的是我的工单页面 评价 撤回； 编辑（与综合保障中心共用的编辑接口）
        //申请人列表  app
        public ActionResult MySubmitList()
        {
                string sql = " and F_IsDelete=0 ";
            // 待完成  0  已完成 1

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

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


            //当前登录人只能看到自己提交的工单
            if (User.F_RoleCode=="BMZG")
            {
                sql += " and F_ApplicationDept  in(select F_DeptId from[dbo].[GetDeptid] ('" + User.F_DeptId + "'))";
            }
            else
            {
                sql += " and F_Applicant='" + User.F_UserCode + "'";
            }
               

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

                if (strpagesize.Trim() != "")
                {
                    pagesize = Convert.ToInt32(strpagesize);
                }
                //if (strcategory.Trim() != "" && strcategory != "undefined")
                //{
                //    sql += " and F_WorkOrderCategory = '" + strcategory + "' ";
                //}
                //if (strname.Trim() != "" && strname != "undefined")
                //{
                //    sql += " and F_Applicant = '" + strname + "' ";
                //}
                //if (dept > -1)
                //{
                //    sql += " and F_ApplicationDept = '" + dept + "' ";
                //}

                //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 (listtype)
                {

                    case 0:
                        sql += " and F_WorkOrderState <4";
                        break;
                    case 1:
                        sql += " and  F_WorkOrderState = 4  ";
                        break;

                }
                int recordCount = 0;
                DataTable datatable = Bll.PagerBll.GetListPager
                                                ("T_IntegratedScheduling_Base ",
                                                  "F_WorkOrderId",
                                                  "*, [dbo].[GetUserName](F_Applicant) Applicant , [dbo].[GetUrgeCount](F_WorkOrderCode) F_UrgeCount ",
                                                  sql,
                                                  "order by F_WorkOrderId desc",
                                                  pagesize,
                                                  pageindex,
                                                  true,
                                                  out recordCount
                                                );


                datatable = WorkOrderBase.SetOtherField(datatable, MENUENUM.我的提交,  User.F_UserCode, User.F_RoleId, 2000,1);

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



            }




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

            Model.T_IntegratedScheduling_Base model = baseBll.GetModel(workordercode);
            if (model == null)
            {
                return Error("没有获取到工单号");
            }
            if (model.F_WorkOrderState == 0)
            {
                model.F_WorkOrderState = (int)EnumSchedullingWorkOrderState.waitsubmit;
                baseBll.Update(model);
                AddOperatorLog( "撤回了工单", (int)EnumOperatorType.myretract, model.F_WorkOrderCode);
                return Success("撤回操作成功");

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

        }


        //评价
       // 1-5星，3星以下需要填写文字评价，
        public ActionResult EvaluateWorkOrder(string WorkOrderCode, string EvaluateContent, int Attitude=0, int Efficiency = 0)
        {
            Model.T_IntegratedScheduling_Base model = baseBll.GetModel(WorkOrderCode);
            Model.T_IntegratedScheduling_Evaluate evamodel = new Model.T_IntegratedScheduling_Evaluate();
            if (model != null)
            {
                if (model.F_Applicant.Trim() == User.F_UserCode)
                {

                    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_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_ConfirmEquip = 2;
                        model.F_Score = Attitude  + Efficiency;
                  
                        AddOperatorLog("评价了工单", (int)EnumOperatorType.evaluate, model.F_WorkOrderCode);

                        if (Attitude < 3 || Efficiency < 3)
                        {
                            model.MYD = 2;
                            msg.AddInternalMessagesInfo("您有工单被差评", "您有工单被差评\n" + "工单编号:" + model.F_WorkOrderCode + "\n差评原因:" + EvaluateContent, model.F_DealMan, User.F_UserCode, EnumSmsType.comprehensive
                       , 0, model.F_WorkOrderCode);
                        }
                        else if (Attitude == 3 ||    Efficiency == 3)
                        {
                            model.MYD = 1;
                        }
                        else
                        {
                            model.MYD = 0;
                        }
                        baseBll.Update(model);
                        return Success("评价成功");
                    }
                    return Error("评价失败");
                }
                else
                {
                    return Error("申请人等于当前登录人才可以评价");
                }
            }
            return Error("评价失败");

        }

        ///// <summary>
        ///// 自动评价 若超过2小时未进行评价，系统默认评价5星
        ///// </summary>
        ///// <returns></returns>
        //[AllowAnonymous]        
        //public ActionResult Evaluate()
        //{
        //    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 = 15;
        //                    baseBll.Update(model);
        //                    AddOperatorLog("评价了工单", (int)EnumOperatorType.evaluate, model.F_WorkOrderCode);                             
        //                }
        //                else
        //                    continue;

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

        //}
        #endregion


        #region 添加操作记录
        public bool AddOperatorLogNew(string content, int type, string workordercode,string usercode)
        {
            Model.T_IntegratedScheduling_OperationLog model = new Model.T_IntegratedScheduling_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_IntegratedScheduling_OperationLog model = new Model.T_IntegratedScheduling_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;
        }
        /// <summary>
        /// 自动评价添加log没有usercode
        /// </summary>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <param name="workordercode"></param>
        /// <returns></returns>
        public bool AddEvaluateOperatorLog(string content, int type, string workordercode)
        {
            Model.T_IntegratedScheduling_OperationLog model = new Model.T_IntegratedScheduling_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,int key,string value,string reason)
        {
            Model.T_IntegratedScheduling_OperationLog model = new Model.T_IntegratedScheduling_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 = reason;
            logBll.Add(model);
            return true;
        }


        public void AddAddlog(string workordercode)
        {
            AddOperatorLog("创建综合调度工单", (int)EnumOperatorType.add, workordercode);
        }
        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 "";

        }


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

        }
        #endregion



    }
}
