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

namespace RMYY_CallCenter_Api.Controllers.CarManage
{
    public class T_Car_WorkOrderController : BaseController
    {
        private Bll.T_Sys_UserAccount userbll = new Bll.T_Sys_UserAccount();
        private Bll.T_Car_WorkOrder orderbll = new Bll.T_Car_WorkOrder();
        private Bll.T_Sys_Department deptbll = new Bll.T_Sys_Department();
        private Bll.T_Car_Message carbll = new Bll.T_Car_Message();
        private static InternalMessagesController msg = new InternalMessagesController();



        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="type"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult GetList( string starttime = "", string endtime = "", 
            string WorkOrderCode = "", int type = 0, int pageindex = 1, int pagesize = 10, int state = -1
            )

        {
            if (User!=null)
            {
                DataTable data = new DataTable();
                string sql = "";
                if (type > 0)
                    sql += $" and F_Type=" + type;
                if (starttime.Trim() != "" && starttime != "undefined")
                    sql += $" and datediff(day,F_CreateTime,'" + starttime + "')<=0";
                if (endtime.Trim() != "" && endtime != "undefined")
                    sql += $" and datediff(day,F_CreateTime,'" + endtime + "')>=0";
                if (WorkOrderCode.Trim() != "" && WorkOrderCode != "undefined")
                    sql += $" and F_WorkOrderCode like '%{WorkOrderCode}%'";
               
                if (User.F_RoleCode == "BMZG")
                {
                    sql += $" and F_ProposerDeptId in(select F_DeptId from [dbo].[GetDeptid] ({User.F_DeptId }))";
                }
                else
                {
                    if (User.F_RoleCode != "GLY" && User.F_RoleCode != "DDZX")
                        sql += $" and F_CreateUser = '{User.F_UserCode }'";
                }
               
                    if (state >= 0)
                {

                   if (state==10|| state == 7)
                    sql += $" and F_State=" + state;
                    else if (state == 0)
                        sql += $" and F_State in (0,-1)"  ;
                    else if (state == 1)
                        sql += $" and F_State in (1,2,4,7)";
                    else if (state == 10)
                        sql += $" and F_State =10";
                }
               


                sql += "and F_IsDel=0";
                int recordCount = 0;
                string where = "";
                if (!string.IsNullOrEmpty(sql))
                {
                    where += sql;
                }
                data = Bll.PagerBll.GetListPager
                                    (
                                    "T_Car_WorkOrder",
                                    "F_ID",
                                    "*,dbo.GetDictionaryName(F_CarType) F_CarTypeName",
                                    where,
                                    "order by F_ID desc",
                                    pagesize,
                                    pageindex,
                                    true,
                                    out recordCount
                                    );
                List<Model.T_Car_WorkOrder> modellist = orderbll.DataTableToList(data);
                if (modellist.Count > 0)
                {
                    int i = 0;
                    foreach (var item in modellist)
                    {
                        item.F_CarTypeName = data.Rows[i]["F_CarTypeName"].ToString();
                        item.F_DeptName = new Bll.T_Sys_Department().GetModel(Convert.ToInt32(item.F_ProposerDeptId))?.F_DeptName ?? "";
                        item.F_TypeName = new Bll.T_Sys_GongDan().GetModel(Convert.ToInt32(item.F_Type))?.F_Name ?? "";
                        item.StateName = GetDescriptionOriginal(data.Rows[i]["F_State"].ToString());
                        i++;
                    }
                }
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = modellist,
                    tatal = recordCount
                };
                return Content(obj.ToJson());
            }
            return Error("无操作权限");
        }

        public  string GetDescriptionOriginal(string  state)
        {
            string message = "待分配";
           switch (state)
            {
                case "-1":
                    message = "新工单";
                    break;
                case "0":
                    message = "待分配";
                    break;
                case "1":
                    message = "待接单";
                    break;
                case "2":
                    message = "已接单";
                    break;
                case "4":
                    message = "处理中";
                    break;
                case "7":
                    message = "待评价";
                    break;
                case "10":
                    message = "已完成";
                    break;
            }
            return message;


        }
       
        /// <summary>
        /// 获取司机列表
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="type"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult GetCarList(string starttime = "", string endtime = "",string carname = "",string driverName="" ,string WorkOrderCode = "",int pageindex = 1, int pagesize = 10, int state = -1)

        {
            if (User != null)
            {
                DataTable data = new DataTable();
                string sql = "";
            
                if (starttime.Trim() != "" && starttime != "undefined")
                    sql += $" and datediff(day,F_CreateTime,'" + starttime + "')<=0";
                if (endtime.Trim() != "" && endtime != "undefined")
                    sql += $" and datediff(day,F_CreateTime,'" + endtime + "')>=0";
                if (state >= 0)
                {
                    if (state ==1)
                        sql += $" and F_State in(2,4)";
                    else if (state == 5)
                        sql += $" and F_State in(0,2,4)";
                    else 
                   sql += $" and F_State=" + state;
                }
                if (carname.Trim() != "" && carname != "undefined")
                    sql += $" and F_CarName like '%{carname}%'";

                if (driverName.Trim() != "" && driverName != "undefined")
                    sql += $" and F_DriverName like '%{driverName}%'";
              
                if (User .F_RoleCode =="SJ")
                {
                    sql += $" and F_DriverCode = '{User .F_UserCode }'";
                }
                else if (User.F_RoleCode == "BMZG")
                {
                    sql += $" and F_CreateUser in(select F_UserCode from T_Sys_UserAccount where F_DeptId in(select F_DeptId from [dbo].[GetDeptid] ({User.F_DeptId })) ) ";
                }
                else if (User.F_RoleCode != "GLY"&& User.F_RoleCode != "BMZG")
                {
                    sql += $" and   F_CreateUser= '{User.F_UserCode}'";
                }

                if (WorkOrderCode.Trim() != "" && WorkOrderCode != "undefined")
                    sql += $" and (F_WorkOrderID like '%{WorkOrderCode}%' or F_WorkOrderCode like '%{WorkOrderCode}%')";
                sql += "and F_IsDelete=0";
                int recordCount = 0;
                string where = "";
                if (!string.IsNullOrEmpty(sql))
                {
                    where += sql;
                }
                data = Bll.PagerBll.GetListPager
                                    (
                                    "T_Car_AssignWorkOrder",
                                    "F_ID",
                                    "*",
                                    where,
                                    "order by F_ID desc",
                                    pagesize,
                                    pageindex,
                                    true,
                                    out recordCount
                                    );
                if (data != null && data.Rows.Count > 0)
                {
                    data.Columns.Add("StateName", typeof(object));
                    foreach (DataRow it in data.Rows)
                    {
                        switch (it["F_State"].ToString())
                        {
                            case "0":
                                it["StateName"] = "待接单";
                                break;
                              case "2":
                                it["StateName"] = "已接单";
                                break;
                              case "4":
                                it["StateName"] = "处理中";
                                break;
                                     case "10":
                                it["StateName"] = "已完成";
                                break;
                        }
                      
                    }
                }
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = data,
                    tatal = recordCount
                };
                return Content(obj.ToJson());
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 报表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="isdc"></param>
        /// <returns></returns>
        public ActionResult GetListExpt(string keyword, string starttime = "", string endtime = "",  int pageindex = 1, int pagesize = 10, int isdc = 0)
        {
            if (User != null)
            {
                #region 查询条件
                string sql = $" and F_IsDel=0";
                DataTable data = new DataTable();
                if (starttime.Trim() != "" && starttime != "undefined")
                    sql += $" and datediff(day,F_CreateTime,'" + starttime + "') <=0 ";
                if (endtime.Trim() != "" && endtime != "undefined")
                    sql += $" and datediff(day,F_CreateTime,'" + endtime + "')>=0";
                if (!string.IsNullOrEmpty(keyword))
                {
                    sql += $"and (F_WorkOrderCode like '%" + keyword.Trim() + "%' or F_ProposerCode like '%" + keyword.Trim() + "%' or F_Phon like '%" + keyword.Trim() + "%')";
                }           
                #endregion
                if (isdc > 0)
                {
                    NPOIHelper nopi = new NPOIHelper();
                    data = DbHelperSQL.Query($" select  F_WorkOrderCode 工单编号,(select F_DeptName from T_Sys_Department where F_DeptId=wo.F_ProposerDeptId ) 申请科室,"
                             + $"F_ProposerName 申请人,F_Phon 联系电话, F_DepartPlace 出发地,F_Destination  目的地,F_CreateTime 申请时间,F_DriverName 司机,F_DriverPhon 司机电话,"
                             + $"(select F_Name from T_Sys_GongDan where F_GDId=wo.F_Type) as 用车事由,F_ControlManName+'('+F_ControlManCode+')'as 调度员,F_Remark 备注"
                             + $" from T_Car_WorkOrder wo WITH(NOLOCK)  where 1=1 " + sql).Tables[0];
                    if (nopi.ExportToExcel("车辆调度统计报表", data) == "")
                    {
                        return Success("导出成功！");
                    }
                    else return Error("导出失败！");
                }
                else
                {
                    int recordCount = 0;
                    if (!string.IsNullOrEmpty(sql))
                    {
                        data = Bll.PagerBll.GetListPager
                            (
                            "T_Car_WorkOrder aa",
                            "F_ID",
                            "*,(select F_DeptName from T_Sys_Department where F_DeptId=aa.F_ProposerDeptId )F_DeptName,(select F_Name from T_Sys_GongDan where F_GDId=aa.F_Type)F_TypeName",
                            sql,
                            "ORDER BY F_ID desc",
                            pagesize,
                            pageindex,
                            true,
                            out recordCount
                            );
                    }
                    var modellist = orderbll.DataTableToList(data);
                    //if (modellist.Count > 0)
                    //{

                    //    foreach (var item in modellist)
                    //    {
                    //        item.F_WoState = EnumHelper.GetDescription((EnumMatWorkOrderState)item.F_State);
                    //        item.F_TypeName = "物资转移";
                    //    }
                    //}
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = modellist,
                        total = recordCount
                    };
                    return Content(obj.ToJson());

                }
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="type"></param>
        /// <param name="detpid"></param>
        /// <param name="startplace"></param>
        /// <param name="endplace"></param>
        /// <param name="needman"></param>
        /// <param name="phon"></param>
        /// <param name="cartype"></param>
        /// <param name="remark"></param>
        /// <param name="source"></param>
        /// <param name="callid"></param>
        /// <returns></returns>
        public ActionResult AddWorkOrder(int type,int hosid,string content,   
            int detpid,string startplace,string endplace,string needman,string phon,
            int cartype,string remark, string EmergencyTypes, string source,string usertime,int birth=0,string callid ="",int LeaveRecordId=0)
        {
            if (User!=null)
            {
                if (type <= 0)
                    return Error("工单类型错误！");
                if (detpid == 0)
                    return Error("请选择申请科室！");
                if (startplace == "")
                    return Error("请填写出发地！");
                if (endplace == "")
                    return Error("请填写目的地！");
                if (needman == "")
                    return Error("请填写申请人！");
                if (phon == "")
                    return Error("请填写手机号码！");
                if (cartype == 0)
                    return Error("请选择车辆要求！");
                var model = new Model.T_Car_WorkOrder();
                #region 添加字段
                model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号
                model.F_Source = source;//电话，电脑，微信
                model.F_Type = type;//工单类型：1院区转运患者、2转运物资、3转运消供器械、4转运设备
                model.F_ProposerDeptId = detpid;//申请部门
                model.F_CallID = callid;//通话记录id
                model.F_DepartPlace = startplace;//出发地
                model.F_Destination = endplace;//目的地
                model.F_ProposerCode = needman;//申请人
                model.F_UseTime = usertime;//用车时间
                model.F_Phon = phon;//联系电话
                model.F_CarType = cartype;//车辆大小
                model.F_Content = content;//调度内容
                model.F_Birth = birth;
                model.F_Remark = remark;//备注
                model.F_HosId = hosid;
                model.F_CreateTime = DateTime.Now;
                model.F_State = (int)EnumWorkOrderState.neworder;//0
                model.F_CreateUser = User.F_UserCode;
                model.F_IsDel = 0;
                model.F_EmergencyTypes = EmergencyTypes;
                if ( LeaveRecordId> 0)

                {
                    var ld = new Bll.T_Call_LeaveRecord().GetModel(LeaveRecordId);
                    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 = 4000;
                        new Bll.T_Call_LeaveRecord().Update(ld);
                        model.F_LeaveRecordId =LeaveRecordId;
                    }
                }

                #endregion
                int n = orderbll.Add(model);
                if (n > 0)
                {
                    string deptname = "";
                    var deptmodel = deptbll.GetModel(User.F_DeptId);
                    if (deptmodel != null)
                        deptname = deptmodel.F_DeptName + "-";
                    AddOperation(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "创建工单", User.F_UserCode, 0,
                       model.F_WorkOrderCode, 0);
                    return Success("添加成功！");
                }
                else return Error("添加失败！");
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="type"></param>
        /// <param name="detpid"></param>
        /// <param name="startplace"></param>
        /// <param name="endplace"></param>
        /// <param name="needman"></param>
        /// <param name="phon"></param>
        /// <param name="cartype"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public ActionResult UpdateWorkOrder(string WorkOrderCode, 
            string usertime,string content, int type,int hosid, int detpid, string startplace, string endplace,
            string needman,string needmanName,string EmergencyTypes, string phon,int birth, int cartype, string remark)
        {
            int userId = 1;
            if (userId != 0)
            {
                var model = orderbll.GetModelByCode (WorkOrderCode);
                if (model == null)
                    return Error("查询不到此工单！");
                if (type <= 0 )
                    return Error("工单类型错误！");
                if (detpid == 0)
                    return Error("请选择申请科室！");
                if (startplace == "")
                    return Error("请填写出发地！");
                if (endplace == "")
                    return Error("请填写目的地！");
                if (needman == "")
                    return Error("请填写申请人！");
                if (phon == "")
                    return Error("请填写手机号码！");
                if (cartype == 0)
                    return Error("请选择车辆要求！");
                if (model.F_State != (int)EnumWorkOrderState.neworder  && model.F_State == (int)EnumWorkOrderState.assign )
                    return Error("此工单已接单不能修改！");
                #region 添加字段
                model.F_Type = type;//工单类型：1院区转运患者、2转运物资、3转运消供器械、4转运设备
                model.F_ProposerDeptId = detpid;//申请部门
                model.F_DepartPlace = startplace;//出发地
                model.F_HosId = hosid;
                model.F_Destination = endplace;//目的地
                model.F_ProposerCode = needman;//申请人
                model.F_ProposerName = needmanName;//申请人姓名
                model.F_Phon = phon;//联系电话
                model.F_UseTime = usertime;//用车时间
                model.F_Content = content;//调度内容
                model.F_CarType = cartype;//车辆大小
                model.F_Remark = remark;//备注
                model.F_State = 0;
                model.F_Birth = birth;
                model.F_EmergencyTypes = EmergencyTypes;
                #endregion
                bool n = orderbll.Update(model);
                if (n)
                {
                    string deptname = "";
                    var deptmodel = deptbll.GetModel(User.F_DeptId);
                    if (deptmodel != null)
                        deptname = deptmodel.F_DeptName + "-";
                    AddOperation(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "修改工单", User.F_UserCode, model.F_State.Value  ,
                    model.F_WorkOrderCode, 0);
                    return Success("修改成功！");
                }
                   
                else return Error("修改失败！");
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public ActionResult Delete(string WorkOrderCode)
        {
            int userId = User.F_UserId;
            if (userId != 0)
            {
                if (string .IsNullOrEmpty (WorkOrderCode))
                    return Error("选择要删除的工单！");

                var model = orderbll.GetModelByCode (WorkOrderCode);
                if (model == null)
                    return Error("查询不到此工单！");
                if (orderbll.Delete(model.F_ID ))
                    return Success("删除成功！");
                else return Error("删除失败！");
                   
            }
            return Error("无操作权限！");
        }

        /// <summary>
        /// 获取工单详情c
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public ActionResult GetModelDetail(string WorkOrderCode, int type=0,int orderid=0)
        {

            switch (type)
            {
                case 0:
                    if (string.IsNullOrEmpty(WorkOrderCode))
                        return Error("工单信息错误！");
                    var model = orderbll.GetModelByCode(WorkOrderCode);
                    if (model != null)
                    {
                        model.HosName = new Bll.T_Wowo_repairyqbll().GetModel(model.F_HosId ?? 0)?.T_Woname ?? "";
                        model.F_ProposerDeptName = new Bll.T_Sys_Department().GetModel(Convert.ToInt32(model.F_ProposerDeptId))?.F_DeptName ?? "";
                        model.F_ProposerName = new Bll.T_Sys_UserAccount().GetModel(model.F_ProposerCode.ToString())?.F_UserName ?? "";
                        model.F_CarName = new Bll.T_Sys_DictionaryValue().GetModel(model.F_CarType.Value)?.F_Name ?? "";
                        model.StateName = GetDescriptionOriginal(model.F_State.ToString());
                        string urgecount = DbHelperSQL.GetSingle("select F_urgecount from[T_Wo_CommonBase] where F_WoCode ='" + WorkOrderCode + "'").ToString();
                        if (model.F_EndTime == null || model.F_AcceptTime==null)
                        {
                            model.SpendTime = "";
                        }
                        else
                        {
                            string strspend = "";
                            TimeSpan ts = model.F_EndTime.Value - model.F_AcceptTime.Value;
                            if (ts.Days != 0)
                            {
                                strspend += ts.Days + "天";
                            }
                            strspend += ts.Hours + "时";
                            strspend += ts.Minutes + "分";
                            strspend += ts.Seconds + "秒";
                            model.SpendTime = strspend;
                        }

                        if (!string.IsNullOrEmpty(urgecount))
                        {
                            model.F_UrgeCount = Convert.ToInt32(urgecount);
                        }
                        int identity = 0;
                        if (User.F_UserCode == model.F_ProposerCode )
                        {
                            identity = 1;
                        }
                        var obj = new
                        {
                            state = "success",
                            message = "成功",
                           allButtons = GetButton(model.F_State.Value  ,User .F_RoleCode, identity),
                            model = model
                        };
                        return Content(obj.ToJson());
                    }
                    else
                        return Success("没有查询到此工单信息");
                case 1://工单流程
                       // var modellist = new BLL.T_Car_Operation().GetModelList($"F_WorkOrderCode='{WorkOrderCode}'");
                    string sqllog = "select  dbo.GetUserNameUserCode(F_CreateUser) username,F_ID,F_WorkOrderCode,F_Message,F_AssignID,F_CreateTime,F_State,F_CreateUser,F_IsDelete,F_AboutReason ,F_AboutKey,F_EnterReason from T_Car_Operation where F_WorkOrderCode='" + WorkOrderCode + "'";

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

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

                //    return Success("获取成功", modellist);
                case 2://评价详情
                    var Evaluate = new BLL.T_Car_Evaluate().GetModelList($"F_WorkOrderCode='{WorkOrderCode}'");
                    return Success("获取成功", Evaluate);
                    
                case 3://司机工单
                    if (orderid <= 0)
                        return Error("请选择工单");
                    var Assignmodel = new BLL.T_Car_AssignWorkOrder().GetModel(orderid);
                    if (Assignmodel != null)
                    {
                      
                        var Carlist = DbHelperSQL.Query  
                            ($"select *,dbo.GetDictionaryName(F_CarType) F_CarTypeName" +
                            $" from T_Car_WorkOrder where F_WorkOrderCode " +
                            $"in({string.Join(",", Assignmodel.F_WorkOrderID.Split(','))}) and F_IsDel=0 " +
                            $"order by charindex(','+F_WorkOrderCode+',',',{Assignmodel.F_WorkOrderID},')").Tables[0];
                        if (Carlist!=null && Carlist.Rows .Count>0)
                        {
                            Carlist.Columns.Add("Buttons", typeof(object));
                            foreach (DataRow it in Carlist.Rows )
                            {
                                int identity = 0;
                                if (User.F_UserCode == it["F_ProposerCode"].ToString())
                                {
                                    identity = 1;
                                }

                                it["Buttons"] = GetButton(int .Parse (it ["F_State"].ToString ()), User.F_RoleCode, identity);
                            }
                        }
                        var obj = new
                        {
                            state = "success",
                            message = "成功",
                            model = Assignmodel,
                            Carlist = Carlist
                        };
                        return Content(obj.ToJson());
                    }
                    else
                        return Error("工单不存在");
                    
            }
            return Error("没传参数");
        }
        /// <summary>
        /// 按钮
        /// </summary>
        public class button
        {
            public int key { get; set; }
            public string value { get; set; }
            public button(int _key, string _value)
            {
                key = _key;
                value = _value;
            }
        }
        public static button distribution()
        {
            return new button(1, "分配");
        }
        public static button withdraw()
        {
            return new button(2, "撤回");
        }
        public static button back()
        {
            return new button(3, "退回");
        }
        public static button receiving()
        {
            return new button(4, "接单");
        }
        public static button start()
        {
            return new button(5, "发车");
        }
        public static button end()
        {
            return new button(6, "抵达");
        }
        public static button evaluate()
        {
            return new button(7, "评价");
        }
        public static button edit()
        {
            return new button(8, "编辑");
        }
        public List <button > GetButton(int state,string role,int identity=0)
        {
            List<button> buttons = new List<button>();
            switch (state)
            {
                case -1:
                    buttons.Add(edit());
                    break;
                case 0:
                  //  buttons.Add(distribution());
                    buttons.Add(withdraw());
                    break;
                case 1:
                    if (role =="SJ")
                    {
                        buttons.Add(back());
                        buttons.Add(receiving());
                    }
                    break;
                case 2:
                    if (role == "SJ")
                    {
                        buttons.Add(start());
                    }
                    break;
                case 4:
                    if (role == "SJ")
                    {
                        buttons.Add(end());
                    }
                    break;
                case 7:
                    if(identity==1)
                    buttons.Add(evaluate());
                    break;

            }
            return  buttons;
        }
        /// <summary>
        /// 派车
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="driver"></param>
        /// <param name="phon"></param>
        /// <param name="carmessage"></param>
        /// <param name="assist"></param>
        /// <returns></returns>
        public ActionResult AssignWorkOrder(string  orderid, string driver
           ,int carid, string assist = "",string assistname="")
        {
            if (driver == "")
                return Error("请选择司机");
            if (string.IsNullOrEmpty(orderid))
                return Error("请选择配送工单");
            var modellist = orderbll.GetModelList($"F_WorkOrderCode in({string.Join(",", orderid.Split (','))}) and F_IsDel=0");
            
            if (modellist!=null && modellist.Count >0)
            {
                if (modellist.Where (x=>x .F_State !=0).Count() >0)
                {
                    return Error("工单已分配");
                }
                if (modellist.Count != orderid.Split(',').Length)
                    return Error("配送工单有误");
                Model.T_Car_AssignWorkOrder assign = new Model.T_Car_AssignWorkOrder();
                var carmodel = carbll.GetModel(carid);
                if (carbll == null)
                    return Error("不存在此车辆信息");
                carmodel.F_State = 1;//车辆状态为已使用
                carbll.Update(carmodel);
                assign.F_WorkOrderID = string.Join(",", orderid.Split(','));
                assign.F_DriverCode = driver;
                var user = new Bll.T_Sys_UserAccount().GetModel(assign.F_DriverCode);
                if (user == null)
                    return Error("司机不存在");
                assign.F_DriverName = user.F_UserName ;
                assign.F_CarId = carmodel.F_Id;
                assign.F_CarName = carmodel.F_CarName;
                assign.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号
                assign.F_DepartPlace = modellist.Where
                    (x => x.F_WorkOrderCode  == orderid.Split(',').FirstOrDefault().Trim())
                    .FirstOrDefault().F_DepartPlace;
                assign.F_Destination = modellist.Where
                    (x => x.F_WorkOrderCode == orderid.Split(',').LastOrDefault().Trim())
                    .LastOrDefault().F_Destination;
                assign.F_CreateTime = DateTime.Now;
                assign.F_CreateUser = User.F_UserCode;
                assign.F_IsDelete = 0;
                assign.F_State = 0;
                int n = new BLL.T_Car_AssignWorkOrder().Add(assign);
                if (n >0)
                {
                    string deptname = "";
                    var deptmodel = deptbll.GetModel(User.F_DeptId);
                    if (deptmodel != null)
                        deptname = deptmodel.F_DeptName + "-";
                    foreach (var model in modellist)
                    {
                        model.F_DriverCode = driver;//司机
                        model.F_DriverName = user.F_UserName ;//司机姓名
                        model.F_DriverPhon = user.F_Telephone  ;//电话
                        model.F_CarMessage = carmodel.F_CarName ;//车辆信息
                        model.F_CarId = carid;//车辆id
                        model.F_ControlManCode = User.F_UserCode;
                        model.F_ControlManName = User.F_UserName;
                        model.F_State = (int)EnumWorkOrderState.assign;//待确定
                        //model.co
                        if (assist != "")
                        {
                            model.F_IsAssist = 1;
                            model.F_AssistMan = assist;
                            model.F_AssistManName = assistname;
                        }
                        if (!orderbll.Update(model))
                        {
                            return Error("派车失败！");
                        }
                        else
                        {
                            AddOperation(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "派车给" + user.F_UserName + "(" + user.F_UserCode + ")", User.F_UserCode, model.F_State.Value,
                            model.F_WorkOrderCode, n);
                            msg.AddInternalMessagesInfo("您有新的工单请及时查收", "您有新的工单请及时查收\n" + "工单编号:" + assign.F_WorkOrderCode  , driver, User .F_UserCode, EnumSmsType.
                                driver
                        , 0, n.ToString (), assign.F_WorkOrderCode);
                        }
                    }
                }
                else
                    return Error("派车失败！");
                return Success("派车成功！");
           }
            else
                return Error("工单不存在！");
        }

        /// <summary>
        /// 接单
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public ActionResult SureWorkOrder(int orderid)
        {
            if (User!=null)
            {
                var model = new BLL.T_Car_AssignWorkOrder().GetModel(orderid);
                if (model == null)
                    return Error("工单信息错误！");
                if (model.F_DriverCode != User.F_UserCode)
                    return Error("无此操作权限！");
                model.F_State = (int)EnumWorkOrderState.receive;//已接单待完成
                
                if (new BLL.T_Car_AssignWorkOrder().Update(model))
                {
                 
                    var modellist = orderbll.GetModelList($"F_WorkOrderCode in({string.Join(",", model.F_WorkOrderID .Split(','))}) and F_IsDel=0");
                    if (modellist!=null && modellist.Count >0)
                    {
                        string deptname = "";
                        var deptmodel = deptbll.GetModel(User.F_DeptId);
                        if (deptmodel != null)
                            deptname = deptmodel.F_DeptName + "-";
                        foreach (var it in modellist)
                        {
                            it .F_State = (int)EnumWorkOrderState.receive;//已接单待完成
                            it.F_AcceptTime = DateTime.Now;//接单时间
                            AddOperation(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "接单", User.F_UserCode, model.F_State.Value,
                          it.F_WorkOrderCode, model.F_ID );
                            orderbll.Update(it);
                        }
                    }
                    else
                    {
                        return Error("工单不存在");
                    }
                    return Success("操作成功！");
                }
                else return Error("操作失败！");
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 退回工单
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public ActionResult BackWorkOrder(int orderid,string reason,int key,string value)
        {
            if (User != null)
            {
                var model = new BLL.T_Car_AssignWorkOrder().GetModel(orderid);
                if (model == null)
                    return Error("工单信息错误！");
                if (model.F_DriverCode != User.F_UserCode)
                    return Error("无此操作权限！");
                model.F_State = (int)EnumWorkOrderState.reback;//已退回
                string reasonmessage = "";
                reasonmessage = "\n原因:" + value;
                if (!string.IsNullOrEmpty(reason)) { 

                    reasonmessage = reasonmessage +","+ reason;
                }
                if (new BLL.T_Car_AssignWorkOrder().Update(model))
                {
                    var carmodel = carbll.GetModel(model.F_CarId.Value);
                    if (carbll != null)
                        carmodel.F_State = 0;
                    carbll.Update(carmodel);
                    var modellist = orderbll.GetModelList($"F_WorkOrderCode in({string.Join(",", model.F_WorkOrderID.Split(','))}) and F_IsDel=0");
                    if (modellist != null && modellist.Count > 0)
                    {
                        string deptname = "";
                        var deptmodel = deptbll.GetModel(User.F_DeptId);
                        if (deptmodel != null)
                            deptname = deptmodel.F_DeptName + "-";
                        foreach (var it in modellist)
                        {
                            it.F_DriverCode = "";//司机
                            it.F_DriverName = "";//司机姓名
                            it.F_DriverPhon = "";//电话
                            it.F_CarMessage = "";//车辆信息
                            it.F_CarId = null ;//车辆id
                            it.F_ControlManCode = "";
                            it.F_ControlManName = "";
                            it.F_State = (int)EnumWorkOrderState.neworder;//退回待分配
                            it.F_AcceptTime = null;
                            AddOperationAboutKey(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "退单"+ reasonmessage, User.F_UserCode, model.F_State.Value,
                        it.F_WorkOrderCode, model.F_ID,key,value,reason);
                          if (  orderbll.Update(it))
                            {
                                msg.AddInternalMessagesInfo("您有工单被退回", "您有工单被退回\n" + "工单编号:" + it.F_WorkOrderCode+ reasonmessage, model.F_CreateUser 
                                    , User.F_UserCode, EnumSmsType.car
                      , 0, it.F_WorkOrderCode );
                            }

                        }
                    }
                    else
                    {
                        return Error("工单不存在");
                    }
                   
                    return Success("操作成功！");
                }
                else return Error("操作失败！");
            }
            return Error("无操作权限！");
        }

        /// <summary>
        /// 撤回工单
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public ActionResult WithdrawWorkOrder(int orderid)
        {
            if (User != null)
            {
                var model = orderbll.GetModel(orderid);
                if (model !=null )
                {
                    if (model.F_State  !=0)
                    {
                        return Error("工单已分配，不可撤单");
                    }
                    string deptname = "";
                    var deptmodel = deptbll.GetModel(User.F_DeptId);
                    if (deptmodel != null)
                        deptname = deptmodel.F_DeptName + "-";
                    model.F_State = -1;
                    if (orderbll .Update (model))
                    {
                        AddOperation(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "撤单", User.F_UserCode, model.F_State.Value,
                           model.F_WorkOrderCode, 0);
                        return Success("撤回成功");
                    }
                    else
                    {
                        return Error("撤单失败");
                    }
                   
                }
                else
                {
                    return Error("工单不存在");
                }
               
                //var model = new BLL.T_Car_AssignWorkOrder().GetModel(orderid);
                //if (model == null)
                //    return Error("工单信息错误！");
                //if (model.F_CreateUser  != User.F_UserCode)
                //    return Error("无此操作权限！");
                //model.F_State = (int)EnumWorkOrderState.reback;//已退回
                //if (new BLL.T_Car_AssignWorkOrder().Update(model))
                //{
                //    var carmodel = carbll.GetModel(model.F_CarId.Value);
                //    if (carbll != null)
                //        carmodel.F_State = 0;
                //    carbll.Update(carmodel);
                //    var modellist = orderbll.GetModelList($"F_WorkOrderCode in({string.Join(",", model.F_WorkOrderID.Split(','))}) and F_IsDel=0");
                //    if (modellist != null && modellist.Count > 0)
                //    {
                //        string deptname = "";
                //        var deptmodel = deptbll.GetModel(User.F_DeptId);
                //        if (deptmodel != null)
                //            deptname = deptmodel.F_DeptName + "-";
                //        foreach (var it in modellist)
                //        {
                //            it.F_DriverCode = "";//司机
                //            it.F_DriverName = "";//司机姓名
                //            it.F_DriverPhon = "";//电话
                //            it.F_CarMessage = "";//车辆信息
                //            it.F_CarId = null;//车辆id
                //            it.F_ControlManCode = "";
                //            it.F_ControlManName = "";
                //            it.F_State = (int)EnumWorkOrderState.neworder;//退回待分配
                //            AddOperation(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "撤单", User.F_UserCode, model.F_State.Value,
                //        it.F_WorkOrderCode, model.F_ID);
                //            orderbll.Update(it);
                //        }
                //    }
                //    else
                //    {
                //        return Error("工单不存在");
                //    }
                //    return Success("操作成功！");
                //}
                //else return Error("操作失败！");
            }
            return Error("无操作权限！");
        }

        /// <summary>
        /// 撤回工单
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        public ActionResult Withdraw(string WorkOrderCode)
        {
            if (User != null)
            {
                var model = orderbll.GetModelByCode (WorkOrderCode);
                if (model != null)
                {
                    if (model.F_State != 0)
                    {
                        return Error("工单已分配，不可撤单");
                    }
                    string deptname = "";
                    var deptmodel = deptbll.GetModel(User.F_DeptId);
                    if (deptmodel != null)
                        deptname = deptmodel.F_DeptName + "-";
                    model.F_State = -1;
                    if (orderbll.Update(model))
                    {
                        AddOperation(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "撤单", User.F_UserCode, model.F_State.Value,
                           model.F_WorkOrderCode, 0);
                        return Success("撤回成功");
                    }
                    else
                    {
                        return Error("撤单失败");
                    }

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

              
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 发车
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="WorkOrderCode"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public ActionResult StartCar (int orderid,string WorkOrderCode, string file="" )
        {
            var model = new BLL.T_Car_AssignWorkOrder().GetModel(orderid);
            if (model == null)
                return Error("工单信息错误！");
            var carWorkOrder = orderbll.GetModelByCode(WorkOrderCode);
            if (carWorkOrder == null)
                return Error("工单不存在！");
            if(!model.F_WorkOrderID .Contains (carWorkOrder.F_WorkOrderCode.ToString () ))
                return Error("该工单不存在这条记录中！");
            carWorkOrder.F_StartTime = DateTime.Now;
            carWorkOrder.F_State = (int)EnumWorkOrderState.dealing;//处理中
            carWorkOrder.F_StartFile = file;
            if (orderbll .Update (carWorkOrder))
            {
                string deptname = "";
                var deptmodel = deptbll.GetModel(User.F_DeptId);
                if (deptmodel != null)
                    deptname = deptmodel.F_DeptName + "-";
                AddOperation(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "发车", User.F_UserCode, model.F_State.Value,
                         carWorkOrder.F_WorkOrderCode, model.F_ID);
                model.F_State = (int)EnumWorkOrderState.dealing;
                if (new BLL.T_Car_AssignWorkOrder().Update(model))
                {
                    return Success("成功");
                }
                else
                    return Error("失败");
            }
            else
                return Error("发车失败");

        }


        /// <summary>
        /// 到达目的地
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="WorkOrderCode"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public ActionResult  EndCar(int orderid, string WorkOrderCode, string file = "")
        {
            var model = new BLL.T_Car_AssignWorkOrder().GetModel(orderid);
            if (model == null)
                return Error("工单信息错误！");
            var carWorkOrder = orderbll.GetModelByCode(WorkOrderCode);
            if (carWorkOrder == null)
                return Error("工单不存在！");
            if (!model.F_WorkOrderID.Contains(carWorkOrder.F_WorkOrderCode.ToString()))
                return Error("该工单不存在这条记录中！");
            if (carWorkOrder.F_State !=4)
                return Error("该工单未发车！");
            carWorkOrder.F_EndTime = DateTime.Now;
            carWorkOrder.F_State = (int)EnumWorkOrderState.dealed;//待评价
            carWorkOrder.F_StartFile = file;
            if (orderbll.Update(carWorkOrder))
            {
                string deptname = "";
                var deptmodel = deptbll.GetModel(User.F_DeptId);
                if (deptmodel != null)
                    deptname = deptmodel.F_DeptName + "-";
                AddOperation(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "到达目的地", User.F_UserCode, model.F_State.Value,
                         carWorkOrder.F_WorkOrderCode, model.F_ID);
                var carsql = $"select count(1) from T_Car_WorkOrder where F_WorkOrderCode in({string.Join(",", model.F_WorkOrderID.Split(','))}) and F_State not in(7,10) and F_IsDel=0";
                var car = DbHelperSQL.GetSingle(carsql).ToString ();
                msg.AddInternalMessagesInfo("您提交的工单已处理完毕，请及时进行评价", "您提交的工单已处理完毕，请及时进行评价\n" + "工单编号:" + carWorkOrder.F_WorkOrderCode, model.F_CreateUser, User .F_UserCode, EnumSmsType.car 
                      , 0, carWorkOrder.F_WorkOrderCode);
                if (int .Parse(car) <=0)
                {
                    var carmodel = carbll.GetModel(model.F_CarId .Value );
                    if (carbll != null)
                    {
                        carmodel.F_State = 0;
                        new Bll.T_Car_Message().Update(carmodel);
                    }
                   
                    model.F_State = (int)EnumWorkOrderState.finish;
                    if (new BLL.T_Car_AssignWorkOrder().Update(model))
                    {

                        return Success("成功");
                    }
                    else
                        return Error("失败");
                }
                else
                    return Success("成功");
            }
            else
                return Error("到达目的地失败");

        }


        /// <summary>
        /// 自动评价
        /// </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 Car_WorkOrder = new Bll.T_Car_WorkOrder().GetModelList(" F_State=6 and F_IsDel=0 " +
             "and datediff(minute , F_EndTime , getdate())>'" + SX * 60 + "'");
            if (Car_WorkOrder != null && Car_WorkOrder.Count > 0)
            {
                foreach (var model in Car_WorkOrder)
                {
                    Model.T_Car_Evaluate evamodel = new Model.T_Car_Evaluate();
                    if (model != null)
                    {
                        evamodel.F_Evaluator = SX + "小时未评价自动评价工单";
                        evamodel.F_EvaluationTime = DateTime.Now;
                        evamodel.F_Isdelete = 0;
                        evamodel.F_WorkOrderCode = model.F_WorkOrderCode;
                        evamodel.F_Score = 5;
                        evamodel.F_EvaluateUser = "系统";
                        BLL.T_Car_Evaluate evabll = new BLL.T_Car_Evaluate();
                        if (evabll.Add(evamodel) > 0)
                        {
                            model.F_State =10;
                            model.F_FinishTime = DateTime.Now;
                            model.MYD = 0;
                            orderbll.Update(model);
                            AddOperation(SX + "小时评价自动评价了工单", "", model.F_State.Value,
                      model.F_WorkOrderCode, 0);

                        }
                        else
                            continue;

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

        }



        /// <summary>
        /// 评价工单
        /// </summary>
        /// <returns></returns>
        public ActionResult EvaluateWorkorder(string WorkOrderCode,string Evaluation,int score=0)
        {
            if (score<=3&&string .IsNullOrEmpty (Evaluation))
            {
                return Error("请输入评价内容");
            }
            var model = new Bll.T_Car_WorkOrder().GetModelByCode (WorkOrderCode);
            Model.T_Car_Evaluate evamodel = new Model.T_Car_Evaluate();
            if (model != null)
            {
                evamodel.F_Evaluator = Evaluation;
                evamodel.F_EvaluationTime = DateTime.Now;
                evamodel.F_Isdelete = 0;
                evamodel.F_WorkOrderCode = model.F_WorkOrderCode;
                evamodel.F_Score = score;
                evamodel.F_EvaluateUser = User .F_UserCode ;
                BLL.T_Car_Evaluate evabll = new BLL.T_Car_Evaluate();
                if (evabll.Add(evamodel) > 0)
                {
                    model.F_State = 10;
                    model.F_FinishTime = DateTime.Now;
                    
                    if(orderbll.Update(model))
                    {
                        string deptname = "";
                        var deptmodel = deptbll.GetModel(User.F_DeptId);
                        if (deptmodel != null)
                            deptname = deptmodel.F_DeptName + "-";
                        AddOperation(deptname + User.F_UserName + "(" + User.F_UserCode + ")" + "评价了工单", User.F_UserCode, model.F_State.Value,
                                 model.F_WorkOrderCode, 0);
                        if (score < 3)
                        {
                            model.MYD = 2;
                            msg.AddInternalMessagesInfo("您有工单被差评", "您有工单被差评\n" + "工单编号:" + model.F_WorkOrderCode + "\n差评原因:" + Evaluation, model.F_DriverCode, User.F_UserCode, EnumSmsType.car
                       , 0, model.F_WorkOrderCode);
                        }
                        else if (score == 3)
                        {
                            model.MYD = 1;
                        }
                        else
                        {
                            model.MYD = 0;
                        }

                        orderbll.Update(model);
                    }
                     else
                    return Success("评价失败"); ;
                }
                else
                    return Success("评价失败"); ;

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

        }



        /// <summary>
        /// 获取科室部门列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDept()
        {
            //int userId = User.F_UserId;
            //if (userId != 0)
            //{
                List<Model.T_Sys_Department> dmodel = deptbll.GetModelList(" F_State=1");
                if (dmodel.Count > 0)
                {
                var obj = new
                {
                    rows = dmodel.Select(p => new
                    {
                        deptid = p.F_DeptId,
                        deptName = p.F_DeptName

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

                }
                else
                    return Success("暂无信息！");
            //}
            //return
            //    Error("无操作权限！");
        }
        /// <summary>
        /// 获取科室人员信息
        /// </summary>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public ActionResult GetPerson(int deptid)
        {
            if (deptid == 0)
                return Error("请先选择科室！");
            var dmodel = deptbll.GetModel(deptid);
            if (dmodel != null)
            {
                string sql = "F_DeptId="+ deptid;
                sql += "and F_EnableFlag=1";
                var ua = userbll.GetModelList(sql);
                if (ua.Count > 0)
                {
                    var obj = new
                    {
                        rows = ua.Select(p => new
                        {
                            usercode = p.F_UserCode,
                            username = p.F_UserName
                        })
                    };
                    return Content(obj.ToJson());
                }
                else return Success("暂无记录");
            }        
           return Error("不存在此科室信息");
        }
        /// <summary>
        /// 获取科室人员信息
        /// </summary>
        /// <param name="deptid"></param>
        /// <returns></returns>
        public ActionResult GetUserList(string rolecode="SJ" )
        {
            if (string .IsNullOrEmpty (rolecode))
                return Error("请先选择角色！");
            var dmodel = new Bll .T_Sys_Role() .GetModel(rolecode);
            if (dmodel != null)
            {
                string sql = $"F_RoleId={dmodel.F_RoleId } and F_DeleteFlag=0"  ;
                var ua = userbll.GetModelList(sql);
                if (ua.Count > 0)
                {
                    var obj = new
                    {
                        rows = ua.Select(p => new
                        {
                            usercode = p.F_UserCode,
                            username = p.F_UserName
                        })
                    };
                    return Content(obj.ToJson());
                }
                else return Success("暂无记录");
            }
            return Error("不存在此角色信息");
        }
        /// <summary>
        /// 添加操作记录
        /// </summary>
        /// <param name="message"></param>
        /// <param name="user"></param>
        /// <param name="state"></param>
        /// <param name="WorkOrderCode"></param>
        /// <param name="assignid"></param>
        /// <returns></returns>
        public int  AddOperation(string message,string user,int state,string WorkOrderCode,int assignid)
        {
            Model.T_Car_Operation oper = new Model.T_Car_Operation();
            oper.F_Message = message;
            oper.F_CreateUser = user;
            oper.F_IsDelete = 0;
            oper.F_State = state;
            oper.F_WorkOrderCode = WorkOrderCode;
            oper.F_AssignID = assignid;
            oper.F_CreateTime = DateTime.Now;
            int n = new BLL.T_Car_Operation().Add(oper);
            return n;
        }

           /// <summary>
        /// 添加操作记录
        /// </summary>
        /// <param name="message"></param>
        /// <param name="user"></param>
        /// <param name="state"></param>
        /// <param name="WorkOrderCode"></param>
        /// <param name="assignid"></param>
        /// <returns></returns>
        public int  AddOperationAboutKey(string message,string user,int state,string WorkOrderCode,int assignid,int key,string value,string reason)
        {
            Model.T_Car_Operation oper = new Model.T_Car_Operation();
            oper.F_Message = message;
            oper.F_CreateUser = user;
            oper.F_IsDelete = 0;
            oper.F_State = state;
            oper.F_WorkOrderCode = WorkOrderCode;
            oper.F_AssignID = assignid;
            oper.F_CreateTime = DateTime.Now;
            oper.F_AboutKey = key;
            oper.F_AboutReason = value;
            oper.F_EnterReason = reason;
            int n = new BLL.T_Car_Operation().Add(oper);
            return n;
        }

    }
}