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

namespace RMYY_CallCenter_Api.Controllers.WorkOrder
{
    /// 红处方配送,其他配送,急查标本配送,血液制品配送
    public class T_Dis_WorkOrderController : BaseController
    {
        Bll.T_Sys_UserAccount userbll = new Bll.T_Sys_UserAccount();
        Bll.T_Dis_WorkOrder orderbll = new Bll.T_Dis_WorkOrder();
        Bll.AddLogBll logbll = new Bll.AddLogBll();
        Bll.T_Dis_WorkOrderItem itembll = new Bll.T_Dis_WorkOrderItem();
        Bll.T_Sys_Department dptbll = new Bll.T_Sys_Department();
        /// <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, int type = 0, string starttime = "", string endtime = "", int pageindex = 1, int pagesize = 10, int state = -1, int isdc = 0)
        {
            if (User != null)
            {
                string transql = "";
                List<string> wokerlist = new List<string>();
                #region 查询条件
                if (type != (int)EnumWorkOrder.OrtherDis && type != (int)EnumWorkOrder.UrgDis && type != (int)EnumWorkOrder.RedDis && type != (int)EnumWorkOrder.BloodDis)
                    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 && User.F_RoleCode != "ZYY")
                {
                    sql += $"and F_State=" + state;
                }
                if (User.F_DeptCode == "ZZWY" && User.F_UserCode == "8000" )//综合保障中心
                {
                   //sql += $" and F_ControlManCode=" + User.F_UserCode;
                }
                else if (User.F_DeptCode == "ZZWY" && User.F_RoleCode == "ZYY")//转运人判断
                {
                    if (state == (int)EnumDisWorkOrderState.assign)
                    {
                        sql += $"and F_State=" + state;
                    }
                    transql = GetTranPersonsql(User.F_UserCode, type, state);
                    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_RoleCode == "JZJYK_GLY")
                {
                    int[] wostate = { (int)EnumDisWorkOrderState.end, (int)EnumDisWorkOrderState.finish };
                    sql += $" and  F_State in(" + string.Join(",", wostate) + ")";
                }
                else if (User.F_RoleCode == "LC_GLY")
                {
                    int[] wostate = { (int)EnumDisWorkOrderState.end, (int)EnumDisWorkOrderState.finish };
                    //sql += $" and  F_State in(" + string.Join(",", wostate) + ") and F_SendDeptId=" + User.F_DeptId + "";
                    sql += $" and  F_State in(" + string.Join(",", wostate) + ")";
                }
                else //申请科室
                {
                    sql += $" and F_ProposerDeptId=" + User.F_DeptId + "";                                   
                }
               
                //if (isdc > 0)
                //{
                //    if (GetListExpt(sql, type))
                //        return Success("导出成功！");
                //    else return Error("导出失败！");
                //}
                #endregion
                int recordCount = 0;
                if (!string.IsNullOrEmpty(sql))
                {
                    data = Bll.PagerBll.GetListPager
                        (
                        "T_Dis_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 (wokerlist.Count > 0 || User.F_UserCode== "ZYY")
                    //{
                    foreach (var item in modellist)
                    {

                        if (wokerlist.Count > 0 || 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??0;
                            item.F_Wostate = EnumHelper.GetDescription((EnumDisWorkOrderState)wostate);
                            item.F_State = wostate;
                        }
                        else
                        {
                            item.F_Wostate = EnumHelper.GetDescription((EnumDisWorkOrderState)item.F_State);
                        }
                        item.F_SitMan = item.F_ControlManName + '(' + item.F_ControlManCode + ')';
                        if (type == (int)EnumWorkOrder.UrgDis)
                        {
                            item.dislist = orderbll.GetModelList("datediff(second,F_CreateTime,'" + item.F_CreateTime + "')=0  and F_Id!=" + item.F_Id + "");
                        }
                        if (type == (int)EnumWorkOrder.RedDis)
                        {

                            item.RedPic = GetRedPics(item.F_ItemMessages);

                        }
                        item.rolecode = User.F_RoleCode;
                        item.deptcode = User.F_DeptCode;
                        item.F_TypeName = GetTypeName(type);
                        //var buttons = ButtonGroup.GetButtons(item.F_State, User.F_RoleCode, item.F_Type);

                    }
                }
                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(" isnull(F_IsUsed,'0')='0' and F_OptType=" + (int)EnumDisItemOpt.assign + " 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 = -1)
        {
            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>
        /// <returns></returns>
        public ActionResult GetTypeState(int type,string rolecode,string deptcode="")
        {
            List<TypeState> tlist = Common.GetGongDanState<EnumDisWorkOrderState>();
            List<TypeState> qlist = Common.GetGongDanState<EnumMatWorkOrderState>();
            List<TypeState> dlit = Common.GetGongDanState<EnumDevWorkOrderState>();
            List<TypeState> hlit = Common.GetGongDanState<EnumHosWorkOrderState>();
            List<TypeState> alit = Common.GetGongDanState<EnumAccWorkOrderState>();
            List<TypeState> newlist = new List<TypeState> ();
         
            switch (type)
            {
                case (int)EnumWorkOrder.RedDis:
                    if (rolecode == "GLY")
                    {
                        tlist.RemoveAll(p => ("'" + (int)EnumDisWorkOrderState.receive + "','" + (int)EnumDisWorkOrderState.dealing + "','" + (int)EnumDisWorkOrderState.takeblood + "','" + (int)EnumDisWorkOrderState.send + "'").Contains(p.StateId));
                    }
                    else if (rolecode == "ZYY")
                    {
                        tlist = tlist.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.assign || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.stayred || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.staydrug || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.end));                     
                    }
                    else
                    {
                        tlist = tlist.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.finish || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.all));
                        tlist.Add(new TypeState { StateId = "8", StateValue = "", StateRemark = "待完结" });
                    }
                    newlist=tlist;
                    break;

                case (int)EnumWorkOrder.OrtherDis:
                case (int)EnumWorkOrder.UrgDis:
                    if (rolecode == "GLY")
                    {
                        tlist.RemoveAll(p => ("'" + (int)EnumDisWorkOrderState.stayred + "','" + (int)EnumDisWorkOrderState.staydrug + "','" + (int)EnumDisWorkOrderState.takeblood + "','" + (int)EnumDisWorkOrderState.send + "'").Contains(p.StateId));
                    }
                    else if (rolecode == "ZYY")
                    {
                        tlist = tlist.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.assign || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.receive || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.dealing || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.end));

                    }

                    else if (rolecode == "JZJYK_GLY")
                    {
                        tlist = tlist.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.finish || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.all));
                        tlist.Add(new TypeState { StateId = "8", StateValue = "", StateRemark = "待完结" });
                    }
                    else
                    {
                        tlist = tlist.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.finish || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.all));
                    }
                    newlist = tlist;
                    break;

                case (int)EnumWorkOrder.BloodDis:
                    if (rolecode == "GLY")
                    {
                        tlist.RemoveAll(p => ("'" + (int)EnumDisWorkOrderState.receive + "','" + (int)EnumDisWorkOrderState.stayred + "','" + (int)EnumDisWorkOrderState.staydrug + "','" + (int)EnumDisWorkOrderState.dealing +  "'").Contains(p.StateId));
                    }
                    else if (rolecode == "ZYY")
                    {
                        tlist = tlist.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.assign || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.takeblood || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.send || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.end));                   
                    }
                    else if(rolecode== "LC_GLY")
                    {
                        tlist = tlist.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.finish || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.all));
                        tlist.Add(new TypeState { StateId = "8", StateValue = "", StateRemark = "待完结" });
                    }
                    else
                    {
                        tlist = tlist.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.finish || Convert.ToInt32(p.StateId) == (int)EnumDisWorkOrderState.all));
                    }

                    newlist = tlist;
                    break;
                case (int)EnumWorkOrder.Mat:
                    if (rolecode == "GLY")
                    {

                    }
                    else if (rolecode == "ZYY")
                    {
                        qlist.RemoveAll(p => (Convert.ToInt32(p.StateId) == (int)EnumMatWorkOrderState.neworder || Convert.ToInt32(p.StateId) == (int)EnumMatWorkOrderState.finish));
                    }
                    else
                    {
                        qlist = qlist.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumMatWorkOrderState.finish || Convert.ToInt32(p.StateId) == (int)EnumMatWorkOrderState.all));
                        qlist.Add(new TypeState { StateId = "4", StateValue = "", StateRemark = "待完结" });                    
                    }
                    newlist = qlist;
                    break;
                case (int)EnumWorkOrder.Dev:
                    if (rolecode == "GLY"&& deptcode== "ZZWY")
                    {


                    }
                    else if (rolecode == "ZYY")
                    {
                        dlit = dlit.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumDevWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumDevWorkOrderState.work || Convert.ToInt32(p.StateId) == (int)EnumDevWorkOrderState.transport || Convert.ToInt32(p.StateId) == (int)EnumDevWorkOrderState.transover));
                    }
                    else if (deptcode == "SBK")
                    {
                        dlit = dlit.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumDevWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumDevWorkOrderState.assign));
                        dlit.Add(new TypeState { StateId = "5", StateValue = "", StateRemark = "待入库" });
                        dlit.Add(new TypeState { StateId = "7", StateValue = "", StateRemark = "待完结" });
                        dlit.Add(new TypeState { StateId = "10", StateValue = "", StateRemark = "已完结" });

                    }
                    else if (deptcode == "LC")
                    {
                        //dlit = dlit.FindAll(p => Convert.ToInt32(p.StateId) == (int)EnumDevWorkOrderState.finish);
                        dlit.Clear();
                        dlit.Add(new TypeState { StateId = "-1", StateValue = "", StateRemark = "已申请" });
                        dlit.Add(new TypeState { StateId = "5", StateValue = "", StateRemark = "待接收" });
                        dlit.Add(new TypeState { StateId = "6", StateValue = "", StateRemark = "待返还" });
                        dlit.Add(new TypeState { StateId = "99", StateValue = "", StateRemark = "已返还" });
                    }
                    newlist = dlit;
                    break;
                case (int)EnumWorkOrder.Hos:

                    if (deptcode == "ZZWY" && rolecode == "GLY")
                    {

                    }
                    else if (deptcode == "ZZWY" && rolecode == "ZYY")
                    {
                        hlit = hlit.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.work || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.receive || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.transport || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.transcomplete));
                    }
                    else if (deptcode == "WYZX" && rolecode == "ZYY")
                    {
                        hlit = hlit.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.awaitfetch || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.fetch || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.install || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.installcomplete));
                    }
                    else if (deptcode == "SBK")
                    {
                        hlit = hlit.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.assign));
                        hlit.Add(new TypeState { StateId = "-2", StateValue = "", StateRemark = "已确认" });
                    }
                    else if (deptcode == "WYZX" && rolecode != "ZYY")
                    {
                        hlit = hlit.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.awaitfetch || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.fetch || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.install || Convert.ToInt32(p.StateId) == (int)EnumHosWorkOrderState.installcomplete));
                        hlit.Add(new TypeState { StateId = "6", StateValue = "", StateRemark = "待转派" });
                    }
                    else if (deptcode == "LC")
                    {
                        hlit.Clear();
                        hlit.Add(new TypeState { StateId = "-1", StateValue = "", StateRemark = "全部" });
                        hlit.Add(new TypeState { StateId = "10", StateValue = "", StateRemark = "待完结" });
                        hlit.Add(new TypeState { StateId = "12", StateValue = "", StateRemark = "已完结" });
                       
                    }
                    newlist = hlit;
                    break;

                case (int)EnumWorkOrder.Serve:
                    if (rolecode == "GLY")
                    {
                        alit.RemoveAll(p => ("'" + (int)EnumAccWorkOrderState.receive + "','"  + (int)EnumAccWorkOrderState.dealing + "'").Contains(p.StateId));
                    }
                    else if (rolecode == "ZYY")
                    {
                        alit = alit.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.assign ||  Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.arrive || Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.keep || Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.end));
                    }
                    else
                    {
                        alit = alit.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.finish));
                        alit.Add(new TypeState { StateId = "6", StateValue = "", StateRemark = "待完结" });
                    }
                    newlist = alit;
                    break;
                case (int)EnumWorkOrder.TakeBlood:
                    if (rolecode == "GLY")
                    {
                        alit.RemoveAll(p => ("'" + (int)EnumAccWorkOrderState.arrive + "','" + (int)EnumAccWorkOrderState.keep +  "'").Contains(p.StateId));
                    }
                    else if (rolecode == "ZYY")
                    {
                        alit = alit.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.assign || Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.receive || Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.dealing || Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.end));
                    }
                    else
                    {
                        alit = alit.FindAll(p => (Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.all || Convert.ToInt32(p.StateId) == (int)EnumAccWorkOrderState.finish));
                        alit.Add(new TypeState { StateId = "6", StateValue = "", StateRemark = "待完结" });
                    }
                    newlist = alit;
                    break;
            }
            return Content(newlist.OrderBy(p => Convert.ToInt32(p.StateId)).ToJson());

        }

        /// <summary>
        /// 获取工单状态
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult GetTypeStatenew(int type)
        {
            var newlist = WorkOrderBase.GetTypeState(type);
            return Content(newlist.OrderBy(p => Convert.ToInt32(p.StateId)).ToJson());

        }

        /// <summary>
        /// 获取工单类型名称
        /// </summary>
        /// <returns></returns>
        public string GetTypeName(int type)
        {
            string name = "";
            switch (type)
            {
                case (int)EnumWorkOrder.RedDis:
                    name = "红处方配送";
                    break;
                case (int)EnumWorkOrder.OrtherDis:
                    name = "其他配送";
                    break;
                case (int)EnumWorkOrder.UrgDis:
                    name = "急查标本配送";
                    break;
                case (int)EnumWorkOrder.BloodDis:
                    name = "血液制品配送";
                    break;
            }
            return name;
        }

        /// <summary>
        /// 获取图片路径
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>

        public string GetRedPics(string ids)
        {
            string PicPath = "";
            if (!string.IsNullOrEmpty(ids))
            {
                var modelist = new Bll.T_Sys_Accessories().GetModelList(" F_FileId in (" + ids.Trim(',') + ")");
                if (modelist.Count > 0)
                {
                    foreach (var item in modelist)
                    {
                        PicPath = PicPath + item.F_FileUrl + ",";
                    }
                }
            }
            return PicPath.Trim(',');
        }


        /// <summary>
        /// 获取工单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetModelDetail(int id)
        {
            string sql = "F_WoID = " + id + "";
            if (id <= 0)
            {
                return Error("请选择要查询的工单！");
            }
            var model = orderbll.GetModel(id);
            var itemlist = itembll.GetModelList(sql);
            //List<Con_WorkOrderInput> Input = modeltoopi(list);
            if (model != null)
            {
                model.HosName = new Bll.T_Wowo_repairyqbll().GetModel(model.F_HosId ?? 0).T_Woname;
                model.dislist = orderbll.GetModelList("datediff(second,F_CreateTime,'" + model.F_CreateTime + "')=0  and F_Id!=" + model.F_Id + "");
                model.F_Wostate = EnumHelper.GetDescription((EnumDisWorkOrderState)model.F_State);
                if (model.F_Type == (int)EnumWorkOrder.RedDis)
                {
                    model.RedPic = GetRedPics(model.F_ItemMessages);
                }
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    model = model,
                    itemlist = itemlist
                };
                return Content(obj.ToJson());
            }
            else
                return Error("没有查询到此工单！");
        }

        /// <summary>
        /// 报表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public ActionResult GetListExpt(string keyword, int type = 0, string starttime = "", string endtime = "", int pageindex = 1, int pagesize = 10, int isdc = 0)
        {
            string sql = $" and F_IsDel=0 and F_Type=" + type;
            #region 查询条件
            if (type != (int)EnumWorkOrder.OrtherDis && type != (int)EnumWorkOrder.UrgDis && type != (int)EnumWorkOrder.RedDis && type != (int)EnumWorkOrder.BloodDis)
                return Error("工单类型错误！");
            if (starttime.Trim() != "" && starttime != "undefined")
                sql += $"and datediff(day,F_CreateTime,'" + starttime + "')<=0";
            if (endtime.Trim() != "" && endtime != "undefined")
                sql += $"and datediff(day,F_CreateTime,'" + endtime + "')>=0";
            if (!string.IsNullOrEmpty(keyword))
            {
                sql += $"and (F_WorkOrderCode like '%" + keyword.Trim() + "%' or F_ProposerCode like '%" + keyword.Trim() + "%' or F_ProposerPhon like '%" + keyword.Trim() + "%')";
            }
            DataTable data = new DataTable();
            #endregion

            NPOIHelper nopi = new NPOIHelper();
            data = GetData(type, sql);
            if (isdc > 0)
            {
                if (nopi.ExportToExcel(GetExportTitle(type), data, col(type)) == "")
                {
                    return Success("导出成功！");
                }
                else return Error("导出失败！");
            }
            else
            {
                int recordCount = 0;
                if (!string.IsNullOrEmpty(sql))
                {
                    data = Bll.PagerBll.GetListPager
                        (
                        "T_Dis_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 (wokerlist.Count > 0 || User.F_UserCode== "ZYY")
                    //{
                    foreach (var item in modellist)
                    {
                        item.F_Wostate = EnumHelper.GetDescription((EnumDisWorkOrderState)item.F_State);

                        item.F_SitMan = item.F_ControlManName + '(' + item.F_ControlManCode + ')';
                        if (type == (int)EnumWorkOrder.RedDis)
                        {

                            item.RedPic = GetRedPics(item.F_ItemMessages);

                        }
                        item.rolecode = User.F_RoleCode;
                        item.F_TypeName = GetTypeName(type);
                        //var buttons = ButtonGroup.GetButtons(item.F_State, User.F_RoleCode, item.F_Type);

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


        private DataTable GetData(int type, string sql)
        {

            DataTable data = new DataTable();
            switch (type)
            {
                case (int)EnumWorkOrder.RedDis:
                    data = new Bll.T_Dis_WorkOrder().GetListRedExpt(sql).Tables[0];
                    break;
                case (int)EnumWorkOrder.OrtherDis:
                    data = new Bll.T_Dis_WorkOrder().GetListOrtherExpt(sql).Tables[0];
                    break;
                case (int)EnumWorkOrder.UrgDis:
                    data = new Bll.T_Dis_WorkOrder().GetListUrgExpt(sql).Tables[0];
                    break;
                case (int)EnumWorkOrder.BloodDis:
                    data = new Bll.T_Dis_WorkOrder().GetListBloodExpt(sql).Tables[0];
                    break;
            }
            return data;
        }
        private string[] col(int type)
        {
            string[] cel =
            {
                "工单编号","申请科室","申请人","联系电话","工单类型","内容","调度员","时间","处理部门","转运人","备注"
            };
            string[] cel2 =
            {
                "工单编号","申请科室","工单类型","工单内容","申请人","联系电话","调度员","配送科室","地点","时间","处理部门","转运人","备注"
            };
            string[] cel3 =
            {
                "工单编号","类型","内容","调度人","上报渠道","上报部门","上报人","地点","时间","处理部门","处理人","备注"
            };
            string[] cel4 =
            {
                "工单编号","工单类型","申请科室","工单内容","申请电话","申请人","上报渠道","送达科室","调度员","时间","处理部门","转运人","备注"
            };
            string[] str = { };
            switch (type)
            {
                case (int)EnumWorkOrder.RedDis:
                    str = cel;
                    break;
                case (int)EnumWorkOrder.OrtherDis:
                    str = cel2;
                    break;
                case (int)EnumWorkOrder.UrgDis:
                    str = cel3;
                    break;
                case (int)EnumWorkOrder.BloodDis:
                    str = cel4;
                    break;
            }
            return str;

        }
        private string GetExportTitle(int type)
        {
            string str = "";
            switch (type)
            {
                case (int)EnumWorkOrder.RedDis:
                    str = "红处方配送统计报表";
                    break;
                case (int)EnumWorkOrder.OrtherDis:
                    str = "其他配送统计报表";
                    break;
                case (int)EnumWorkOrder.UrgDis:
                    str = "急查标本配送统计报表";
                    break;
                case (int)EnumWorkOrder.BloodDis:
                    str = "血液制品配送统计报表";
                    break;
            }
            return str;

        }


        /// <summary>
        /// 添加工单
        /// </summary>
        /// <param name="type"></param>
        /// <param name="store"></param>
        /// <param name="positon"></param>
        /// <param name="usercode"></param>
        /// <param name="username"></param>
        /// <param name="phon"></param>
        /// <param name="senddeptid"></param>
        /// <param name="deptname"></param>
        /// <param name="itemessage"></param>
        /// <param name="remark"></param>
        /// <param name="callid"></param>
        /// <returns></returns>
        public ActionResult AddWorOrder(int type, int hosid, int deptid, string deptname, string usercode, string username, string phon, string itemessage, string remark, string callid = "", int isthird = 0, int islarge = 0, string carrytime = "", int number = 0, string pic = "", string positon = "", string orthertype = "", string source = "")
        {
            if (User != null)
            {
                #region 添加条件
                if (type != (int)EnumWorkOrder.OrtherDis && type != (int)EnumWorkOrder.UrgDis && type != (int)EnumWorkOrder.RedDis && type != (int)EnumWorkOrder.BloodDis)
                    return Error("工单类型错误！");
                if (hosid <= 0)
                    return Error("请选择院区！");


                if (deptid <= 0)
                    return Error("请选择申请部门！");
                if (usercode == "")
                    return Error("请选择申请人！");
                if (phon == "")
                    return Error("请输入联系电话！");
                if (type == (int)EnumWorkOrder.OrtherDis && string.IsNullOrEmpty(orthertype))
                {
                    return Error("请选择配送类型！");
                }
                //if (string.IsNullOrEmpty(itemessage))
                //    return Error("请填写配送信息！");
                #endregion
                var model = new Model.T_Dis_WorkOrder();
                model.F_Type = type;//工单类型  急标本配送
                model.F_Source = source;
                model.F_CallID = callid;
                model.F_State = (int)EnumDisWorkOrderState.neworder;//新工单待转派
                model.F_HosId = hosid;//院区
                model.F_ProposerDeptId = deptid;//申请科室
                model.F_ProposerDeptName = deptname;//申请科室名称
                model.F_ProposerCode = usercode;//申请人
                model.F_ProposerName = username;
                model.F_ProposerPhon = phon;
                model.F_BedPosition = positon;//送达地点
                model.F_Remark = remark;
                model.F_CreateTime = DateTime.Now;
                model.F_CreateCode = User.F_UserCode;
                model.F_CreateName = User.F_UserName;
                model.F_IsDel = 0;
                if (!string.IsNullOrEmpty(orthertype))
                    model.F_OrtherType = orthertype;
                if (type == (int)EnumWorkOrder.OrtherDis)
                {
                    if (isthird == 1)
                    {
                        model.F_IsThird = 1;
                        model.F_Islarge = islarge;
                        if (!string.IsNullOrEmpty(carrytime))
                            model.F_CarryTime = Convert.ToDateTime(carrytime);
                    }
                    #region 信息处理
                    if (string.IsNullOrEmpty(itemessage))
                        return Error("请填写配送信息！");
                    string[] _list = itemessage.TrimEnd(',').Split(',');
                    string mscontents = "";
                    for (int i = 0; i < _list.Length; i++)
                    {
                        string[] _temp = _list[i].Split('-');
                        string itemess = _temp[0];
                        int num = Convert.ToInt32(_temp[1]);

                        if (num > 0 && itemess != "")
                        {
                            mscontents = string.IsNullOrEmpty(mscontents) ? (itemess + ",数量:" + num) : (mscontents + " ； " + itemess + ",数量:" + num);
                        }
                        else return Error("配送信息不正确！");
                    }
                    #endregion
                    model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号
                    model.F_ItemMessages = itemessage;//配送内容
                    model.F_ItemContents = mscontents;
                    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)EnumDisItemOpt.create, "", 0, User.F_UserCode);
                    }
                    else return Error("添加失败");
                }
                if (type == (int)EnumWorkOrder.RedDis)
                {
                    if (number <= 0)
                        return Error("红处方数量不能为空！");
                    model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号
                    model.F_DisNum = number;//红处方数量
                    model.F_ItemMessages = pic;//红处方图片
                    model.F_ItemContents = "红处方配送";
                    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)EnumDisItemOpt.create, "", 0, User.F_UserCode);
                    }
                    else return Error("添加失败");
                }
                if (type == (int)EnumWorkOrder.UrgDis)
                {
                    #region 信息处理
                    if (string.IsNullOrEmpty(itemessage))
                        return Error("请填写配送信息！");
                    string[] _list = itemessage.TrimEnd(',').Split(',');
                    //string deptstr = "";
                    //string[] deptlist = { };
                    for (int i = 0; i < _list.Length; i++)
                    {
                        string[] _temp = _list[i].Split('-');
                        int sendeptid = Convert.ToInt32(_temp[0]);
                        string mscontents = "";
                        string sendepatname = "";
                        try { sendepatname = dptbll.GetModel(sendeptid).F_DeptName; }
                        catch { return Error("请填写正确送达科室信息！"); }
                        //if (_temp[1].IndexOf('|') > 0 && _temp[2].IndexOf('|') > 0)
                        //{
                        var itemess = _temp[1].Trim('|').Split('|');
                        var num = _temp[2].Trim('|').Split('|');
                        for (int k = 0; k < itemess.Length; k++)
                        {
                            mscontents = string.IsNullOrEmpty(mscontents) ? itemess[k] + " : 数量" + num[k] : mscontents + ";" + itemess[k] + " : 数量" + num[k];
                        }
                        model.F_ItemMessages = itemessage;//配送内容
                        model.F_ItemContents = mscontents;
                        model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号
                        model.F_SendDeptId = sendeptid;
                        model.F_SendDeptName = sendepatname;
                        int tt = orderbll.Add(model);
                        if (tt > 0)
                        {
                            logbll.AddLog(tt, 0, type, User.F_UserName + "(" + User.F_UserCode + ")" + "创建新工单", 0, (int)EnumDisItemOpt.create, "", 0, User.F_UserCode);
                        }
                        else return Error("添加失败");
                        //deptstr += sendeptid + ",";
                        //}
                        //else return Error("操作失败,请填写正确信息！");
                    }
                    //if (!string.IsNullOrEmpty(deptstr))
                    //    deptlist = deptstr.TrimEnd(',').Split(',');
                    #endregion
                }
                if (type == (int)EnumWorkOrder.BloodDis)
                {
                    #region 信息处理
                    if (string.IsNullOrEmpty(itemessage))
                        return Error("请填写配送信息！");
                    string[] _list = itemessage.TrimEnd(',').Split(',');
                    string mscontents = "";
                    //string deptstr = "";
                    //string[] deptlist = { };
                    for (int i = 0; i < _list.Length; i++)
                    {
                        string[] _temp = _list[i].Split('-');
                        int sendeptid = Convert.ToInt32(_temp[0]);
                        string itemess = _temp[1];
                        int num = Convert.ToInt32(_temp[2]);
                        string sendepatname = "";
                        try { sendepatname = dptbll.GetModel(sendeptid).F_DeptName; }
                        catch { return Error("请填写正确送达科室信息！"); }
                        if (num > 0 && itemess != "" && sendepatname != "" && sendeptid > 0)
                        {
                            //mscontents = string.IsNullOrEmpty(mscontents) ? (itemess + "配送到" + sendepatname + "科室" + ",数量:" + num) : (mscontents + " ； " + itemess + "配送到" + sendepatname + "科室" + ",数量:" + num);
                            mscontents = itemess + "送到" + sendepatname + ",数量:" + num;
                            model.F_ItemMessages = itemessage;//配送内容
                            model.F_ItemContents = mscontents;
                            model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号
                            model.F_SendDeptId = sendeptid;
                            model.F_SendDeptName = sendepatname;
                            int tt = orderbll.Add(model);
                            if (tt > 0)
                            {
                               logbll.AddLog(tt, 0, type, User.F_UserName + "(" + User.F_UserCode + ")" + "创建新工单", 0, (int)EnumDisItemOpt.create, "", 0, User.F_UserCode);
                            }
                            else return Error("添加失败");
                            //deptstr += sendeptid + ",";
                        }
                        else return Error("操作失败,请填写正确信息！");
                    }
                    //if (!string.IsNullOrEmpty(deptstr))
                    //    deptlist = deptstr.TrimEnd(',').Split(',');
                    #endregion
                }
                return Success("操作成功！");
            }
            return Error("无操作权限");
        }
        /// <summary>
        /// 修改工单
        /// </summary>
        /// <param name="type"></param>
        /// <param name="store"></param>
        /// <param name="positon"></param>
        /// <param name="usercode"></param>
        /// <param name="username"></param>
        /// <param name="phon"></param>
        /// <param name="senddeptid"></param>
        /// <param name="deptname"></param>
        /// <param name="itemessage"></param>
        /// <param name="remark"></param>
        /// <param name="callid"></param>
        /// <returns></returns>
        public ActionResult UpdateWorkOrder(int woid, int type, int hosid, int deptid, string deptname, string positon, string usercode, string username, string phon, string itemessage, string remark, string callid = "", int isthird = 0, int islarge = 0, string carrytime = "", int number = 0, string pic = "", string orthertype = "")
        {
            if (User != null)
            {

                #region 添加条件
                if (woid <= 0)
                    return Error("请选择要修改的工单！");
                if (type != (int)EnumWorkOrder.OrtherDis && type != (int)EnumWorkOrder.UrgDis && type != (int)EnumWorkOrder.RedDis && type != (int)EnumWorkOrder.BloodDis)
                    return Error("工单类型错误！");
                if (hosid <= 0)
                    return Error("请选择院区！");
                if (deptid <= 0)
                    return Error("请选择申请部门！");
                if (usercode == "")
                    return Error("请选择申请人！");
                if (phon == "")
                    return Error("请输入联系电话！");
                if (type == (int)EnumWorkOrder.OrtherDis && string.IsNullOrEmpty(orthertype))
                {
                    return Error("请选择配送类型！");
                }
                //if (string.IsNullOrEmpty(itemessage))
                //    return Error("请填写配送信息！");
                #endregion

                var model = orderbll.GetModel(woid);
                if (model == null)
                    return Error("不存在此工单信息！");
                if (model.F_State == (int)EnumDisWorkOrderState.assign || model.F_TransPersonCode != "")
                    return Error("工单已指派不能修改！");
                model.F_ProposerDeptId = deptid;//申请科室
                model.F_ProposerDeptName = deptname;//申请科室名称
                model.F_ProposerCode = usercode;//申请人
                model.F_ProposerName = username;
                model.F_ProposerPhon = phon;
                model.F_BedPosition = positon;//送达地点
                model.F_Remark = remark;
                if (!string.IsNullOrEmpty(orthertype))
                    model.F_OrtherType = orthertype;
                if (type == (int)EnumWorkOrder.OrtherDis && isthird == 1)
                {
                    model.F_IsThird = 1;
                    model.F_Islarge = islarge;
                    if (!string.IsNullOrEmpty(carrytime))
                        model.F_CarryTime = Convert.ToDateTime(carrytime);
                }
                if (type == (int)EnumWorkOrder.OrtherDis || type == (int)EnumWorkOrder.UrgDis)
                {
                    #region 信息处理
                    if (string.IsNullOrEmpty(itemessage))
                        return Error("请填写配送信息！");
                    string[] _list = itemessage.TrimEnd(',').Split(',');
                    string mscontents = "";
                    for (int i = 0; i < _list.Length; i++)
                    {
                        string[] _temp = _list[i].Split('-');
                        string itemess = _temp[0];
                        int num = Convert.ToInt32(_temp[1]);

                        if (num > 0 && itemess != "")
                        {
                            mscontents = string.IsNullOrEmpty(mscontents) ? (itemess + ",数量:" + num) : (mscontents + " ； " + itemess + ",数量:" + num);
                        }
                        else return Error("配送信息不正确！");
                    }
                    #endregion
                    model.F_ItemMessages = itemessage;//配送内容
                    model.F_ItemContents = mscontents;
                    bool n = orderbll.Update(model);
                    if (n)
                    {
                       logbll.AddLog(woid, 0, type, User.F_UserName + "(" + User.F_UserCode + ")" + "修改工单", (int)EnumDisItemType.update, (int)EnumDisItemOpt.update, "", 0, User.F_UserCode);
                    }
                    else return Error("修改失败");
                }
                if (type == (int)EnumWorkOrder.RedDis)
                {
                    if (number <= 0)
                        return Error("红处方数量不能为空！");
                    model.F_DisNum = number;//红处方数量
                    model.F_ItemMessages = pic;//红处方图片
                    model.F_ItemContents = "红处方配送";
                    bool n = orderbll.Update(model);
                    if (n)
                    {
                       logbll.AddLog(woid, 0, type, User.F_UserName + "(" + User.F_UserCode + ")" + "修改工单", (int)EnumDisItemType.update, (int)EnumDisItemOpt.update, "", 0, User.F_UserCode);
                    }
                    else return Error("修改失败");
                }
                if (type == (int)EnumWorkOrder.BloodDis)
                {
                    #region 信息处理
                    if (string.IsNullOrEmpty(itemessage))
                        return Error("请填写配送信息！");
                    string[] _list = itemessage.TrimEnd(',').Split(',');
                    string mscontents = "";
                    //string deptstr = "";
                    //string[] deptlist = { };
                    for (int i = 0; i < _list.Length; i++)
                    {
                        string[] _temp = _list[i].Split('-');
                        string itemess = _temp[0];
                        int sendeptid = Convert.ToInt32(_temp[1]);
                        string sendepatname = _temp[2].ToString();
                        int num = Convert.ToInt32(_temp[3]);

                        if (num > 0 && itemess != "" && sendepatname != "" && sendeptid > 0)
                        {
                            //mscontents = string.IsNullOrEmpty(mscontents) ? (itemess + "配送到" + sendepatname + "科室" + ",数量:" + num) : (mscontents + " ； " + itemess + "配送到" + sendepatname + "科室" + ",数量:" + num);
                            mscontents = itemess + "配送到" + sendepatname + "科室" + ",数量:" + num;
                            model.F_ItemMessages = itemessage;//配送内容
                            model.F_ItemContents = mscontents;
                            var deptmodel = dptbll.GetModel(sendeptid);
                            if (deptmodel != null)
                            {
                                model.F_SendDeptId = sendeptid;
                                model.F_SendDeptName = sendepatname;
                                bool tt = orderbll.Update(model);
                                if (tt)
                                {
                                   logbll.AddLog(woid, 0, type, User.F_UserName + "(" + User.F_UserCode + ")" + "修改工单", (int)EnumDisItemType.update, (int)EnumDisItemOpt.update, "", 0, User.F_UserCode);
                                }
                                else return Error("修改失败");
                            }
                            else return Error("不存在此部门信息！");
                            //deptstr += sendeptid + ",";
                        }
                        else return Error("配送信息不正确！");
                    }
                    //if (!string.IsNullOrEmpty(deptstr))
                    //    deptlist = deptstr.TrimEnd(',').Split(',');
                    #endregion


                }
                return Success("操作成功！");
            }
            return Error("无操作权限！");
        }
        /// <summary>
        /// 转派
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult AssignWo(int woid, string transMestr)
        {
            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)EnumDisWorkOrderState.assign;//已指派待查收
                if (orderbll.Update(omodel))
                    return Success("转派成功！");
                else return Error("转派失败！");
            }
            return Error("转派失败,不存在此工单编号！");
        }



        /// <summary>
        /// 转派工单
        /// </summary>
        private bool AssignTrans(Model.T_Sys_UserAccount nowUser, Model.T_Dis_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)EnumDisItemOpt.assign;
            wostate = (int)EnumDisWorkOrderState.assign;//已指派待查收
            content = nowUser.F_UserName + "(" + nowUser.F_UserCode + ")" + opt + "工单给 " + tousername + optcont;
            itemid = WorkOrderBase.AddLogTrans(wokerModel.F_Id, wostate, (int)wokerModel.F_Type, content, (int)EnumDisItemType.deal, optbut, touser, clus.F_UserName, userphon, usertalkie, clbm, nowUser);
            #endregion
            if (itemid > 0)
            {
                return true;
            }
            else return false;
        }

        /// <summary>
        /// 工单查收
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult SureWo(int woid)
        {
            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("操作失败,不存在此工单编号！");
        }



        /// <summary>
        /// 工单处理
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult DealWork(int woid)
        {
            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("操作失败,不存在此工单编号！");
        }


        /// <summary>
        /// 取红处方
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult FeachRed(int woid)
        {
            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("操作失败,不存在此工单编号！");
        }


        /// <summary>
        /// 取药
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult FeachDrug(int woid)
        {
            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("操作失败,不存在此工单编号！");
        }



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

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

        /// <summary>
        /// 处理完成操作
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult ServiceWo(int woid)
        {
            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("操作失败,不存在此工单编号！");
        }


        /// <summary>
        /// 完结工单
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult OverWo(int woid, string sureman, string phon, string talkie)
        {
            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)
            {           
                var n =WorkOrderBase.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_FinishMan = sureman;
                    omodel.F_FinishManName = user.F_UserName;
                    omodel.F_FinishManPhon = phon;
                    omodel.F_FinishManTalkie = talkie;
                    orderbll.Update(omodel);
                    return Success("操作成功！");
                }
                else return Error("操作失败！");
            }
            return Error("操作失败,不存在此工单编号！");
        }


        /// <summary>
        /// 处理工单
        /// </summary>
        /// <param name="nowUser"></param>
        /// <param name="model"></param>
        /// <param name="cont"></param>
        /// <param name="F_Files"></param>
        /// <param name="isover"></param>
        /// <returns></returns>
        public bool DealWO(Model.T_Sys_UserAccount nowUser, Model.T_Dis_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)EnumDisItemOpt.receive;//查收
                if (model.F_Type == (int)EnumWorkOrder.OrtherDis || model.F_Type == (int)EnumWorkOrder.UrgDis)
                {
                    wostate1 = (int)EnumDisWorkOrderState.receive;//已查收待处理
                }
                else if (model.F_Type == (int)EnumWorkOrder.BloodDis)
                {
                    wostate1 = (int)EnumDisWorkOrderState.takeblood;//已查收待取血
                }
                else if (model.F_Type == (int)EnumWorkOrder.RedDis)
                {
                    wostate1 = (int)EnumDisWorkOrderState.stayred;//已查收待取红处方
                }
            }
            if (type == 2)
            {
                opt = "处理工单";
                optbut = (int)EnumDisItemOpt.deal;//处理
                wostate1=(int)EnumDisWorkOrderState.dealing;//处理中
            }
            if (type == 3)
            {
                opt = "完成工单";
                optbut = (int)EnumDisItemOpt.end;
                wostate1 = (int)EnumDisWorkOrderState.end;//已完成
            }
            if (type == 4)
            {
                opt = "取红处方";
                optbut = (int)EnumDisItemOpt.stayred;
                wostate1 = (int)EnumDisWorkOrderState.staydrug;//已取红处方待取药
            }
            if (type == 5)
            {
                opt = "取药";
                optbut = (int)EnumDisItemOpt.staydrug;
                wostate1 = (int)EnumDisWorkOrderState.end;//已取药待完成
            }
            if (type == 6)
            {
                opt = "取血";
                optbut = (int)EnumDisItemOpt.takeblood;
                wostate1 = (int)EnumDisWorkOrderState.send;//已取血待送达
            }
            if (type == 7)
            {
                opt = "送达";
                optbut = (int)EnumDisItemOpt.send;
                wostate1 = (int)EnumDisWorkOrderState.end;//已送达待完成
            }
            //if (type == 5)
            //{
            //    opt = "异常结束工单";
            //    optbut = (int)EnumDevItemOpt.abreback;
            //    wostate = (int)EnumDevWorkOrderState.abreback;//异常结束
            //}
            //#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, User.F_UserCode);
            if (itemid > 0)
            {
                #region 判断工单的状态
                if (!string.IsNullOrEmpty(model.F_TransPersonCode) && type == 1 || type == 2 || type == 3 || type == 4 || type == 5 || type == 6 || type == 7)
                {
                    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)EnumDisItemOpt.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)EnumDisItemOpt.deal + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                        else if (type == 3)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=" + (int)EnumDisItemOpt.end + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                        else if (type == 4)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=" + (int)EnumDisItemOpt.stayred + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                        else if (type == 5)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=" + (int)EnumDisItemOpt.staydrug + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                        else if (type == 6)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=" + (int)EnumDisItemOpt.takeblood + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                        else if (type == 7)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=" + (int)EnumDisItemOpt.send + " and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                    }
                    if (i == transcode.Count())
                    {
                        if (type == 1)
                        {
                            wostate = (int)EnumDisWorkOrderState.receive;//已查收待处理
                        }
                        else if (type == 2)
                        {
                            wostate = (int)EnumDisWorkOrderState.dealing;//处理中
                        }
                        else if (type == 3)
                        {
                            wostate = (int)EnumDisWorkOrderState.end;//已完成
                        }
                        else if (type == 4)
                        {
                            wostate = (int)EnumDisWorkOrderState.staydrug;//已取红处方待取药
                        }
                        else if (type == 5)
                        {
                            wostate = (int)EnumDisWorkOrderState.end;//已取药待完成
                        }
                        else if (type == 6)
                        {
                            wostate = (int)EnumDisWorkOrderState.send;//已取血待送达
                        }
                        else if (type == 7)
                        {
                            wostate = (int)EnumDisWorkOrderState.send;//已送达待完成
                        }
                    }
                    else
                    {
                        wostate = (int)model.F_State;//工单状态不变
                    }

                }
                #endregion
                #region 处理工单            
                model.F_State = wostate;
                orderbll.Update(model);
                #endregion
                return true;
            }
            else
                return false;
            #endregion
        }


        /// <summary>
        /// 添加工单记录
        /// </summary>
        //public long AddLogTrans(int woid, int wostate, int type, 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 = (int)(EnumWorkOrder)(type);//工单类型
        //    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>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelWorkOrder(string[] ids)
        {
            string usercode = User.F_UserCode;
            if (usercode != "")
            {
                if (ids != null && ids.Length > 0)
                {
                    string strid = "";
                    foreach (string str in ids)
                    {
                        strid += str + ",";
                    }
                    if (orderbll.CustomDelete(strid, usercode))
                    {
                        return Success("删除成功！");
                    }
                    else return Error("删除失败！");
                }
                return Error("请选择要删除的记录！");

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


        public static string[] GetNamesArr<T>()
        {
            return Enum.GetNames(typeof(T));
        }

        public string test()
        {
            //return GetNamesArr<EnumWorkOrder>();
            //Enum.GetNames(typeof(EnumWorkOrder));
            string str = "";
            foreach (string s in Enum.GetNames(typeof(EnumWorkOrder)))
            {
                str += s + ",";
            }
            return str;
        }



    }
}