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_Mat_WorkOrderController : BaseController
    {
        private Bll.T_Mat_WorkOrder orderbll = new Bll.T_Mat_WorkOrder();
        private Bll.T_Sys_UserAccount userbll = new Bll.T_Sys_UserAccount();
        private Bll.T_Mat_WorkOrderItem itembll = new Bll.T_Mat_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)
        {
            if (User!=null)
            {
                string transql = "";
                List<string> wokerlist =new List<string>();
                #region 查询条件
                string sql = $" and F_IsDel=0";
                DataTable data = new DataTable();
                if (starttime.Trim() != "" && starttime != "undefined")
                    sql += $"and datediff(day,F_CreateTime,'" + starttime + "')<=0";
                if (endtime.Trim() != "" && endtime != "undefined")
                    sql += $"and datediff(day,F_CreateTime,'" + endtime + "')>=0";
                if (!string.IsNullOrEmpty(keyword))
                {
                    sql += $"and (F_WorkOrderCode like '%" + keyword.Trim() + "%' or F_ProposerCode like '%" + keyword.Trim() + "%' or F_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, 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
                {
                    sql += $" and F_ProposerStoreId=" + User.F_DeptId + "";
                }
                #endregion
                int recordCount = 0;
                if (!string.IsNullOrEmpty(sql))
                {
                    data = Bll.PagerBll.GetListPager
                        (
                        "T_Mat_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)
                    {
                        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((EnumMatWorkOrderState)wostate);
                                item.F_State = wostate;
                            }
                            else
                            {
                                item.F_WoState = EnumHelper.GetDescription((EnumMatWorkOrderState)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)
        {
         string str = string.Empty;
        var list= itembll.GetModelList("F_OptType=" + (int)EnumDevItemOpt.assign + "and F_WoState=" + (int)EnumDevWorkOrderState.assign + " and F_NextUser=" + usercode+" ").Select(t => t.F_WoID).Distinct<long>().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 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_WoState=" + wostate + "";
            }
            else
            {
                sql = $"  isnull(F_IsUsed, '0') = '0' and(F_CreateUser = " + usercode + " or  F_NextUser = " + usercode + ")";
            }
            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;
        }


        public string GetMatStateName(int F_Id, string F_UserCode)
        {
            return EnumHelper.GetDescription((EnumMatWorkOrderState)itembll.GetModelList("F_WoID=" + F_Id + " and (F_CreateUser=" + F_UserCode + " or F_NextUser=" + F_UserCode + ")").OrderByDescending(pp => pp.F_ID).FirstOrDefault().F_OptType);
        }
        /// <summary>
        /// 获取工单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetModelDetail(int id)
        {
            if (User != null)
            {
                string sql = "F_WoID = " + id + "";
                if (id <= 0)
                {
                    return Error("请选择要查询的工单！");
                }
                var model = orderbll.GetModel(id);
                string wostateName = EnumHelper.GetDescription((EnumMatWorkOrderState)model.F_State);
                var itemlist = itembll.GetModelList(sql);
                //List<Con_WorkOrderInput> Input = modeltoopi(list);
                if (model != null)
                {
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        model = model,
                        wostateName = wostateName,
                        itemlist = itemlist
                    };
                    return Content(obj.ToJson());
                }
                else
                    return Error("没有查询到此工单！");
            }
            else 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)
        {
            if (User!=null)
            {
                #region 查询条件
                string sql = $" and F_IsDel=0";
                DataTable data = new DataTable();
                if (starttime.Trim() != "" && starttime != "undefined")
                    sql += $" and datediff(day,F_CreateTime,'" + starttime + "') <=0 ";
                if (endtime.Trim() != "" && endtime != "undefined")
                    sql += $" and datediff(day,F_CreateTime,'" + endtime + "')>=0";
                if (!string.IsNullOrEmpty(keyword))
                {
                    sql += $"and (F_WorkOrderCode like '%" + keyword.Trim() + "%' or F_ProposerCode like '%" + keyword.Trim() + "%' or F_ProposerPhon like '%" + keyword.Trim() + "%')";
                }
                if (state >= 0)
                {
                    sql += $"and F_State=" + state;
                }
                #endregion
                if (isdc > 0)
                {
                    NPOIHelper nopi = new NPOIHelper();
                    data = new Bll.T_Mat_WorkOrder().GetListExpt(sql).Tables[0];
                    if (nopi.ExportToExcel("物资转移统计报表", data, col()) == "")
                    {
                        return Success("导出成功！");
                    }
                    else return Error("导出失败！");
                }
                else
                {
                    int recordCount = 0;
                    if (!string.IsNullOrEmpty(sql))
                    {
                        data = Bll.PagerBll.GetListPager
                            (
                            "T_Mat_WorkOrder aa",
                            "F_Id",
                            "*",
                            sql,
                            "ORDER BY F_Id desc",
                            pagesize,
                            pageindex,
                            true,
                            out recordCount
                            );
                    }
                    var modellist = orderbll.DataTableToList(data);
                    if (modellist.Count > 0)
                    {

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

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




        private string[] col()
        {
            string[] cel =
            {
                "工单编号","类型","申请仓库","送达科室","申请人","联系电话","工单内容","调度员","上报时间","转运部门","转运人","备注","派工及时率","转运完成率"
            };
            return cel;

        }

        /// <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 AddWorkOrder(int type, int hosid,int storeid, string store, string positon, string usercode, string username, string phon, string itemessage, string remark, string callid = "")
        {
            if (User != null)
            {

                #region 添加条件
                if (type != (int)EnumWorkOrder.Mat)
                    return Error("工单类型错误！");
                if (hosid <= 0)
                    return Error("请选择院区！");
                if (storeid<=0)
                    return Error("请选择申请仓库！");
                if (usercode == "")
                    return Error("请选择申请人！");
                if (phon == "")
                    return Error("请输入联系电话！");
                if (string.IsNullOrEmpty(itemessage))
                    return Error("请填写转移物资信息！");
                #endregion

                var model = new Model.T_Mat_WorkOrder();
                model.F_Type = (int)EnumWorkOrder.Mat;//工单类型  2物资转移
                model.F_Source = "PC端";
                model.F_CallID = callid;
                model.F_State = (int)EnumWorkOrderState.neworder;//新工单待转派
                model.F_WorkOrderCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");//工单编号
                model.F_ProposerStoreId = storeid;
                model.F_ProposerStore = store;//申请仓库
                model.F_StorePosition = positon;//仓库位置
                model.F_ProposerCode = usercode;//申请人
                model.F_ProposerName = username;
                model.F_ProposerPhon = phon;
                //model.F_SendDeptId = senddeptid;//送达科室
                //model.F_SendDeptName = deptname;//科室姓名
                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;
                #region 信息处理
                if (string.IsNullOrEmpty(itemessage))
                    return Error("请填写配送信息！");
                string[] _list = itemessage.TrimEnd(',').Split(',');
                string mscontents = "";
                //string deptstr = "";
                //string[] deptlist = { };
                try
                {
                    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 = new Bll.T_Sys_Department().GetModel(sendeptid).F_DeptName; }
                        catch { return Error("请填写正确送达科室信息！"); }
                        if (num > 0 && itemess != "" && sendepatname != "" && sendeptid > 0)
                        {
                            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, (int)EnumWorkOrder.Mat, User.F_UserName + "(" + User.F_UserCode + ")" + "创建新工单", 0, (int)EnumDisItemOpt.create, "", 0, User.F_UserCode);
                            }
                        }
                        else return Error("操作失败,请填写正确信息！");
                    }
                }
                catch
                {
                    return Error("配送信息格式不正确！");
                }
                #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, string store, string positon, string usercode, string username, string phon, int senddeptid, string deptname, string itemessage, string remark, string callid = "")
        {
            if (User != null)
            {
                #region 添加条件

                var model = orderbll.GetModel(woid);
            if (model == null)
                return Error("不存在此工单！");
            if (type <= 0)
                return Error("工单类型错误！");
            if (hosid <= 0)
                return Error("请选择院区！");
            if (string.IsNullOrEmpty(store))
                return Error("请选择申请仓库！");
            if (usercode == "")
                return Error("请选择申请人！");
            if (phon == "")
                return Error("请输入联系电话！");
            if (senddeptid == 0)
                return Error("请选择送达科室！");
            if (string.IsNullOrEmpty(itemessage))
                return Error("请填写转移物资信息！");
            if (model.F_State == (int)EnumMatWorkOrderState.assign || model.F_TransPersonCode!="")
                return Error("工单已指派不能修改！");
            #endregion
            model.F_ProposerStore = store;//申请仓库
            model.F_StorePosition = positon;//仓库位置
            model.F_ProposerCode = usercode;//申请人
            model.F_ProposerName = username;
            model.F_ProposerPhon = phon;
            model.F_SendDeptId = senddeptid;//送达科室
            model.F_SendDeptName = deptname;//科室姓名
            model.F_ItemMessages = itemessage;//物质转移内容
            model.F_Remark = remark;
            model.F_IsDel = 0;
            if (orderbll.Update(model))
            {
               logbll.AddLog(woid, 0,(int)EnumWorkOrder.Mat, User.F_UserName + "(" + User.F_UserCode + ")" + "修改工单", (int)EnumMatItemType.update, (int)EnumMatItemOpt.update, "", 0, User.F_UserCode);
                return Success("修改成功！");
            }
            else return Error("修改失败");
            }
            return Error("无操作权限");
        }

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

        //    Model.T_Mat_WorkOrderItem itemModel = new Model.T_Mat_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_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="woid"></param>
        /// <returns></returns>
        //public ActionResult AssignWo(int woid)
        //{
        //    string usercode = "8000";
        //    int state = 0;
        //    int clbm = 1;//综合保障中心
        //    var ua = userbll.GetModel(usercode);
        //    if (woid == 0)
        //        return Error("工单编号错误！");
        //    var omodel = orderbll.GetModel(woid);
        //    if (omodel != null)
        //    {
        //        bool n = AssignWO(ua, omodel, "", "", clbm);
        //        if (n)
        //        {
        //            omodel.F_ControlManCode = usercode;
        //            omodel.F_ControlManName = ua.F_UserName;
        //            orderbll.Update(omodel);
        //            return Success("转派成功！");
        //        }
        //        return Error("转派失败！");
        //    }
        //    return Error("转派失败,不存在此工单编号！");
        //}

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

        /// <summary>
        /// 添加工单记录
        /// </summary>
        public long AddLogTrans(int woid, int wostate, 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_Mat_WorkOrderItem itemModel = new Model.T_Mat_WorkOrderItem();
            #region 
            //处理当前工单的记录之前的记录过期
            var itemlast = itembll.GetModelList($" F_OptType !=1 and isnull(F_IsUsed,'0')='0' 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_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>
        private bool AssignTrans(Model.T_Sys_UserAccount nowUser, Model.T_Mat_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, content, (int)EnumMatItemType.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 (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("操作失败,不存在此工单编号！");
            }
            else return Error("无操作权限！");
        }



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


        /// <summary>
        /// 物资送达操作
        /// </summary>
        /// <param name="woid"></param>
        /// <returns></returns>
        public ActionResult ServiceWo(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("操作失败,不存在此工单编号！");
            }
            else 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_ProposerStoreId != User.F_DeptId)
                        return Error("无操作权限！");                 
                    //if (DealWO(User, omodel, "", "", 6))
                    var n = AddLogTrans(woid, (int)omodel.F_State, user.F_UserName + "(" + user.F_UserCode + ")" + "确认完结工单", (int)EnumDisItemType.deal, (int)EnumDisItemOpt.over, "", "", phon, talkie, 0, User);
                    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("操作失败,不存在此工单编号！");
            }
            else 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_Mat_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)EnumMatItemOpt.receive;//查收
                wostate1 = (int)EnumMatWorkOrderState.receive;//已查收待转运
            }
            if (type == 2)
            {
                opt = "处理工单";
                optbut = (int)EnumMatItemOpt.deal;//处理
                wostate1 = (int)EnumMatWorkOrderState.dealing;//转运中
            }
            if (type == 3)
            {
                opt = "物资已送达";
                optbut = (int)EnumMatItemOpt.send;
                wostate1 = (int)EnumMatWorkOrderState.send;//已完成
            }
            //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)EnumWorkOrder.Mat, content, (int)EnumMatItemType.deal, optbut, "", 0, nowUser.F_UserCode);
            if (itemid > 0)
            {
                #region 判断工单的状态
                if (!string.IsNullOrEmpty(model.F_TransPersonCode)&&type==1 || type == 2|| type == 3)
                {
                    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=2 and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                        else if (type == 2)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=3 and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                        else if (type == 3)
                        {
                            if (itembll.GetModelList(" F_WoID=" + model.F_Id + " and F_OptType=4 and F_CreateUser=" + item.ToString() + "").FirstOrDefault() != null)
                                i++;
                        }
                    }
                    if (i == transcode.Count())
                    {
                        if (type == 1)
                        {
                            wostate = (int)EnumMatWorkOrderState.receive;//已查收待处理
                        }
                        else if (type == 2)
                        {
                            wostate = (int)EnumMatWorkOrderState.dealing;//处理中
                        }
                        else if (type == 3)
                        {
                            wostate = (int)EnumMatWorkOrderState.send;//已送达
                        }
                    }
                    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>
        /// <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("无操作权限！");
        }


    }
}