Zoe
using AIMS.Bussiness.ApplicationDto.Dto;
using AIMS.Bussiness.ApplicationDto.NJWorkTasksDto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AIMS.Bussiness.Application.Application.NJTerminalApp
{
   public interface INJTerminalAppService
    {

      //=============================================展示终端列表================================================================
        /// <summary>
        /// 显示终端列表(后台)(Zoe)
        /// </summary>
        /// <param name="pageRows"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        KeyValuePair<int, IEnumerable<TerminalAll>> GetTerminalList(string SerialNum, int pageRows, int page);

      
        /// <summary>
        /// 展示终端列表(前台)
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="serialNum"></param>
        /// <param name="nJNum"></param>
        /// <param name="rows"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        KeyValuePair<int, IEnumerable<ReceptionTerminalAll>> ReceptionGetTerminalListM(string areaId, string serialNum, string nJNum, int rows, int page);
        KeyValuePair<int, IEnumerable<ReceptionTerminalAll>> ReceptionGetTerminalListH(Guid orgId, string serialNum, string nJNum, int rows, int page);

        /// <summary>
        /// 增加终端前展示(前台)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ReceptionBeforeInsertTerminalFromSerialNum ReceptionInsertTerminalFromSerialNum(string serialNum);
        ReceptionBeforeInsertTerminalFromNJNum ReceptionInsertTerminalFromNJNum(string nJNum);

        //=========================================================增加终端========================================================
        /// <summary>
        /// 增加终端(后台)(Zoe)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        DtoResult<string> InsertTerminal(TerminalInsert model);
        /// <summary>
        /// 增加终端(前台)(Zoe)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        DtoResult<string> ReceptionInsertTerminal(ReceptionTerminalInsert model);
        //========================================修改前展示终端列表=========================================================================
       
        /// <summary>
        /// 修改前展示终端列表(后台)
        /// </summary>
        /// <param name="terId"></param>
        /// <returns></returns>
        TerminalInfo GetTerminalInfo(Guid terId);
        /// <summary>
        /// 修改前展示终端列表(前台)
        /// </summary>
        /// <param name="terId"></param>
        /// <returns></returns>
        ReceptionTerminalInfo GetReceptionTerminalInfo(Guid terId);
        //============================================修改终端===========================================================
        /// <summary>
        /// 修改终端(后台)(Zoe)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        DtoResult<string> UpdateTerminal(TerminalUpdate model);
        /// <summary>
        /// 修改终端(前台)(Zoe)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        DtoResult<string> ReceptionUpdateTerminal(ReceptionTerminalUpdate model);
        //============================================删除终端====================================================================
        /// <summary>
        /// 删除终端(后台)(Zoe)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        DtoResult<string> DelTerminal(int id);
        /// <summary>
        /// 删除终端(前台)(Zoe)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        DtoResult<string> ReceptionDelTerminal(int id);
        //================================================启用或禁用终端=================================================================
        /// <summary>
        /// 启用或禁用终端(后台)(Zoe)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="disabled"></param>
        /// <returns></returns>
        DtoResult<string> SetTerminalEnabled(Guid id, bool enabled);
        //============================================解绑终端===================================================
        DtoResult<string> ReceptionUnbindTerminal(string serialNum);

        #region 区域树
        List<TreeNode> LoadAreaTreeNodeByUserId(Guid userId);

        List<TreeNode> GetAreaTreeNode(string code);
        #endregion
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AIMS.Bussiness.Interface;
using AIMS.Bussiness.ApplicationDto.NJWorkTasksDto;
using AIMS.Bussiness.ApplicationDto.Dto;
using Common.BaseLibrary.Unity;
using Microsoft.Practices.Unity;
using AIMS.Model;
using Common.IRepositories;
using AIMS.Bussiness.ApplicationDto.Enum;
using AIMS.Bussiness.Application.Application.WorkDefaultConfigApp;

namespace AIMS.Bussiness.Application.Application.NJTerminalApp
{


    /// <summary>
    /// 作者:Zoe
    /// 时间:2017/10/31
    /// 描述:终端应用层服务
    /// </summary>
   
    public  class NJTerminalAppService:INJTerminalAppService
    {
         /// <summary>
        /// 展示终端列表(后台)(Zoe)
        /// </summary>
        /// <returns></returns>
        public KeyValuePair<int, IEnumerable<TerminalAll>> GetTerminalList(string SerialNum, int rows, int page)
        {
            if (string.IsNullOrWhiteSpace(SerialNum)) SerialNum = "";
            IExtensionRepository<NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJTerminal>>();
            IExtensionRepository<TerminalType> TerminalTypeService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<TerminalType>>();
            IExtensionRepository<TerminalUpgradePackage> terminalUpgradePackageRepo = DIFactory.ObjectContainer.Resolve<IExtensionRepository<TerminalUpgradePackage>>();
            var TerminalQuery = TerminalService.GetModel(p => p.SerialNum.Contains(SerialNum) ).AsEnumerable();
            var TerminalTypeQuery = TerminalTypeService.GetModel().AsEnumerable();
            var terminalUpgradePackageQuery = terminalUpgradePackageRepo.GetModel().AsEnumerable();
            var query = from u in TerminalQuery
                        from o in TerminalTypeQuery
                        join p in terminalUpgradePackageQuery on o.Id equals p.TerminalTypeId into jop
                        from p in jop.DefaultIfEmpty()
                        where u.TypeId== o.Id
                        orderby u.SerialNum
                        select new TerminalAll
                        {
                            Id = u.Id,
                            SerialNum = u.SerialNum,
                            TypeId=o.Id,
                            TypeName=o.TypeName,
                            FirmwareVersion = p!=null? p.Versions:"",
                            SIMNumber = u.SIMNumber!=null?u.SIMNumber.ToString():"",
                            IsDisabled = u.IsDisabled,
                            StartTime = u.IsDisabled?"": u.StartTime.ToString("yyyy-MM-dd"),
                            AreaId = u.AreaId,
                            OrganizationId = u.OrganizationId,
                        };
            IEnumerable<TerminalAll> TerminalList = query.ToList();
         
             int startIndex = (page - 1) * rows;
             int count = TerminalList.Count();
             if (count > rows && rows != -1)
            {
                if ((startIndex + rows) > count)
                    TerminalList = TerminalList.Skip(startIndex).Take(count - startIndex);
                else
                    TerminalList = TerminalList.Skip(startIndex).Take(rows);
            }
           KeyValuePair<int, IEnumerable<TerminalAll>> kv = new KeyValuePair<int, IEnumerable<TerminalAll>>(count, TerminalList);
            return kv;
        }

    

        //=========================================================================================================================
        /// <summary>
        /// 展示终端(前台)(Zoe)管理员版本
        /// </summary>
        /// <param name="AreaId"></param>
        /// <param name="SerialNum"></param>
        /// <param name="NJNum"></param>
        /// <param name="pageRows"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public KeyValuePair<int, IEnumerable<ReceptionTerminalAll>> ReceptionGetTerminalListM(string areaId, string serialNum, string nJNum, int rows, int page)
        {
            if (string.IsNullOrWhiteSpace(serialNum)) serialNum = "";
            if (string.IsNullOrWhiteSpace(nJNum)) nJNum = "";
            IExtensionRepository<NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJTerminal>>();
            IExtensionRepository<NJ> NJService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJ>>();
            IExtensionRepository<AIMS.Model.NJWorkDefaultConfig> NJWorkDefaultConfigService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJWorkDefaultConfig>>();
            IExtensionRepository<Org> orgService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<Org>>();
            IExtensionRepository<User> userService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<User>>();

            var TerminalQuery = TerminalService.GetModel(p => p.IsDeleted!=true && p.SerialNum.Contains(serialNum) && p.AreaId==areaId).AsEnumerable();
            var NJQuery = NJService.GetModel(p => p.NJNum.Contains(nJNum)).AsEnumerable();
            var njWorkDefaultConfigQuery = NJWorkDefaultConfigService.GetModel().AsEnumerable();
            var orgList = orgService.GetModel().Where(p => p.IsDisabled != true).ToList();
            var userList = userService.GetModel().Where(p => p.IsDeleted != true).ToList();

            //var query = from n in NJWorkDefaultConfigQuery join
            //            u in TerminalQuery on n.TaskTerminalID equals u.Id
            //            join p in NJQuery on n.TaskNJID equals p.Id
            //            where n.TaskTerminalID == u.Id && n.TaskNJID== p.Id
            //            select new ReceptionTerminalAll
            //            {
            //                Id = u.Id,
            //                SerialNum = u.SerialNum,
            //                StartTime = u.StartTime.ToString("yyyy-MM-dd"),
            //                IsDisabled = u.IsDisabled,
            //                NJNum=p.NJNum,
            //                AreaId = u.AreaId,
            //                OrganizationId = u.OrganizationId,
            //                Owner=p.Owner,
            //            };
            var query = from u in TerminalQuery
                        join c in njWorkDefaultConfigQuery on u.Id equals c.TaskTerminalID into juc
                        from c in juc.DefaultIfEmpty()
                        join n in NJQuery on new { id= (c != null ? c.TaskNJID : 0) } equals new { id = n.Id } into jtn
                        from n in jtn.DefaultIfEmpty()
                        join o in orgList on u.OrganizationId equals o.Id into juo
                        from o in juo.DefaultIfEmpty()
                        join p in userList on u.UserId equals p.Id into jup
                        from p in jup.DefaultIfEmpty()
                        where (nJNum!="" && n!=null && n.NJNum!="") || nJNum==""
                        select new ReceptionTerminalAll
                        {

                            Id = u.Id,
                            SerialNum = u.SerialNum,
                            StartTime = u.IsDisabled?"": u.StartTime.ToString("yyyy-MM-dd"),
                            IsDisabled = u.IsDisabled,
                            NJNum = n != null ? n.NJNum : "",
                            AreaId = u.AreaId,
                            OrganizationId = u.OrganizationId,
                            Owner = o != null ? o.Name : (p != null ? p.Name : "")
                        };
            IEnumerable<ReceptionTerminalAll> TerminalList = query.ToList();
                   int startIndex = (page - 1) * rows;
            int count = TerminalList.Count();
            if (count > rows && rows != -1)
            {
                if ((startIndex + rows) > count)
                    TerminalList = TerminalList.Skip(startIndex).Take(count - startIndex);
                else
                    TerminalList = TerminalList.Skip(startIndex).Take(rows);
            }
            KeyValuePair<int, IEnumerable<ReceptionTerminalAll>> kv = new KeyValuePair<int, IEnumerable<ReceptionTerminalAll>>(count, TerminalList);
            return kv;
        }
       
        //---------------------------------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 展示终端(前台)(Zoe)合作社版本
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="serialNum"></param>
        /// <param name="nJNum"></param>
        /// <param name="rows"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public KeyValuePair<int, IEnumerable<ReceptionTerminalAll>> ReceptionGetTerminalListH(Guid orgId, string serialNum, string nJNum, int rows, int page)
        {
            if (string.IsNullOrWhiteSpace(serialNum)) serialNum = "";
            if (string.IsNullOrWhiteSpace(nJNum)) nJNum = "";
            IExtensionRepository<NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJTerminal>>();
            IExtensionRepository<NJ> NJService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJ>>();
            IExtensionRepository<AIMS.Model.NJWorkDefaultConfig> NJWorkDefaultConfigService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJWorkDefaultConfig>>();
            IExtensionRepository<Org> orgService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<Org>>();

            var TerminalQuery = TerminalService.GetModel(p => p.IsDeleted != true && p.SerialNum.Contains(serialNum) && p.OrganizationId == orgId).AsEnumerable();
            var org = orgService.Find(orgId);
            var NJQuery = NJService.GetModel(p => p.NJNum.Contains(nJNum)).AsEnumerable();
            var njWorkDefaultConfigQuery = NJWorkDefaultConfigService.GetModel().AsEnumerable();

            //var query = from n in NJWorkDefaultConfigQuery
            //            join u in TerminalQuery on n.TaskTerminalID equals u.Id
            //            join p in NJQuery on n.TaskNJID equals p.Id
            //            where n.TaskTerminalID == u.Id && n.TaskNJID == p.Id
            //            select new ReceptionTerminalAll
            //            {
            //                Id = u.Id,
            //                SerialNum = u.SerialNum,
            //                StartTime = u.StartTime.ToString("yyyy-MM-dd"),
            //                IsDisabled = u.IsDisabled,
            //                NJNum = p.NJNum,
            //                AreaId = u.AreaId,
            //                OrganizationId = u.OrganizationId,
            //                Owner = p.Owner,
            //            };

            var query = from u in TerminalQuery
                        join c in njWorkDefaultConfigQuery on u.Id equals c.TaskTerminalID into juc
                        from c in juc.DefaultIfEmpty()
                        join n in NJQuery on new { id = (c != null ? c.TaskNJID : 0) } equals new { id = n.Id } into jtn
                        from n in jtn.DefaultIfEmpty()
                        where (nJNum != "" && n != null && n.NJNum != "") || nJNum == ""
                        select new ReceptionTerminalAll
                        {
                            Id = u.Id,
                            SerialNum = u.SerialNum,
                            StartTime = u.IsDisabled ? "" : u.StartTime.ToString("yyyy-MM-dd"),
                            IsDisabled = u.IsDisabled,
                            NJNum = n!=null?n.NJNum:"",
                            AreaId = u.AreaId,
                            OrganizationId = u.OrganizationId,
                            Owner = org!=null?org.Name:"",
                        };

            IEnumerable<ReceptionTerminalAll> TerminalList = query.ToList();

            int startIndex = (page - 1) * rows;
            int count = TerminalList.Count();
            if (count > rows && rows != -1)
            {
                if ((startIndex + rows) > count)
                    TerminalList = TerminalList.Skip(startIndex).Take(count - startIndex);
                else
                    TerminalList = TerminalList.Skip(startIndex).Take(rows);
            }
            KeyValuePair<int, IEnumerable<ReceptionTerminalAll>> kv = new KeyValuePair<int, IEnumerable<ReceptionTerminalAll>>(count, TerminalList);
            return kv;
        }

       
        //======================================================================================================================

        /// <summary>
        /// 增加前展示通过终端序列号找农机车牌号(前台)
        /// </summary>
        /// <param name="serialNum"></param>
        /// <returns></returns>
        public ReceptionBeforeInsertTerminalFromSerialNum ReceptionInsertTerminalFromSerialNum(string serialNum)
        {
            ReceptionBeforeInsertTerminalFromSerialNum model = null;
            
            IExtensionRepository<AIMS.Model.NJ> NJService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJ>>();

            var NJ = NJService.GetModel().Where(p => p.NJIDCode == serialNum).FirstOrDefault();

            if (NJ == null)
            {
               
            }
            return model;
        }

        //==========================================================================================================================================
        /// <summary>
        /// 增加前展示通过农机车牌号找终端序列号(前台)
        /// </summary>
        /// <param name="nJNum"></param>
        /// <returns></returns>
        public ReceptionBeforeInsertTerminalFromNJNum ReceptionInsertTerminalFromNJNum(string nJNum)
        {
            ReceptionBeforeInsertTerminalFromNJNum model = null;
            IExtensionRepository<NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJTerminal>>();
            IExtensionRepository<AIMS.Model.NJ> NJService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJ>>();

            var NJ = NJService.GetModel().Where(p => p.NJNum == nJNum&&p.NJIDCode!=null && p.NJIDCode != "" && p.NJIDCode != "NJIDCode").FirstOrDefault();

            if (NJ != null)
            {
                model.SerialNum = NJ.NJIDCode;
            }
            return model;
        }



      
        //====================================================================================================================================
        /// <summary>
        /// 增加终端(后台)(Zoe)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public DtoResult<string> InsertTerminal(TerminalInsert model)
        {
            DtoResult<string> result = new DtoResult<string>() { Result = false };
            IExtensionRepository<AIMS.Model.NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJTerminal>>();
            AIMS.Model.NJTerminal Terminal = TerminalService.GetModel().Where(u => u.SerialNum== model.SerialNum).FirstOrDefault();
            if (Terminal != null)
            {
                result.Message = "该终端序列号已存在!";
                return result;
            }
           Terminal = TerminalService.GetModel().Where(u => u.SIMNumber== model.SIMNumber).FirstOrDefault();
            if (Terminal != null)
            {
                result.Message = "该SIM卡号已存在!";
                return result;
            }
            else
            { 
            Terminal = new AIMS.Model.NJTerminal()
            {
                Id= Guid.NewGuid(),
                 SerialNum =model.SerialNum,
                   TypeId=model.TypeId,
                   SIMNumber=model.SIMNumber,
                   IsDisabled=true,
                   //增加时间项,防止自动生成无效的时间 by:xyong
                    CreateTime=DateTime.Now,
                    StartTime=DateTime.MinValue,
                    TokenTimesout=DateTime.Now,
                   //end xyong
            };
            }
            TerminalService.Insert(Terminal);
            result.Result = true;
            result.Message = "操作成功!";
            return result;
        }


    
        //===========================================================================================



        /// <summary>
        /// 增加终端(前台)(Zoe)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public DtoResult<string> ReceptionInsertTerminal(ReceptionTerminalInsert model)
        {
            DtoResult<string> result = new DtoResult<string>() { Result = false };
            IExtensionRepository<AIMS.Model.User> userService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.User>>();
            IExtensionRepository<Org> orgService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<Org>>();
            IExtensionRepository<AIMS.Model.NJTerminal> terminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJTerminal>>();
            IExtensionRepository<AIMS.Model.NJ> njService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJ>>();
            IExtensionRepository<AIMS.Model.NJWorkDefaultConfig> njWorkDefaultConfigService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJWorkDefaultConfig>>();
            IWorkDefaultConfigAppService workDefaultConfigService = DIFactory.ObjectContainer.Resolve<IWorkDefaultConfigAppService>();//接口注入


            
            Org org = null;
            User user = userService.Find(model.UserId);
            if (user != null)
            {
                org = orgService.Find(user.OrganizationId); 
            }
            else
            {
                result.Message = "无效的用户标识!";
                return result;
            }

            AIMS.Model.NJTerminal terminal = terminalService.GetModel().Where(u => u.SerialNum == model.SerialNum).FirstOrDefault();
            if (terminal == null  )
            {
                result.Message = "该终端序列号未在系统中登记!";
                return result;
            }
            NJWorkDefaultConfig workDefaultConfig = njWorkDefaultConfigService.GetModel().Where(u => u.TaskTerminalID == terminal.Id).FirstOrDefault();
            if (workDefaultConfig != null)
            {
                result.Message = "该终端序列号已被绑定!";
                return result;
            }
            AIMS.Model.NJ nj = null;
            if (!string.IsNullOrWhiteSpace(model.NJNum))
            {
                nj = njService.GetModel().Where(u => u.NJNum == model.NJNum).FirstOrDefault();
                if (nj == null)
                {
                    result.Message = "该农机不存在!";
                    return result;
                }
                if(org!=null && nj.OrganizationId != org.Id)
                {
                    result.Message = "该农机不属于本组织!";
                    return result;
                }
                if (org == null && nj.OrganizationId == null && nj.Owner != user.Name)//TODO: nj表中没有用户Id,这里用了
                {
                    result.Message = "该农机不属于本用户!";
                    return result;
                }
                workDefaultConfig = njWorkDefaultConfigService.GetModel().Where(u => u.TaskNJID == nj.Id).FirstOrDefault();
                if (workDefaultConfig != null)
                {
                    result.Message = "农机已被绑定!";
                    return result;
                }
            }


            if (org!=null)
            {
                //操作人员归属合作社
                if((terminal.OrganizationId!=null && terminal.OrganizationId != org.Id) || terminal.UserId!=null)
                {
                    result.Message = "该终端不属于本组织!";
                    return result;
                }
                if (terminal.OrganizationId == org.Id)
                {
                    result.Message = "该终端已属于本组织,无需再次添加!";
                    return result;
                }
                terminal.OrganizationId = org.Id;
                terminal.AreaId = org.AreaId;
                terminal.UserId = null;
                terminalService.Update(terminal);
            }
            else
            {
                //有农机的散户
                if ((terminal.UserId != null && terminal.UserId != user.Id) || terminal.OrganizationId!=null)
                {
                    result.Message = "该终端不属于本用户!";
                    return result;
                }
                if(terminal.UserId==user.Id)
                {
                    result.Message = "该终端已属于本用户,无需再次添加!";
                    return result;
                }
                terminal.OrganizationId = null;
                terminal.AreaId = user.AreaId;
                terminal.UserId = user.Id;
                terminalService.Update(terminal);
            }

            if (nj==null)
            {
                result.Result = true;
                result.Message = "操作成功!";
                return result;
            }

            var bing = njWorkDefaultConfigService.GetModel().FirstOrDefault(p => p.TaskNJID == nj.Id && p.TaskTerminalID == terminal.Id);
            if (bing != null && nj.NJIDCode == terminal.Id.ToString())
            {
                result.Message = "此终端号与车牌号原先就是绑定的,无需再次绑定!";
                return result;
            }


            //var oldBind = njWorkDefaultConfigService.GetModel().FirstOrDefault(p =>  p.TaskTerminalID == terminal.Id);
            //if (oldBind != null)
            //{
            //    var oldNj = njService.GetModel().FirstOrDefault(p=>p.Id==oldBind.TaskNJID);
            //    oldNj.NJIDCode = "";
            //    njService.Update(oldNj);
            //}
            //AIMS.Model.NJ oldNJOfTeminal = njService.GetModel().Where(u => u.NJIDCode == model.SerialNum).FirstOrDefault();
            //if (oldNJOfTeminal != null)
            //{
            //    oldNJOfTeminal.NJIDCode = "";
            //    njService.Update(oldNJOfTeminal);
            //}
            //var  list = njWorkDefaultConfigService.GetModel().Where(u => u.TaskTerminalID == terminal.Id || u.TaskNJID==nj.Id).ToList();
            //if (list.Count > 0)
            //{
            //    njWorkDefaultConfigService.Delete(list);
            //}
            
            result = workDefaultConfigService.BingingWorkDefault(nj.Id, terminal.Id);
            //result.Result = true;
            //result.Message = "操作成功!";
            return result;
        }


     
            //=============================================================================================
            /// <summary>
            /// 修改终端前展示(后台)
            /// </summary>
            /// <param name="terId"></param>
            /// <returns></returns>
            public TerminalInfo GetTerminalInfo(Guid terId)
        {
            TerminalInfo model = null;
            IExtensionRepository<AIMS.Model.NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJTerminal>>();
            var Terminal = TerminalService.Find(terId);
            if (Terminal!=null)
            {
                model = new TerminalInfo();
                model.Id = Terminal.Id;
                model.SerialNum = Terminal.SerialNum;
                model.TypeId = Terminal.TypeId;
                model.SIMNumber = Terminal.SIMNumber;
            }
            return model;
        }

        /// <summary>
        /// 修改终端前展示(前台)
        /// </summary>
        /// <param name="terId"></param>
        /// <returns></returns>
        public ReceptionTerminalInfo GetReceptionTerminalInfo(Guid terId)
        {
            ReceptionTerminalInfo model = null;
            IExtensionRepository<AIMS.Model.NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJTerminal>>();
            IExtensionRepository<AIMS.Model.NJ> NJService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJ>>();
            IExtensionRepository<NJWorkDefaultConfig> njWorkDefaultConfigRepo = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJWorkDefaultConfig>>();
            

            var Terminal = TerminalService.Find(terId);
           
            if (Terminal != null)
            {
                model = new ReceptionTerminalInfo();
                model.Id = Terminal.Id;
                model.SerialNum = Terminal.SerialNum;
                model.StartTime = Terminal.IsDisabled ? "" : Terminal.StartTime.ToString("yyyy-MM-dd");
                model.IsDisabled = Terminal.IsDisabled;
                var njWorkDefaultConfig = njWorkDefaultConfigRepo.GetModel().FirstOrDefault(p=>p.TaskTerminalID==Terminal.Id);
                if (njWorkDefaultConfig != null)
                {
                    var NJ = NJService.GetModel().Where(p => p.Id == njWorkDefaultConfig.TaskNJID).FirstOrDefault();
                    if (NJ != null)
                    {
                        model.NJNum = NJ.NJNum;
                    }
                }
                
            }
            return model;
        }

     
        //=============================================================================================================================
        /// <summary>
        ///修改终端(后台)(Zoe)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public DtoResult<string> UpdateTerminal(TerminalUpdate model)
        {
            DtoResult<string> result = new DtoResult<string>() { Result = false };
            IExtensionRepository<AIMS.Model.NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJTerminal>>();
            AIMS.Model.NJTerminal Terminal = TerminalService.Find(model.Id);
                if (Terminal != null)
            {
                if (Terminal.SerialNum != model.SerialNum&&Terminal.Id!=model.Id)
                {
                    AIMS.Model.NJTerminal item = TerminalService.GetModel().Where(u => u.SerialNum == model.SerialNum).FirstOrDefault();
                    if (item != null)
                    {
                        result.Message = "该终端序列号已存在!";
                        return result;
                    }
                }

                if (Terminal.SIMNumber != model.SIMNumber && Terminal.Id != model.Id)
                {
                    AIMS.Model.NJTerminal item = TerminalService.GetModel().Where(u => u.SIMNumber == model.SIMNumber).FirstOrDefault();
                    if (item != null)
                    {
                        result.Message = "该SIM卡号已存在!";
                        return result;
                    }
                }

                Terminal.SerialNum = model.SerialNum;
                Terminal.TypeId = model.TypeId;
                Terminal.SIMNumber = model.SIMNumber;
                TerminalService.Update(Terminal);
                result.Result = true;
                result.Message = "操作成功!";
                return result;
            }
            result.Message = "该终端不存在!";
            return result;
        }
        //===================================================================================================================
        /// <summary>
        /// 修改终端(绑定农机)(前台)(Zoe)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public DtoResult<string> ReceptionUpdateTerminal(ReceptionTerminalUpdate model)
        {
            DtoResult<string> result = new DtoResult<string>() { Result = false };
            IExtensionRepository<AIMS.Model.User> userService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.User>>();
            IExtensionRepository<Org> orgService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<Org>>();
            IExtensionRepository<AIMS.Model.NJTerminal> terminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJTerminal>>();
            IExtensionRepository<AIMS.Model.NJ> njService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJ>>();
            IExtensionRepository<AIMS.Model.NJWorkDefaultConfig> njWorkDefaultConfigService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJWorkDefaultConfig>>();
            IWorkDefaultConfigAppService workDefaultConfigService = DIFactory.ObjectContainer.Resolve<IWorkDefaultConfigAppService>();


            AIMS.Model.NJTerminal oldTerminal = terminalService.Find(model.Id);

            if (oldTerminal != null)
            {
                Org org = null;
                User user = userService.Find(model.UserId);
                if (user != null)
                {
                    org = orgService.Find(user.OrganizationId);
                }
                else
                {
                    result.Message = "无效的用户标识!";
                    return result;
                }

                AIMS.Model.NJTerminal terminal = terminalService.GetModel().Where(u => u.SerialNum == model.SerialNum).FirstOrDefault();
                if (terminal == null)
                {
                    result.Message = "该终端序列号未登记!";
                    return result;
                }
                NJWorkDefaultConfig workDefaultConfig = njWorkDefaultConfigService.GetModel().Where(u => u.TaskTerminalID == terminal.Id && u.TaskTerminalID!=oldTerminal.Id).FirstOrDefault();
                if (workDefaultConfig != null)
                {
                    result.Message = "该终端序列号已被绑定!";
                    return result;
                }
                

                AIMS.Model.NJ nj = null;
                if (!string.IsNullOrWhiteSpace(model.NJNum))
                {
                    nj = njService.GetModel().Where(u => u.NJNum == model.NJNum).FirstOrDefault();
                    if (nj == null)
                    {
                        result.Message = "该农机车牌号未登记!";
                        return result;
                    }
                    if (org != null && nj.OrganizationId != org.Id)
                    {
                        result.Message = "该车牌号不属于本组织!";
                        return result;
                    }
                    if (org == null && nj.OrganizationId == null && nj.Owner != user.Name)//TODO: nj表中没有用户Id,这里用了
                    {
                        result.Message = "该车牌号不属于本用户!";
                        return result;
                    }
                    workDefaultConfig = njWorkDefaultConfigService.GetModel().Where(u => u.TaskNJID == nj.Id && u.TaskTerminalID!=oldTerminal.Id).FirstOrDefault();
                    if (workDefaultConfig != null)
                    {
                        result.Message = "农机已被绑定!";
                        return result;
                    }
                }


                if (terminal.Id != oldTerminal.Id)
                {
                    if (org != null)
                    {
                        //操作人员归属合作社
                        if ((terminal.OrganizationId != null && terminal.OrganizationId != org.Id) || terminal.UserId != null)
                        {
                            result.Message = "该终端序列号不属于本组织!";
                            return result;
                        }
                        if (terminal.OrganizationId == org.Id)
                        {
                            result.Message = "填写的终端序列号已属于本组织,不允许重复!";
                            return result;
                        }
                        //解绑原先的绑定
                        var oldBind0 = njWorkDefaultConfigService.GetModel().FirstOrDefault(p => p.TaskTerminalID == oldTerminal.Id);
                        if (oldBind0 != null)
                        {
                            var oldNj = njService.GetModel().FirstOrDefault(p => p.Id == oldBind0.TaskNJID);
                            oldNj.NJIDCode = "";
                            njService.Update(oldNj);
                        }

                        var list = njWorkDefaultConfigService.GetModel().Where(u => u.TaskTerminalID == oldTerminal.Id).ToList();
                        if (list.Count > 0)
                        {
                            njWorkDefaultConfigService.Delete(list);
                        }
                        oldTerminal.OrganizationId = null;
                        oldTerminal.UserId = null;
                        oldTerminal.AreaId = null;
                        terminalService.Update(oldTerminal);
                        //新的
                        terminal.OrganizationId = org.Id;
                        terminal.AreaId = org.AreaId;
                        terminal.UserId = null;
                        terminalService.Update(terminal);
                    }
                    else
                    {
                        //有农机的散户
                        if ((terminal.UserId != null && terminal.UserId != user.Id) || terminal.OrganizationId != null)
                        {
                            result.Message = "该终端序列号不属于本用户!";
                            return result;
                        }
                        if (terminal.UserId == user.Id)
                        {
                            result.Message = "填写的终端序列号已属于本用户,不允许重复!";
                            return result;
                        }
                        //解绑原先的绑定
                        var oldBind0 = njWorkDefaultConfigService.GetModel().FirstOrDefault(p => p.TaskTerminalID == oldTerminal.Id);
                        if (oldBind0 != null)
                        {
                            var oldNj = njService.GetModel().FirstOrDefault(p => p.Id == oldBind0.TaskNJID);
                            oldNj.NJIDCode = "";
                            njService.Update(oldNj);
                        }

                        var list = njWorkDefaultConfigService.GetModel().Where(u => u.TaskTerminalID == oldTerminal.Id).ToList();
                        if (list.Count > 0)
                        {
                            njWorkDefaultConfigService.Delete(list);
                        }
                        oldTerminal.OrganizationId = null;
                        oldTerminal.UserId = null;
                        oldTerminal.AreaId = null;
                        terminalService.Update(oldTerminal);

                        //新的
                        terminal.OrganizationId = null;
                        terminal.AreaId = user.AreaId;
                        terminal.UserId = user.Id;
                        terminalService.Update(terminal);
                    }
                    
                }
                if (nj==null)
                {
                    result.Result = true;
                    result.Message = "操作成功!";
                    return result;
                }



                var bing = njWorkDefaultConfigService.GetModel().FirstOrDefault(p => p.TaskNJID == nj.Id && p.TaskTerminalID == terminal.Id);
                if (bing != null && nj.NJIDCode == terminal.Id.ToString())
                {
                    result.Message = "此终端号与车牌号原先就是绑定的,无需再次绑定!";
                    return result;
                }


                var oldBind = njWorkDefaultConfigService.GetModel().FirstOrDefault(p => p.TaskTerminalID == terminal.Id);
                if (oldBind != null)
                {
                    var oldNj = njService.GetModel().FirstOrDefault(p => p.Id == oldBind.TaskNJID);
                    oldNj.NJIDCode = "";
                    njService.Update(oldNj);
                }
               
                var oldlist = njWorkDefaultConfigService.GetModel().Where(u => u.TaskTerminalID == terminal.Id || u.TaskNJID == nj.Id).ToList();
                if (oldlist.Count > 0)
                {
                    njWorkDefaultConfigService.Delete(oldlist);
                }

                result = workDefaultConfigService.BingingWorkDefault(nj.Id, terminal.Id);

                //result.Result = true;
                //result.Message = "操作成功!";
                return result;
            }
            result.Message = "该终端不存在!";
            return result;
        }
        //================================================================================================================================
        /// <summary>
        /// 删除终端(后台)(Zoe)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DtoResult<string> DelTerminal(int id)
        {
            DtoResult<string> result = new DtoResult<string>() { Result = false };
            IExtensionRepository<AIMS.Model.NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJTerminal>>();
            AIMS.Model.NJTerminal item = TerminalService.Find(id);
            if (item != null)
            {
                item.IsDeleted = true;
                TerminalService.Update(item);
                result.Result = true;
                result.Message = "操作成功!";
                return result;
            }
            result.Message = "终端不存在,传入Id错误!";
            return result;
        }
        //==========================================================================================================================
        /// <summary>
        /// 删除终端(前台)(Zoe)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DtoResult<string> ReceptionDelTerminal(int id)
        {
            DtoResult<string> result = new DtoResult<string>() { Result = false };
            IExtensionRepository<AIMS.Model.NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJTerminal>>();
            AIMS.Model.NJTerminal item = TerminalService.Find(id);
            if (item != null)
            {
                //item.IsDeleted = true;
                item.OrganizationId = null;
                item.UserId = null;
                item.AreaId = null;
                TerminalService.Update(item);
                result.Result = true;
                result.Message = "操作成功!";
                return result;
            }
            result.Message = "终端不存在,传入Id错误!";
            return result;
        }
        //==================================================================================================================================
        /// <summary>
        /// 启用或禁用终端(后台)(Zoe)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DtoResult<string> SetTerminalEnabled(Guid id, bool enabled)
        {
            DtoResult<string> result = new DtoResult<string>() { Result = false };
            IExtensionRepository<AIMS.Model.NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJTerminal>>();
            AIMS.Model.NJTerminal item = TerminalService.Find(id);
            if (item != null)
            {
                item.IsDisabled = !enabled;
                item.StartTime =  enabled ? (item.StartTime == DateTime.MinValue?DateTime.Now:item.StartTime) : item.StartTime;
                TerminalService.Update(item);
                result.Result = true;
                result.Message = "操作成功!";
                return result;
            }
            result.Message = "终端不存在,传入Id错误!";
            return result;
        }
        //======================================================================================================================

        /// <summary>
        /// 解绑农机(前台)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DtoResult<string> ReceptionUnbindTerminal(string serialNum)
        {
            DtoResult<string> result = new DtoResult<string>() { Result = false };
            IExtensionRepository<AIMS.Model.NJTerminal> TerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJTerminal>>();
            IExtensionRepository<AIMS.Model.NJ> NJService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJ>>();
            IExtensionRepository<AIMS.Model.NJWorkDefaultConfig> NJWorkDefaultConfigService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AIMS.Model.NJWorkDefaultConfig>>();

            //AIMS.Model.NJTerminal item = TerminalService.Find(serialNum);
            AIMS.Model.NJTerminal terminal = TerminalService.GetModel().Where(u => u.SerialNum == serialNum).FirstOrDefault();
            AIMS.Model.NJ NJ = NJService.GetModel().Where(u => u.NJIDCode == serialNum).FirstOrDefault();
            AIMS.Model.NJWorkDefaultConfig nJWorkDefaultConfig = NJWorkDefaultConfigService.GetModel().Where(u => u.TaskTerminalID == terminal.Id).FirstOrDefault();
            if (NJ != null&& nJWorkDefaultConfig!=null)
            {
             
                NJ.NJIDCode = "";
                NJService.Update(NJ);
                //nJWorkDefaultConfig.TaskTerminalID = new Guid("");
                //NJWorkDefaultConfigService.Update(nJWorkDefaultConfig);
                NJWorkDefaultConfigService.Delete(nJWorkDefaultConfig);
                
                result.Result = true;
                result.Message = "操作成功!";
                return result;
            }
            result.Message = "未绑定!";
            return result;
        }

        #region 区域树
        public List<TreeNode> LoadAreaTreeNodeByUserId(Guid userId)
        {
            IExtensionRepository<AdminArea> areaService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AdminArea>>();
            IExtensionRepository<TAreaAdministrator> areaAdministratorService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<TAreaAdministrator>>();

            IEnumerable<string> areaAdminIdList = areaAdministratorService.GetModel().Where(u => u.UserId == userId).Select(u => u.AreaId).ToList();
            List<AdminArea> areaQuery = areaService.GetModel().Where(u => areaAdminIdList.Contains(u.Id) && u.Level == 0).ToList();
            List<AdminArea> areaQuery1 = areaService.GetModel().Where(u => areaAdminIdList.Contains(u.Id) && u.Level == 1).ToList();
            List<AdminArea> areaQuery2 = areaService.GetModel().Where(u => areaAdminIdList.Contains(u.Id) && u.Level == 2).ToList();
            List<AdminArea> areaQuery3 = areaService.GetModel().Where(u => areaAdminIdList.Contains(u.Id) && u.Level == 3).ToList();

            if (areaQuery.Count > 0)
                areaAdminIdList = areaQuery.Select(u => u.Id).ToList();
            else if (areaQuery1.Count > 0)
                areaAdminIdList = areaQuery1.Select(u => u.Id).ToList();
            else if (areaQuery2.Count > 0)
                areaAdminIdList = areaQuery2.Select(u => u.Id).ToList();
            else if (areaQuery3.Count > 0)
                areaAdminIdList = areaQuery3.Select(u => u.Id).ToList();

            if (areaAdminIdList != null && areaAdminIdList.Count() > 0)
            {
                List<AdminArea> areaList = areaService.GetModel().Where(u => areaAdminIdList.Contains(u.Id)).ToList();
                List<AdminArea> areaAllList = areaService.GetModel().Where(u => areaAdminIdList.Contains(u.ParentId) && u.IsActive == true).ToList();
                return ToTreeNodes(areaList, areaAllList, true);
            }
            return null;
        }

        public List<TreeNode> GetAreaTreeNode(string code)
        {
            IExtensionRepository<AdminArea> areaService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AdminArea>>();
            List<AdminArea> areaList = new List<AdminArea>();
            if (!string.IsNullOrEmpty(code))
            {
                AdminArea area = areaService.Find(code);
                if (area != null)
                {
                    if (area.IsActive == false)
                        areaList = null;
                    else
                        areaList = areaService.GetModel().Where(u => u.ParentId == code && u.IsActive == true).ToList();
                }
            }
            return ToTreeNodes(areaList, null, false);
        }
        private List<TreeNode> ToTreeNodes(List<AdminArea> listPer, List<AdminArea> areaAllList, bool isFirstVisit)
        {
            List<TreeNode> listNodes = new List<TreeNode>();
            if (listPer != null)
            {

                LoadTreeNode(listPer, listNodes, areaAllList, isFirstVisit);
            }
            return listNodes;
        }

        private void LoadTreeNode(List<AdminArea> listPer, List<TreeNode> listNodes, List<AdminArea> areaAllList, bool isFirstVisit)
        {
            if (listPer != null)
            {
                foreach (AdminArea item in listPer)
                {
                    TreeNode node = ToNode(item, areaAllList, isFirstVisit);
                    listNodes.Add(node);
                    if (isFirstVisit)
                    {
                        LoadTreeNode(areaAllList, node.children, null, false);
                    }
                }
            }
        }

        private TreeNode ToNode(AdminArea area, List<AdminArea> areaAllList, bool isFirstVisit)
        {
            IExtensionRepository<NJTerminal> njTerminalService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<NJTerminal>>();
            IExtensionRepository<AdminArea> areaAppService = DIFactory.ObjectContainer.Resolve<IExtensionRepository<AdminArea>>();

            int njTerminalCount = njTerminalService.GetModel().Where(u => u.AreaId == area.Id &&u.IsDisabled==false&& u.IsDeleted != true).ToList().Count();
            if (area == null)
                return null;
            string nodeState = "closed";
            List<AdminArea> areaList = areaAppService.GetModel().Where(u => u.ParentId == area.Id && u.IsActive == true).ToList();

            if (areaList == null || areaList.Count <= 0 || isFirstVisit)
                nodeState = "open";
            TreeNode node = new TreeNode()
            {
                id = area.Id.ToString(),
                text = area.Name + "(" + njTerminalCount.ToString() + ")",
                parentId = area.ParentId.ToString(),
                level = area.Level,
                state = nodeState,
                isActive = area.IsActive,
                Checked = true,
                children = new List<TreeNode>()
            };
            return node;
        }
        #endregion
    }


}
using AIMS.Bussiness.Application.Application.NJTerminalApp;
using AIMS.Bussiness.ApplicationDto.Dto;
using AIMS.Bussiness.ApplicationDto.NJWorkTasksDto;
using AIMS.Bussiness.ApplicationDto.TerminalDto;
using AIMS.Bussiness.Interface;
using AIMS.Model;
using AIMS.Web.Helper;
using Common.BaseLibrary.Extension;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;


namespace AIMS.Web.Api
{
    /// <summary>
    /// 终端控制器(Zoe)
    /// </summary>
    public class NJTerminalController : ApiBaseController
    {
        private INJTerminalAppService iNJTerminalAppService = null;

        public NJTerminalController(INJTerminalAppService njerminalAppService, IAIMSOrganizationService organizationService)
            : base(organizationService)
        {
            this.iNJTerminalAppService = njerminalAppService;
        }
        //===================================展示终端列表============================================================
        /// <summary>
        /// 展示终端列表(后台)
        /// </summary>
        /// <param name="SerialNum">终端序列号</param>
        /// <param name="rows">行数</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/api/NJTerminal/GetTerminalList")]
        public DtoResult<GridDto<List<TerminalAll>>> GetTerminalList(string SerialNum, int rows, int page)
        {
            KeyValuePair<int, IEnumerable<TerminalAll>> modelList = iNJTerminalAppService.GetTerminalList(SerialNum, rows, page);
            GridDto<List<TerminalAll>> dto = new GridDto<List<TerminalAll>>();
            dto.Total = modelList.Key;
            dto.Rows = modelList.Value.ToList();
            return DtoResultHelper<GridDto<List<TerminalAll>>>.RetDtoResult((int)HttpStatusCode.OK, "成功", true, dto);
        }

        /// <summary>
        /// 展示终端列表(前台)管理员版本
        /// </summary>
        /// <param name="areaId"></param>
        /// <param name="serialNum"></param>
        /// <param name="nJNum"></param>
        /// <param name="rows"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/api/NJTerminal/ReceptionGetTerminalListM")]
       
        public DtoResult<GridDto<List<ReceptionTerminalAll>>> ReceptionGetTerminalListM(string areaId, string serialNum, string nJNum, int rows, int page)
        {
            KeyValuePair<int, IEnumerable<ReceptionTerminalAll>> modelList = iNJTerminalAppService.ReceptionGetTerminalListM( areaId, serialNum, nJNum, rows, page);
            GridDto<List<ReceptionTerminalAll>> dto = new GridDto<List<ReceptionTerminalAll>>();
            dto.Total = modelList.Key;
            dto.Rows = modelList.Value.ToList();
            return DtoResultHelper<GridDto<List<ReceptionTerminalAll>>>.RetDtoResult((int)HttpStatusCode.OK, "成功", true, dto);
        }
//------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 展示终端列表(前台)合作社版本
        /// </summary>
        /// <param name="orgId"></param>
        /// <param name="serialNum"></param>
        /// <param name="nJNum"></param>
        /// <param name="rows"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/api/NJTerminal/ReceptionGetTerminalListH")]

        public DtoResult<GridDto<List<ReceptionTerminalAll>>> ReceptionGetTerminalListH(Guid orgId, string serialNum, string nJNum, int rows, int page)
        {
            KeyValuePair<int, IEnumerable<ReceptionTerminalAll>> modelList = iNJTerminalAppService.ReceptionGetTerminalListH(orgId, serialNum, nJNum, rows, page);
            GridDto<List<ReceptionTerminalAll>> dto = new GridDto<List<ReceptionTerminalAll>>();
            dto.Total = modelList.Key;
            dto.Rows = modelList.Value.ToList();
            return DtoResultHelper<GridDto<List<ReceptionTerminalAll>>>.RetDtoResult((int)HttpStatusCode.OK, "成功", true, dto);
        }
        //=======================================================================================================================
        /// <summary>
        /// 增加前展示通过终端序列号找农机车牌号(前台)
        /// </summary>
        /// <param name="serialNum"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/api/NJTerminal/ReceptionInsertTerminalFromSerialNum")]
        public DtoResult<ReceptionBeforeInsertTerminalFromSerialNum> ReceptionInsertTerminalFromSerialNum(string serialNum)
        {
           
            var model = iNJTerminalAppService.ReceptionInsertTerminalFromSerialNum(serialNum);
            if (model != null)
            {
                return DtoResultHelper<ReceptionBeforeInsertTerminalFromSerialNum>.RetDtoResult((int)HttpStatusCode.OK, "成功", true, model);
            }
            return DtoResultHelper<ReceptionBeforeInsertTerminalFromSerialNum>.RetDtoResult((int)HttpStatusCode.NotFound, "没有找到对应车牌号", false, null);
        }

        /// <summary>
        /// 增加前展示通过农机车牌号找终端序列号(前台)
        /// </summary>
        /// <param name="nJNum"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/api/NJTerminal/ReceptionInsertTerminalFromNJNum")]
        public DtoResult<ReceptionBeforeInsertTerminalFromNJNum> ReceptionInsertTerminalFromNJNum(string nJNum)
        {

            var model = iNJTerminalAppService.ReceptionInsertTerminalFromNJNum(nJNum);
            if (model != null)
            {
                return DtoResultHelper<ReceptionBeforeInsertTerminalFromNJNum>.RetDtoResult((int)HttpStatusCode.OK, "成功", true, model);
            }
            return DtoResultHelper<ReceptionBeforeInsertTerminalFromNJNum>.RetDtoResult((int)HttpStatusCode.NotFound, "没有找到对应终端序列号", false, null);
        }

        //=====================================新增终端======================================================
        /// <summary>
        /// 新增终端(后台)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/api/NJTerminal/InsertTerminal")]
        public DtoResult<string> InsertTerminal([FromBody]TerminalInsert model)
        {
            DtoResult<string> dtoResult = iNJTerminalAppService.InsertTerminal(model);
            dtoResult.Code = ((int)(HttpStatusCode.OK)).ToString();
            return dtoResult;
        }
        /// <summary>
        /// 新增终端(前台)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/api/NJTerminal/ReceptionInsertTerminal")]
        public DtoResult<string> ReceptionInsertTerminal([FromBody]ReceptionTerminalInsert model)
        {
            DtoResult<string> dtoResult = iNJTerminalAppService.ReceptionInsertTerminal(model);
            dtoResult.Code = ((int)(HttpStatusCode.OK)).ToString();
            return dtoResult;
        }
        //=================================修改前展示终端列表==========================================================
        /// <summary>
        /// 修改前展示终端(后台)
        /// </summary>
        /// <param name="terId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/api/NJTerminal/GetTerminalInfo")]
        public DtoResult<TerminalInfo> GetTerminalInfo(string terId)
        {
            var id = Guid.Parse(terId);
            var model = iNJTerminalAppService.GetTerminalInfo(id);
            if (model != null)
            {
                return DtoResultHelper<TerminalInfo>.RetDtoResult((int)HttpStatusCode.OK, "成功", true, model);
            }
            return DtoResultHelper<TerminalInfo>.RetDtoResult((int)HttpStatusCode.NotFound, "没有找到对应终端", false, null);
        }

        /// <summary>
        /// 修改前展示终端列表(前台)
        /// </summary>
        /// <param name="terId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/api/NJTerminal/GetReceptionTerminalInfo")]
        public DtoResult<ReceptionTerminalInfo> GetReceptionTerminalInfo(string terId)
        {
            var id = Guid.Parse(terId);
            var model = iNJTerminalAppService.GetReceptionTerminalInfo(id);
            if (model != null)
            {
                return DtoResultHelper<ReceptionTerminalInfo>.RetDtoResult((int)HttpStatusCode.OK, "成功", true, model);
            }
            return DtoResultHelper<ReceptionTerminalInfo>.RetDtoResult((int)HttpStatusCode.NotFound, "没有找到对应终端", false, null);
        }
        //======================================更改终端===============================================================
        /// <summary>
        /// 更改终端(后台)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/api/NJTerminal/UpdateTerminal")]
        public DtoResult<string> UpdateTerminal([FromBody]TerminalUpdate model)
        {
            DtoResult<string> dtoResult = iNJTerminalAppService.UpdateTerminal(model);
            dtoResult.Code = ((int)(HttpStatusCode.OK)).ToString();
            return dtoResult;
        }


        /// <summary>
        /// 更改终端(绑定农机)(前台)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/api/NJTerminal/ReceptionUpdateTerminal")]
        public DtoResult<string> ReceptionUpdateTerminal([FromBody]ReceptionTerminalUpdate model)
        {
            DtoResult<string> dtoResult = iNJTerminalAppService.ReceptionUpdateTerminal(model);
            dtoResult.Code = ((int)(HttpStatusCode.OK)).ToString();
            return dtoResult;
        }
        //=======================================删除终端========================================================
        /// <summary>
        /// 删除终端(后台)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/api/NJTerminal/DelTerminal")]
        public DtoResult<string> DelTerminal([FromBody]int id)
        {
            DtoResult<string> dtoResult = iNJTerminalAppService.DelTerminal(id);
            dtoResult.Code = ((int)(HttpStatusCode.OK)).ToString();
            return dtoResult;
        }

        /// <summary>
        /// 删除终端(前台)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/api/NJTerminal/ReceptionDelTerminal")]
        public DtoResult<string> ReceptionDelTerminal([FromBody]int id)
        {
            DtoResult<string> dtoResult = iNJTerminalAppService.ReceptionDelTerminal(id);
            dtoResult.Code = ((int)(HttpStatusCode.OK)).ToString();
            return dtoResult;
        }
        //===========================================启用或禁用终端==========================================================
        /// <summary>
        /// 启用或禁用终端(后台)
        /// </summary>
        /// <param name="model">参数{id:终端Id,enabled:是否启用}</param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/api/NJTerminal/SetTerminalEnabled")]
        public DtoResult<string> SetTerminalEnabled([FromBody]TerminalEnableModel model)
        {
            DtoResult<string> dtoResult = iNJTerminalAppService.SetTerminalEnabled(Guid.Parse(model.id), model.enabled);
            dtoResult.Code = ((int)(HttpStatusCode.OK)).ToString();
            return dtoResult;
        }

        //=================================================解绑农机(前台)============================================================================

        /// <summary>
        /// 解绑农机(前台)
        /// </summary>
        /// <param name="serialNum"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/api/NJTerminal/ReceptionUnbindTerminal")]
        public DtoResult<string> ReceptionUnbindTerminal([FromBody]string serialNum)
        {
            DtoResult<string> dtoResult = iNJTerminalAppService.ReceptionUnbindTerminal(serialNum);
            dtoResult.Code = ((int)(HttpStatusCode.OK)).ToString();
            return dtoResult;
        }

        /// <summary>
        /// 通过用户Id,初次加载树,展开第一层节点
        /// </summary>
        /// <param name="userId">用户Id guid</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/api/NJTerminal/LoadAreaTreeNodeByUserId")]
        public DtoResult<List<TreeNode>> LoadAreaTreeNodeByUserId(Guid userId)
        {
            List<TreeNode> treeNodelList = iNJTerminalAppService.LoadAreaTreeNodeByUserId(userId);
            return DtoResultHelper<List<TreeNode>>.RetDtoResult((int)HttpStatusCode.OK, "成功", true, treeNodelList);
        }

        /// <summary>
        ///通过区域Id展开树下层节点 
        /// </summary>
        /// <param name="code">区域Id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/api/NJTerminal/GetAreaTreeNode")]
        public DtoResult<List<TreeNode>> GetAreaTreeNode(string code)
        {
            List<TreeNode> treeNodelList = iNJTerminalAppService.GetAreaTreeNode(code);
            return DtoResultHelper<List<TreeNode>>.RetDtoResult((int)HttpStatusCode.OK, "成功", true, treeNodelList);
        }

    }
    /// <summary>
    /// IsTerminalDisabled的参数
    /// </summary>
    public class TerminalEnableModel
    {
        /// <summary>
        /// 终端Id
        /// </summary>
        public string id { get; set; }
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool enabled { get; set; }
    }


  



}

 

posted on 2017-11-30 17:26  口袋里的SKY  阅读(320)  评论(0编辑  收藏  举报