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

namespace RMYY_CallCenter_Api.Controllers.WorkOrder
{
    public class T_Acc_WorkOrderController : BaseController
    {
        private Bll.T_Acc_WorkOrder orderbll = new Bll.T_Acc_WorkOrder();
        private Bll.T_Sys_UserAccount userbll = new Bll.T_Sys_UserAccount();
        private Bll.T_Dis_WorkOrderItem itembll = new Bll.T_Dis_WorkOrderItem();
        private Bll.AddLogBll logbll = new Bll.AddLogBll();

        /// <summary>
        /// 陪检获取列表 陪检服务 血站取血
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult GetList(string keyword,string starttime = "", string endtime = "", int pageindex = 1, int pagesize = 10, int state = -1, int type=0)
        {
            if (User != null)
            {
                string transql = "";
                List<string> wokerlist = new List<string>();
                #region 查询条件
                DataTable data = new DataTable();
                if (type <= 0)
                    return Error("请输入工单类型！");
                if (type != (int)EnumWorkOrder.Serve && type != (int)EnumWorkOrder.TakeBlood)
                    return Error("工单类型错误！");
                string sql = $" and F_IsDel=0 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 (!string.IsNullOrEmpty(keyword))
                {
                    sql += $"and (F_WorkOrderCode like '%" + keyword.Trim() + "%' or F_ProposerCode like '%" + keyword.Trim() + "%' or F_ProposerPhon like '%" + keyword.Trim() + "%')";
                }
                if (state >= 0 && User.F_RoleCode != "ZYY")
                {
                    sql += $"and F_State=" + state;
                }
                if (User.F_DeptCode == "ZZWY" && User.F_RoleCode != "ZYY")//综合保障中心
                {
                    if (User.F_UserCode != "8000")
                        sql += $" and F_ControlManCode=" + User.F_UserCode;
                }
                else if (User.F_RoleCode == "ZYY")//转运人判断
                {
                    transql = GetTranPersonsql(User.F_UserCode,type, state);
                    //string assignsql = GetTransql(User.F_UserCode, type);
                    if (transql != "")
                    {
                        wokerlist = transql.Split(',').Distinct().ToList();
                    }
                    if (wokerlist.Count > 0)
                    {
                        sql += $" and F_Id in (" + string.Join(",", wokerlist) + ")";
                    }
                    else
                    {
                        sql += $" and F_Id in (0)";
                    }
                }
                else /*if (User.F_DeptCode == "CK")//申请科室*/
                {
                    //int[] wostate = { (int)EnumAccWorkOrderState.end, (int)EnumAccWorkOrderState.finish };
                    //sql += $" and F_ProposerDeptId=" + User.F_DeptId + "";
                    //if (state == 6)
                    //{
                    //    sql += $" and F_State not in " +string.Join(",", wostate) + "";
                    //}
                   sql += $" and F_ProposerDeptId=" + User.F_DeptId + "";
                }

                #endregion
                int recordCount = 0;
                if (!string.IsNullOrEmpty(sql))
                {
                    data = Bll.PagerBll.GetListPager
                        (
                        "T_Acc_WorkOrder aa",
                        "F_Id",
                        "*",
                        sql,
                        "ORDER BY F_Id desc",
                        pagesize,
                        pageindex,
                        true,
                        out recordCount
                        );
                }
                var modellist = orderbll.DataTableToList(data);
                if (modellist.Count > 0)
                {

                    if (modellist.Count > 0)
                    {
                        foreach (var item in modellist)
                        {
                            if (User.F_RoleCode == "ZYY")
                            {
                                int? wostate = itembll.GetModelList("F_WoID=" + item.F_Id + " and (F_CreateUser=" + User.F_UserCode + " or F_NextUser like '%" + User.F_UserCode + "%')").OrderByDescending(pp => pp.F_ID).FirstOrDefault().F_WoState;
                                item.F_Wostate = EnumHelper.GetDescription((EnumAccWorkOrderState)wostate);
                                item.F_State = wostate;
                            }
                            else
                            {
                                item.F_Wostate = EnumHelper.GetDescription((EnumAccWorkOrderState)item.F_State);
                            }
                            item.F_SitMan = item.F_ControlManName + '(' + item.F_ControlManCode + ')';
                            item.rolecode = User.F_RoleCode;
                            item.deptcode = User.F_DeptCode;
                        }
                    }
                }

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


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

        /// <summary>
        /// 转运人待查收工单
        /// </summary>
        /// <param name="usercode"></param>
        /// <returns></returns>
        private string GetTransql(string usercode, int type)
        {
            string str = string.Empty;
            var list = itembll.GetModelList("F_OptType=" + (int)EnumDisItemOpt.assign + "and F_IsUsed='0' and F_WoType=" + type + " and F_WoState=" + (int)EnumDisWorkOrderState.assign + " and F_NextUser=" + usercode + " ").Select(t => t.F_WoID).Distinct().ToList();
            if (list.Count > 0)
                foreach (var item in list)
                {
                    str = string.IsNullOrEmpty(str) ? item.ToString() : str + "," + item.ToString();
                }
            return str;
        }
        /// <summary>
        /// 转运人操作的工单
        /// </summary>
        /// <param name="usercode"></param>
        /// <param name="roleid"></param>
        /// <returns></returns>
        private string GetTranPersonsql(string usercode, int type,int wostate)
        {
            string wokerlist = "";
            string[] wokerarr = { };
            string sql = "";
            if (wostate > 0)
            {

                sql = $"  isnull(F_IsUsed, '0') = '0' and(F_CreateUser = " + usercode + " or  F_NextUser = " + usercode + ") and F_WoType=" + type + " and F_WoState=" + wostate + "";
            }
            else
            {
                sql = $"  isnull(F_IsUsed, '0') = '0' and(F_CreateUser = " + usercode + " or  F_NextUser = " + usercode + ") and F_WoType=" + type + "";
            }
            var itemlist = itembll.GetModelList(sql).Select(t => t.F_WoID).Distinct<long>().ToList();
            if (itemlist.Count > 0)
            {
                foreach (var item in itemlist)
                {
                    wokerlist = string.IsNullOrEmpty(wokerlist) ? item.ToString() : wokerlist + "," + item.ToString();
                }
                if (wokerlist != "")
                    wokerarr = wokerlist.Split(',');
            }
            return wokerlist;
        }

        private string GetWoStateName(int woid, string usercode)
        {
            string wostate = "";
            var model = orderbll.GetModel(woid);
            var item = itembll.GetModelList("F_WoID=" + woid + " and (F_CreateUser=" + usercode + " or F_NextUser=" + usercode + ")").OrderByDescending(pp => pp.F_ID).FirstOrDefault();
            if (model != null && item != null)
            {
                if (model.F_State == (int)EnumDisWorkOrderState.finish)
                    wostate = "已完结";
                else wostate = EnumHelper.GetDescription((EnumDisWorkOrderState)item.F_OptType);
            }
            return wostate;
        }

        /// <summary>
        /// 获取工单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetModelDetail(int id)
        {
            if (User != null)
            {
                if (id <= 0)
                {
                    return Error("请选择要查询的工单！");
                }
                var model = orderbll.GetModel(id);
                if (model != null)
                {
                    //var aa = model?.F_Type ?? 0;
                    string sql = "F_WoID = " + id + " and F_WoType=" + model.F_Type + "";
                    model.F_Wostate = EnumHelper.GetDescription((EnumAccWorkOrderState)model.F_State);
                    model.F_SitMan = model.F_ControlManName + '(' + model.F_ControlManCode + ')';
                    model.rolecode = User.F_RoleCode;
                    model.HosName = new Bll.T_Wowo_repairyqbll().GetModel(model.F_HosId ?? 0)?.T_Woname ?? "";
                    var itemlist = itembll.GetModelList(sql);
                    //List<Con_WorkOrderInput> Input = modeltoopi(list);
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        model = model,
                        itemlist = itemlist
                    };
                    return Content(obj.ToJson());

                }
                else
                    return Error("没有查询到此工单！");
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 报表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public ActionResult GetListExpt( string keyword, string starttime = "", string endtime = "", int state = -1, int pageindex = 1, int pagesize = 10, int isdc = 0, int type=0)
        {
            if (User != null)
            {
                #region 查询条件
                if (type <= 0)
                    return Error("请输入正确的工单类型！");
                if (type != (int)EnumWorkOrder.Serve && type != (int)EnumWorkOrder.TakeBlood)
                    return Error("工单类型错误！");
                string sql = $" and F_IsDel=0 and F_Type=" + type;
                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_ProposerPhon like '%" + keyword.Trim() + "%')";
                }
                if (state >= 0)
                {
                    sql += $"and F_State=" + state;
                }
                #endregion
                if (isdc > 0)
                {
                    if (type == (int)EnumWorkOrder.Serve)
                    {
                        data = DbHelperSQL.Query(" select  F_WorkOrderCode 工单编号,F_ProposerDeptName 申请科室,F_ProposerName 申请人,F_ProposerPhon 联系电话, "
                           + $" F_Source 渠道来源,F_InpatientNum  住院号,(F_PatientName + F_BedNum) as 患者信息,F_CheckItem 检查项目,F_InspectionTime 预约时间,F_IsWithPipe 是否带管,F_TravelMode 出行方式,F_NursingLevel 护理级别,F_ControlManName+'('+F_ControlManCode+')'as 调度员,F_TransPerson 转运人,F_Remark 备注"
                          + $" from T_Acc_WorkOrder wo WITH(NOLOCK)  where 1=1 " + sql).Tables[0];
                        NPOIHelper nopi = new NPOIHelper();
                        //data = new Bll.T_Acc_WorkOrder().GetListExpt(sql).Tables[0];
                        if (nopi.ExportToExcel("陪检服务统计报表", data) == "")
                        {
                            return Success("导出成功！");
                        }
                        else return Error("导出失败！");
                    }
                    else if (type == (int)EnumWorkOrder.TakeBlood)
                    {
                        data = DbHelperSQL.Query(" select  F_WorkOrderCode 工单编号,F_ProposerDeptName 申请科室,F_ProposerName 申请人,F_ProposerPhon 联系电话,F_CarMessage 车辆信息,F_DriverName 司机, "
                          + $"F_ControlManName+'('+F_ControlManCode+')'as 调度员,F_TransPerson 转运人,F_Remark 备注"
                         + $" from T_Acc_WorkOrder wo WITH(NOLOCK)  where 1=1 " + sql).Tables[0];
                        NPOIHelper nopi = new NPOIHelper();
                        //data = new Bll.T_Acc_WorkOrder().GetListExpt(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_Acc_WorkOrder aa",
                            "F_Id",
                            "*",
                            sql,
                            "ORDER BY F_Id desc",
                            pagesize,
                            pageindex,
                            true,
                            out recordCount
                            );
                    }
                    var modellist = orderbll.DataTableToList(data);
                    if (modellist.Count > 0)
                    {

                        if (modellist.Count > 0)
                        {
                            foreach (var item in modellist)
                            {
                                item.F_Wostate = EnumHelper.GetDescription((EnumAccWorkOrderState)item.F_State);
                                item.F_SitMan = item.F_ControlManName + '(' + item.F_ControlManCode + ')';
                                item.rolecode = User.F_RoleCode;
                            }
                        }
                    }
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = modellist,
                        total = recordCount
                    };
                    return Content(obj.ToJson());
                }

            }
            return Error("无操作权限！");
        }
        //private string[] col()
        //{
        //    string[] cel =
        //    {
        //        "工单编号","申请科室","申请人","联系电话","渠道来源","住院号","患者信息","检查项目","预约时间","是否带管","出行方式","护理级别","调度员","转运人","备注"
        //    };
        //    return cel;

        //}


        /// <summary>
        /// 工单添加
        /// </summary>
        /// <param name="type"></param>
        /// <param name="dept"></param>
        /// <param name="deptname"></param>
        /// <param name="usercode"></param>
        /// <param name="username"></param>
        /// <param name="phon"></param>
        /// <param name="patient"></param>
        /// <param name="bednum"></param>
        /// <param name="inpatientnum"></param>
        /// <param name="checkitem"></param>
        /// <param name="yuyuetime"></param>
        /// <param name="attention"></param>
        /// <param name="travel"></param>
        /// <param name="nursinglevel"></param>
        /// <param name="withpipe"></param>
        /// <param name="remark"></param>
        /// <param name="callid"></param>
        /// <returns></returns>
        public ActionResult AddWorkOrder(int type,int hosid, int dept, string deptname, string usercode, string username, string phon, string patient, string bednum, string inpatientnum, string checkitem, string yuyuetime, string attention, string travel, string nursinglevel, string withpipe, string remark, string callid = "")
        {
            if (User != null)
            {
                #region 添加条件
                if (type != (int)EnumWorkOrder.Serve && type != (int)EnumWorkOrder.TakeBlood)
                    return Error("工单类型错误！");
                if (hosid < 0)
                    return Error("请选择院区！");
                if (dept < 0)
                    return Error("请选择申请科室！");
                if (usercode == "")
                    return Error("请选择申请人！");
                if (phon == "")
                    return Error("请输入联系电话！");
                #endregion
                var model = new Model.T_Acc_WorkOrder();
                model.F_Type = type;//工单类型  陪检,取血
                model.F_Source = "PC端";
                model.F_CallID = callid;
                model.F_State = (int)EnumAccWorkOrderState.neworder;//新工单待转派
                model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号
                model.F_HosId = hosid;//院区
                model.F_ProposerDeptId = dept;//申请科室
                model.F_ProposerDeptName = deptname;//科室名称
                model.F_ProposerCode = usercode;//申请人
                model.F_ProposerName = username;
                model.F_ProposerPhon = phon;
                model.F_Remark = remark;//备注
                if (type == (int)EnumWorkOrder.Serve)
                {
                    model.F_PatientName = patient;//患者姓名
                    model.F_BedNum = bednum;//床号
                    model.F_InpatientNum = inpatientnum;//住院号
                    model.F_CheckItem = checkitem;//检查项目
                    model.F_InspectionTime = Convert.ToDateTime(yuyuetime ?? "");//检查预约时间
                    model.F_NeedAttention = attention;//注意事项
                    model.F_TravelMode = travel;//出行方式
                    model.F_NursingLevel = nursinglevel;//护理级别
                    model.F_IsWithPipe = withpipe;//是否带管 引流管、尿管、胃管、PICC、CVC、输液管、其他
                }
                model.F_CreateTime = DateTime.Now;
                model.F_CreateCode = User.F_UserCode;
                model.F_CreateName = User.F_UserName;
                model.F_IsDel = 0;
                int n = orderbll.Add(model);
                if (n > 0)
                {
                    var wmodel = orderbll.GetModel(n);
                    logbll.AddLog(n, 0, type, User.F_UserName + "(" + User.F_UserCode + ")" + "创建新工单", 0, (int)EnumAccItemOpt.create, "", 0, User.F_UserCode);
                    return Success("操作成功！");
                }
                else return Error("添加失败");
            }
            return Error("无操作权限");
        }

        /// <summary>
        /// 修改工单
        /// </summary>
        /// <param name="woid"></param>
        /// <param name="type"></param>
        /// <param name="dept"></param>
        /// <param name="deptname"></param>
        /// <param name="usercode"></param>
        /// <param name="username"></param>
        /// <param name="phon"></param>
        /// <param name="patient"></param>
        /// <param name="bednum"></param>
        /// <param name="inpatientnum"></param>
        /// <param name="checkitem"></param>
        /// <param name="yuyuetime"></param>
        /// <param name="attention"></param>
        /// <param name="travel"></param>
        /// <param name="nursinglevel"></param>
        /// <param name="withpipe"></param>
        /// <param name="remark"></param>
        /// <param name="callid"></param>
        /// <returns></returns>
        public ActionResult UpdateWorkOrder(int woid, int hosid, int type, int dept, string deptname, string usercode, string username, string phon, string patient, string bednum, string inpatientnum, string checkitem, string yuyuetime, string attention, string travel, string nursinglevel, string withpipe, string remark, string callid = "")
        {
            if (User != null)
            {
                #region 添加条件
                if (woid <= 0)
                    return Error("请选择要修改的工单");
                if (type != (int)EnumWorkOrder.Serve && type != (int)EnumWorkOrder.TakeBlood)
                    return Error("工单类型错误！");
                if (hosid < 0)
                    return Error("请选择院区！");
                if (dept < 0)
                    return Error("请选择申请科室！");
                if (usercode == "")
                    return Error("请选择申请人！");
                if (phon == "")
                    return Error("请输入联系电话！");
                var model = orderbll.GetModel(woid);
                if (model == null)
                    return Error("不存在此工单信息！");
                if (model.F_State == (int)EnumDisWorkOrderState.assign || model.F_TransPersonCode != "")
                    return Error("工单已指派不能修改！");
                #endregion
                model.F_HosId = hosid;//院区
                model.F_ProposerDeptId = dept;//申请科室
                model.F_ProposerDeptName = deptname;//科室名称
                model.F_ProposerCode = usercode;//申请人
                model.F_ProposerName = username;
                model.F_ProposerPhon = phon;
                model.F_Remark = remark;//备注
                if (type == (int)EnumWorkOrder.Serve)
                {
                    model.F_PatientName = patient;//患者姓名
                    model.F_BedNum = bednum;//床号
                    model.F_InpatientNum = inpatientnum;//住院号
                    model.F_CheckItem = checkitem;//检查项目
                    model.F_InspectionTime = Convert.ToDateTime(yuyuetime ?? "");//检查预约时间
                    model.F_NeedAttention = attention;//注意事项
                    model.F_TravelMode = travel;//出行方式
                    model.F_NursingLevel = nursinglevel;//护理级别
                    model.F_IsWithPipe = withpipe;//是否带管 引流管、尿管、胃管、PICC、CVC、输液管、其他
                }
                bool n = orderbll.Update(model);
                if (n)
                {
                   logbll.AddLog(woid, (int)model.F_State, (int)model.F_Type, User.F_UserName + "(" + User.F_UserCode + ")" + "修改工单", (int)EnumAccItemOpt.update, (int)EnumAccItemOpt.update, "", 0, User.F_UserCode);
                    return Success("操作成功！");
                }
                else return Error("修改失败");
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 转派
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult AssignWo(int woid, string transMestr, string drivername = "", string carmessage = "", string driverphon = "")
        {
            if (User != null)
            {
                string transperson = "";
                string transcodestr = "";
                if (woid == 0)
                    return Error("工单编号错误！");
                var omodel = orderbll.GetModel(woid);
                if (omodel != null)
                {
                    if (transMestr == "")
                        return Error("转运人的信息不能为空！");
                    string[] _list = transMestr.TrimEnd(',').Split(',');
                    for (int i = 0; i < _list.Length; i++)
                    {
                        string[] _temp = _list[i].Split('|');
                        string code = _temp[0];
                        string phon = _temp[1];
                        string talkie = _temp[2];
                        string name = "";
                        if (code != "" && phon != "")
                        {
                            try { name = userbll.GetModel(code).F_UserName; }
                            catch { return Error("转运人信息不正确"); }
                            bool n = AssignTrans(User, omodel, "", code, phon, talkie);
                            if (n)
                            {
                                transperson = string.IsNullOrEmpty(transperson) ? name + "(" + code + ")" : transperson + "," + name + "(" + code + ")";
                                transcodestr = string.IsNullOrEmpty(transcodestr) ? code : transcodestr + "," + code;
                                continue;
                            }
                        }
                        else return Error("转运人编号和手机号不能为空！");
                    }
                    omodel.F_ControlManCode = User.F_UserCode;//调度人
                    omodel.F_ControlManName = User.F_UserName;
                    omodel.F_TransPersonCode = transcodestr;//转派人编码字符串
                    omodel.F_TransPerson = transperson;
                    omodel.F_State = (int)EnumAccWorkOrderState.assign;//已指派待查收
                    if (omodel.F_Type == (int)EnumWorkOrder.TakeBlood)
                    {
                        if (drivername == "" || carmessage == "" || driverphon == "")
                            return Error("请填写司机车辆信息！");
                        omodel.F_DriverName = drivername;//司机姓名
                        omodel.F_CarMessage = carmessage;//车辆信息
                        omodel.F_DriverPhon = driverphon;//司机电话
                    }
                    if (orderbll.Update(omodel))
                        return Success("转派成功！");
                    else return Error("转派失败！");
                }
                return Error("转派失败,不存在此工单编号！");
            }
            return Error("无操作权限！");
        }

        /// <summary>
        /// 工单查收
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult SureWo(int woid)
        {
            if (User != null)
            {
                if (woid == 0)
                    return Error("工单编号错误！");
                var omodel = orderbll.GetModel(woid);
                if (omodel != null)
                {
                    if (DealWO(User, omodel, "", "", 1))
                        return Success("操作成功，请尽快处理工单！");
                    else return Error("工单操作失败！");
                }
                return Error("操作失败,不存在此工单编号！");
            }
            return Error("无操作权限！");
        }

        /// <summary>
        /// 到达
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult ArriveWo(int woid)
        {
            if (User != null)
            {
                if (woid == 0)
                    return Error("工单编号错误！");
                var omodel = orderbll.GetModel(woid);
                if (omodel != null)
                {
                    if (DealWO(User, omodel, "", "", 2))
                        return Success("操作成功，请尽快处理工单！");
                    else return Error("工单操作失败！");
                }
                return Error("操作失败,不存在此工单编号！");
            }
            return Error("无操作权限!");
        }


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




        /// <summary>
        /// 待处理
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult DealBooldWo(int woid)
        {
            if (User != null)
            {
                if (woid == 0)
                    return Error("工单编号错误！");
                var omodel = orderbll.GetModel(woid);
                if (omodel != null)
                {
                    if (DealWO(User, omodel, "", "", 5))
                        return Success("操作成功，请尽快处理工单！");
                    else return Error("工单操作失败！");
                }
                return Error("操作失败,不存在此工单编号！");
            }
            return Error("无操作权限!");
        }

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


        /// <summary>
        /// 完结工单
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult OverWo(int woid, string sureman, string phon, string talkie)
        {
            if (User != null)
            {
                if (woid == 0)
                    return Error("工单编号错误！");
                if (string.IsNullOrEmpty(sureman))
                    return Error("请填写确认人");
                var user = userbll.GetModel(sureman);
                if (user == null)
                    return Error("不存在此确认人信息请正确填写！");
                var omodel = orderbll.GetModel(woid);
                if (omodel != null)
                {
                    if (omodel.F_ProposerDeptId != User.F_DeptId)
                        return Error("无操作权限！");
                    var n = AddLogTrans(woid, (int)omodel.F_State, (int)omodel.F_Type, user.F_UserName + "(" + user.F_UserCode + ")" + "确认完结工单", (int)EnumDisItemType.deal, (int)EnumDisItemOpt.over, "", "", phon, talkie, 0, User);
                    //if (DealWO(ua, omodel, "", "", 6))
                    if (n > 0)
                    {
                        omodel.F_FinishTime = DateTime.Now;
                        omodel.F_State = (int)EnumDisWorkOrderState.finish;
                        omodel.F_SureMan = sureman;
                        omodel.F_SureManName = user.F_UserName;
                        omodel.F_SureManPhon = phon;
                        omodel.F_SureManTalkie = talkie;
                        orderbll.Update(omodel);
                        return Success("操作成功！");
                    }
                    else return Error("操作失败！");
                }
                return Error("操作失败,不存在此工单编号！");
            }
            return Error("无操作权限!");
        }




        /// <summary>
        /// 处理工单
        /// </summary>
        /// <param name="nowUser"></param>
        /// <param name="model"></param>
        /// <param name="cont"></param>
        /// <param name="F_Files"></param>
        /// <param name="isover"></param>
        /// <returns></returns>
        public bool DealWO(Model.T_Sys_UserAccount nowUser, Model.T_Acc_WorkOrder model, string cont, string F_Files = "", int type = 1)
        {
            #region 工单处理

            var opt = "";
            int optbut = 0;
            int wostate = 0;
            int wostate1 = 0;
            string[] transcode = { };
            var fmodel = new Model.T_Dev_WorkOrder();
            if (type == 1)
            {
                opt = "查收工单";
                optbut = (int)EnumAccItemOpt.receive;//查收
                if (model.F_Type == (int)EnumWorkOrder.TakeBlood)
                {
                    wostate1 = (int)EnumAccWorkOrderState.receive;//已查收待处理
                }
                else if (model.F_Type == (int)EnumWorkOrder.Serve)
                {
                    wostate1 = (int)EnumAccWorkOrderState.arrive;//已查收待陪检
                }
            }
            //if (type == 2)
            //{
            //    opt = "查收工单";
            //    optbut = (int)EnumAccItemOpt.receive;//到达
            //    wostate1 = (int)EnumAccWorkOrderState.arrive;//已查收待陪检
            //}
            if (type == 3)
            {
                opt = "陪检中";
                optbut = (int)EnumAccItemOpt.keep;//陪检中
                wostate1=(int)EnumAccWorkOrderState.keep;//陪检中
            }
            if (type == 4)
            {
                opt = "完成工单";
                optbut = (int)EnumAccItemOpt.end;//完成
                wostate1 = (int)EnumAccWorkOrderState.end;//完成
            }
            if (type == 5)
            {
                opt = "处理工单";
                optbut = (int)EnumAccItemOpt.deal;//处理
                wostate1 = (int)EnumAccWorkOrderState.dealing;//处理中
            }
            //if (type == 5)
            //{
            //    opt = "异常结束工单";
            //    optbut = (int)EnumDevItemOpt.abreback;
            //    wostate = (int)EnumDevWorkOrderState.abreback;//异常结束
            //}
            //if (type == 6)
            //{
            //    opt = "完结工单";
            //    optbut = (int)EnumMatItemOpt.end;
            //    wostate = (int)EnumMatWorkOrderState.finish;//已完结
            //}
            //#region 读取当前登录人部门
            //string deptname = "";
            //var deptmodel = deptbll.GetModel(nowUser.F_DeptId);
            //if (deptmodel != null)
            //{
            //    deptname = deptmodel.F_DeptName + "-";
            //}
            //#endregion
            var optcont = "";
            if (!string.IsNullOrEmpty(cont))
                optcont = "，说明：" + cont;
            var content = nowUser.F_UserName + "(" + nowUser.F_UserCode + ")" + opt + optcont;
            var itemid =logbll.AddLog(model.F_Id, wostate1, (int)model.F_Type, content, (int)EnumDevItemType.deal, optbut, "", 0, nowUser.F_UserCode);
            if (itemid > 0)
            {
                #region 判断工单的状态
                if (!string.IsNullOrEmpty(model.F_TransPersonCode) && type == 1 || type == 2 || type == 3 || type == 4 || type == 5)
                {
                    int i = 0;
                    transcode = model.F_TransPersonCode.Split(',');
                    foreach (var item in transcode)
                    {
                        if (type == 1)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=" + (int)EnumAccItemOpt.receive + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                        //else if (type == 2)
                        //{
                        //    if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=" + (int)EnumAccItemOpt.arrive + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                        //        i++;
                        //}
                        else if (type == 3)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=" + (int)EnumAccItemOpt.keep + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                        else if (type == 4)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=" + (int)EnumAccItemOpt.end + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                        else if (type == 5)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=" + (int)EnumAccItemOpt.deal + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                    }
                    if (i == transcode.Count())
                    {
                        if (type == 1)
                        {
                            wostate = (int)EnumAccWorkOrderState.arrive;//已查收待陪检
                        }
                        //else if (type == 2)
                        //{
                        //    wostate = (int)EnumAccWorkOrderState.arrive;//已到达
                        //}
                        else if (type == 3)
                        {
                            wostate = (int)EnumAccWorkOrderState.keep;//陪检中
                        }
                        else if (type == 4)
                        {
                            wostate = (int)EnumAccWorkOrderState.end;//已完成
                        }
                        else if (type == 5)
                        {
                            wostate = (int)EnumAccWorkOrderState.dealing;//处理中
                        }
                    }
                    else
                    {
                        wostate = (int)model.F_State;//工单状态不变
                    }

                }
                #endregion
                #region 处理工单            
                model.F_State = wostate;
                //if (type == 6)
                //{
                //    model.F_FinishTime = DateTime.Now;
                //}
                orderbll.Update(model);
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }


        /// <summary>
        /// 转派工单
        /// </summary>
        private bool AssignTrans(Model.T_Sys_UserAccount nowUser, Model.T_Acc_WorkOrder wokerModel, string cont, string usercode, string userphon, string usertalkie)
        {
            string touser = ""; string tousername = "";
            int clbm = 0;
            Model.T_Sys_UserAccount clus = new Model.T_Sys_UserAccount();
            #region 获取接收人
            if (usercode != "")
            {
                clus = userbll.GetModel(usercode);
                clbm = clus.F_DeptId;
                if (clus != null)
                {
                    touser = clus.F_UserCode;
                    tousername = clus.F_UserName + "(" + clus.F_UserCode + ")";
                }
            }
            #endregion
            #region 工单处理
            var opt = "指派";
            int optbut = 0;
            int wostate = 0;
            string content = "";
            long itemid = 0;
            var optcont = "";
            if (!string.IsNullOrEmpty(cont))
                optcont = "，说明：" + cont;
            optbut = (int)EnumMatItemOpt.assign;
            wostate = (int)EnumMatWorkOrderState.assign;//已指派待查收
            content = nowUser.F_UserName + "(" + nowUser.F_UserCode + ")" + opt + "工单给 " + tousername + optcont;
            itemid = AddLogTrans(wokerModel.F_Id, wostate, (int)wokerModel.F_Type, content, (int)EnumMatItemType.deal, optbut, touser, clus.F_UserName, userphon, usertalkie, clbm, nowUser);
            #endregion
            if (itemid > 0)
            {
                return true;
            }
            else return false;

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

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

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


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

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

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

        /// <summary>
        /// 删除工单
        /// </summary>
        /// <returns></returns>
        public ActionResult DelWorkOrder(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                //StringBuilder sb = new StringBuilder();
                foreach (var item in ids)
                {
                    //sb.Append("'" + item + "',");
                    Model.T_Acc_WorkOrder womodel = orderbll.GetModel(Convert.ToInt32(item));
                    if (womodel != null && womodel.F_State == (int)EnumAccWorkOrderState.neworder && womodel.F_IsDel==0)//0)
                    {
                        #region 修改工单记录
                        womodel.F_IsDel = 1;
                        womodel.F_DeleteBy = User.F_UserCode;
                        womodel.F_DeleteTime = DateTime.Now;
                        orderbll.Update(womodel);
                        #endregion

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

        public ActionResult test()
        {
            int recordCount = 0;
            var data = Bll.PagerBll.GetListPager
                         (
                         "(select * from T_Acc_WorkOrder) aa",
                         "F_Id",
                         "*",
                         "",
                         "ORDER BY F_Id desc",
                         10,
                         1,
                         true,
                         out recordCount
                         );
            var modellist = orderbll.DataTableToList(data);
            if (modellist.Count > 0)
            {
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = modellist
                };
                return Content(obj.ToJson());

            }
            else return Error("暂无工单记录");
        }
    }
}