using System; using System.Linq; using System.Web.Mvc; using Central.Control.Domain; using Ant.Service.Common.Enums; using Ant.Service.Common; using System.Collections.Generic; using MES.Production.Service.IService; using System.Collections; using System.Globalization; using ChangFa.Machinery.WebPage.Controllers; using System.Web; using System.Xml; using System.Text; using System.IO; using System.Net; using System.Drawing; using Ant.Service.Utility; using System.Text.RegularExpressions; using Newtonsoft.Json; using MES.Production.Entity; using Ant.ORM; using Ant.Data; using MES.Production.Entity.Entity; using JsonHelper = Ant.Service.Common.JsonHelper; using JsonConverter = Ant.Service.Common.JsonConverter; namespace ChangFa.Machinery.WebPage.Areas.SysManage.Controllers { /// /// 部门管理控制器 /// add 作者: 季健国 QQ:181589805 by 2016-05-25 /// public class DepartmentController : BaseController { #region 声明容器 /// /// 部门 /// IDepartmentManage DepartmentManage { get; set; } /// /// 用户部门 /// IUserDepartmentManage UserDepartmentManage { get; set; } /// /// 岗位人员 /// IPostUserManage PostUserManage { get; set; } /// /// 岗位部门 /// IPostDepartmentManage PostDepartmentManage { get; set; } #endregion /// /// 加载导航页 /// /// [UserAuthorizeAttribute(ModuleAlias = "Department", OperaAction = "View")] public ActionResult Home() { return View(); } /// /// 加载主页 /// [UserAuthorizeAttribute(ModuleAlias = "Department", OperaAction = "View")] public ActionResult Index() { try { #region 处理查询参数 string dptId = Request.QueryString["dptid"]; #endregion #region 加载列表 //加载部门信息 var result = this.DepartmentManage.Get(p => p.ID == dptId) ?? new SYS_DISTRIBUTORS(); if (!string.IsNullOrEmpty(dptId)) { //加载岗位 var postlist = this.PostDepartmentManage.GetPostIDByDptId(dptId); ViewData["postInfo"] = postlist; //加载部门岗位关系ID var postIdStr = postlist.Aggregate(string.Empty, (current, t) => current + t.ID + ",").TrimEnd(','); //读取相关用户,构造用户,增加岗位ID列 var userList = this.PostUserManage.LoadAll(p => postIdStr.Contains(p.SYS_POST_DEPARTMENT.FK_POST_ID) && p.SYS_POST_DEPARTMENT.FK_DEPARTMENT_ID == dptId).Select(c => new { POSTID = c.SYS_POST_DEPARTMENT.FK_POST_ID, c.SYS_USER.NAME }).GroupBy(c => c).Select(d => new { POSTID = d.Key.POSTID, NAME = d.Key.NAME }).ToList(); ViewData["userInfo"] = JsonConverter.JsonClass(userList); } #endregion return View(result); } catch (Exception e) { WriteLog(enumOperator.Select, "经销商管理加载主页:", e); throw e.InnerException; } } /// /// 加载详情页 /// [HttpGet] [UserAuthorizeAttribute(ModuleAlias = "Department", OperaAction = "Detail")] public ActionResult Detail(string id) { try { string filePathName = string.Empty; DistributorUser distributorUser = new DistributorUser(); SYS_DISTRIBUTORS entity = new SYS_DISTRIBUTORS(); int uid = 0; if (CurrentUser.USERTYPE == 2) { uid = CurrentUser.Id; } ViewBag.moduleparent = this.DepartmentManage.GetDepartmentByDetailNew(uid); //添加子部门 string parentId = Request.QueryString["parentId"]; if (!string.IsNullOrEmpty(parentId)) { //entity.PARENTID = parentId; distributorUser.distributorInfo.PARENTID = parentId; return View(distributorUser); } if (!string.IsNullOrEmpty(id)) { entity = this.DepartmentManage.Get(p => p.ID == id); distributorUser.distributorInfo = entity; using (AntORM orm = new AntORM()) { orm.db = DataAccessFactory.CreateDataConnection("CyclingItem"); RequestModel res = new RequestModel { newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "获取公告信息" } }; var reslut = orm.Queryable().Where(p => p.distributorId == id).ToList(); if (reslut.IsSuccess) { string strlist = ""; foreach (EntYW_UserDistributor mod in reslut.ResultModel) { int userid = mod.userId.ToInt32(); var userreslut = orm.Queryable().Where(p => p.ID == userid).FirstOrDefault(res); if (userreslut.IsSuccess) { En_SYS_USER usermod = userreslut.ResultModel; strlist += usermod.ID + "|" + usermod.NAME; } } ViewData["userid"] = strlist; } var usereslut = orm.Queryable().Where(p => p.DPTID == entity.ID).FirstOrDefault(res); if (usereslut.IsSuccess) { distributorUser.userInfo = usereslut.ResultModel; } } } else { distributorUser.distributorInfo = new SYS_DISTRIBUTORS(); distributorUser.distributorInfo.PARENTID = "32f7a4bd-84de-4587-be29-734d65ad6f70"; distributorUser.userInfo = new En_SYS_USER() { ISCANLOGIN = false }; } return View(distributorUser); } catch (Exception e) { WriteLog(enumOperator.Select, "经销商管理加载详情页:", e); throw e.InnerException; } } /// /// 保存部门 /// [ValidateInput(false)] [UserAuthorizeAttribute(ModuleAlias = "Department", OperaAction = "Add,Edit")] public ActionResult Save(DistributorUser entity) { bool isEdit = false; bool bz = true; var fileid = Request.Form["hidfileid"]; var fileurl = Request.Form["hidfilename"]; var paretid = Request.Form["PARENTID"]; int userid = 0; var citystr = Request.Form["hkprov"] + "," + Request.Form["hkcity"] + "," + Request.Form["hkcountry"]; var json = new JsonHelper() { Msg = "保存成功", Status = "n" }; try { var _entity = new SYS_DISTRIBUTORS(); var _userenty = new En_SYS_USER(); if (entity.distributorInfo != null) { if (!string.IsNullOrEmpty(entity.distributorInfo.ID)) { EntYW_UserDistributor yW_User = new EntYW_UserDistributor(); using (AntORM orm = new AntORM()) { orm.db = DataAccessFactory.CreateDataConnection("CyclingItem"); RequestModel res = new RequestModel { newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "获取公告信息" } }; var disreult = orm.DeleteByLambda(p => p.distributorId == entity.distributorInfo.ID, res); foreach (string str in Request.Form["hidsendUserid"].Split(',')) { if (!str.IsEmpty()) { EntYW_UserDistributor entmod = new EntYW_UserDistributor(); entmod.userId = str.ToInt32(); entmod.distributorId = entity.distributorInfo.ID; entmod.ID = Guid.NewGuid(); var reslutuser = orm.Save(entmod, res); } } } #region 修改 _entity = this.DepartmentManage.Get(p => p.ID == entity.distributorInfo.ID); entity.distributorInfo.CREATEDATE = _entity.CREATEDATE; entity.distributorInfo.CREATEPERID = _entity.CREATEPERID; entity.distributorInfo.PARENTID = paretid; entity.distributorInfo.UPDATEDATE = DateTime.Now; entity.distributorInfo.UPDATEUSER = this.CurrentUser.Name; entity.distributorInfo.Address = Request.Form["distributorInfo.Address"]; entity.distributorInfo.FenceRadius = Request.Form["example_length"].ToInt32(); entity.distributorInfo.LICENSEURL = fileurl; entity.distributorInfo.LICENSEVALUE = fileid; entity.distributorInfo.ProvinceCity = citystr; if (entity.distributorInfo.PARENTID != _entity.PARENTID) { entity.distributorInfo.CODE = this.DepartmentManage.CreateCode(entity.distributorInfo.PARENTID); } else { entity.distributorInfo.CODE = _entity.CODE; } //获取父级记录 if (string.IsNullOrEmpty(paretid)) { //业务等级 entity.distributorInfo.BUSINESSLEVEL = 1; entity.distributorInfo.PARENTCODE = null; } else { var parententity = this.DepartmentManage.Get(p => p.ID == _entity.PARENTID); entity.distributorInfo.BUSINESSLEVEL = parententity.BUSINESSLEVEL + 1; entity.distributorInfo.PARENTCODE = parententity.CODE; entity.distributorInfo.ParentName = parententity.NAME; } #endregion _entity = entity.distributorInfo; _userenty = entity.userInfo; _userenty.ACCOUNT = _userenty.PHONE; _userenty.USERTYPE = 2; isEdit = true; using (AntORM orm = new AntORM()) { orm.db = DataAccessFactory.CreateDataConnection("CyclingItem"); RequestModel res = new RequestModel { newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "获取公告信息" } }; var resuser = orm.UpdateById(_userenty, res); } } else { #region 添加 _entity = entity.distributorInfo; _entity.ID = Guid.NewGuid().ToString(); _entity.CREATEDATE = DateTime.Now; _entity.CREATEPERID = this.CurrentUser.Name; _entity.PARENTID = paretid; _entity.UPDATEDATE = DateTime.Now; _entity.UPDATEUSER = this.CurrentUser.Name; _entity.Address = entity.distributorInfo.Address; _entity.FenceRadius = Request.Form["example_length"].ToInt32(); _entity.LICENSEURL = fileurl; _entity.LICENSEVALUE = fileid; _entity.ProvinceCity = citystr; _entity.Province = Request.Form["hkprov"].ToInt32(); _entity.City = Request.Form["hkcity"].ToInt32(); _entity.Area = Request.Form["hkcountry"].ToInt32(); _userenty = entity.userInfo; _userenty.DPTID = _entity.ID; var pwd = PasswordUtils.MD5_Encrypt("111111", 32); _userenty.USERTYPE = 2; _userenty.ACCOUNT = _userenty.PHONE; _userenty.PASSWORD = pwd; _userenty.CREATEDATE = DateTime.Now; _userenty.CREATEPER = this.CurrentUser.Name; _userenty.UPDATEDATE = DateTime.Now; _userenty.UPDATEUSER = this.CurrentUser.Name; using (AntORM orm = new AntORM()) { orm.db = DataAccessFactory.CreateDataConnection("CyclingItem"); RequestModel res = new RequestModel { newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "获取公告信息" } }; var resuser = orm.SaveHaveNull(_userenty, res); if (resuser.IsSuccess) { userid = resuser.RecordNum; _userenty.ID = userid; } } //根据上级部门的ID确定当前部门的CODE _entity.CODE = this.DepartmentManage.CreateCode(_entity.PARENTID); //获取父级记录 if (string.IsNullOrEmpty(_entity.PARENTID)) { //业务等级 entity.distributorInfo.BUSINESSLEVEL = 1; entity.distributorInfo.PARENTCODE = null; } else { var parententity = this.DepartmentManage.Get(p => p.ID == _entity.PARENTID); entity.distributorInfo.BUSINESSLEVEL = parententity.BUSINESSLEVEL + 1; entity.distributorInfo.PARENTCODE = parententity.CODE; entity.distributorInfo.ParentName = parententity.NAME; } #endregion EntYW_UserDistributor yW_User = new EntYW_UserDistributor(); using (AntORM orm = new AntORM()) { orm.db = DataAccessFactory.CreateDataConnection("CyclingItem"); RequestModel res = new RequestModel { newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "获取公告信息" } }; foreach (string str in Request.Form["hidsendUserid"].Split(',')) { if (!str.IsEmpty()) { int uid = str.ToInt32(); var num = orm.Queryable().Where(p => p.distributorId == _entity.ID && p.userId == uid).Count(); if (num > 0) { bz = false; } } } if (bz) { foreach (string str in Request.Form["hidsendUserid"].Split(',')) { EntYW_UserDistributor entmod = new EntYW_UserDistributor(); entmod.userId = str.ToInt32(); entmod.distributorId = _entity.ID; entmod.ID = Guid.NewGuid(); var reslutuser = orm.Save(entmod, res); } } } EntSYS_USER_ROLE roleMod = new EntSYS_USER_ROLE(); using (AntORM orm = new AntORM()) { orm.db = DataAccessFactory.CreateDataConnection("CyclingItem"); RequestModel res = new RequestModel { newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "获取公告信息" } }; roleMod.FK_ROLEID = 3; roleMod.FK_USERID = _userenty.ID.ToInt32(); orm.Save(roleMod, res); } } //先取消电子围栏 var addressmod = AddressToGPS(entity.distributorInfo.Address); if (addressmod.Geocodes.Count > 0) { foreach (Geocode mod in addressmod.Geocodes) { string lnglatstr = mod.Location; _entity.Theodolite = lnglatstr; } } #region 老版创建电子围栏 //var addressmod = AddressToGPS(entity.distributorInfo.Address); //if (addressmod.Geocodes.Count > 0) //{ // foreach (Geocode mod in addressmod.Geocodes) // { // string lnglatstr = mod.Location; // _entity.Theodolite = lnglatstr; // if (lnglatstr.IndexOf(',') >= 0) // { // string lng = lnglatstr.Split(',')[0]; // string lat = lnglatstr.Split(',')[1]; // if (entity.distributorInfo.FenceID.IsEmpty()) // { // var reslutFences = ToolGPSamap.CreaterGeofence(lng.ToDou(), lat.ToDou(), entity.distributorInfo.FenceRadius.ToDou(), entity.distributorInfo.NAME); // if (!reslutFences.data.gid.IsEmpty()) // { // entity.distributorInfo.FenceID = reslutFences.data.gid; // _userenty = entity.userInfo; // _userenty.DPTID = _entity.ID; // var pwd = PasswordUtils.MD5_Encrypt("111111", 32); // _userenty.USERTYPE = 2; // _userenty.PASSWORD = pwd; // _userenty.CREATEDATE = DateTime.Now; // _userenty.CREATEPER = this.CurrentUser.Name; // _userenty.UPDATEDATE = DateTime.Now; // _userenty.UPDATEUSER = this.CurrentUser.Name; // using (AntORM orm = new AntORM()) // { // orm.db = DataAccessFactory.CreateDataConnection("CyclingItem"); // RequestModel res = new RequestModel // { // newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "获取公告信息" } // }; // var resuser = orm.Save(_userenty, res); // } // } // else // { // json.Status = "n"; // json.Msg = reslutFences.data.message; // return Json(json); // } // } // else // { // RequestQueryFence request = new RequestQueryFence(); // request.gid = entity.distributorInfo.FenceID; // var FenceReslut = ToolGPSamap.QueryGeoFence(request); // var list = FenceReslut.Data.RsList; // foreach (RsList mm in list) // { // var fencereslut = ToolGPSamap.UpdateGeofence(lng.ToDou(), lat.ToDou(), entity.distributorInfo.FenceRadius.ToDou(), entity.distributorInfo.NAME, mm.Gid); // } // } // } // } //} //else //{ // string lnglatstr = _entity.Theodolite; // if (lnglatstr.IndexOf(',') >= 0) // { // string lng = lnglatstr.Split(',')[0]; // string lat = lnglatstr.Split(',')[1]; // if (entity.distributorInfo.FenceID.IsEmpty()) // { // var reslutFences = ToolGPSamap.CreaterGeofence(lng.ToDou(), lat.ToDou(), entity.distributorInfo.FenceRadius.ToDou(), entity.distributorInfo.NAME); // if (!reslutFences.data.gid.IsEmpty()) // { // entity.distributorInfo.FenceID = reslutFences.data.gid; // _userenty = entity.userInfo; // _userenty.DPTID = _entity.ID; // var pwd = PasswordUtils.MD5_Encrypt("111111", 32); // _userenty.USERTYPE = 2; // _userenty.PASSWORD = pwd; // _userenty.CREATEDATE = DateTime.Now; // _userenty.CREATEPER = this.CurrentUser.Name; // _userenty.UPDATEDATE = DateTime.Now; // _userenty.UPDATEUSER = this.CurrentUser.Name; // using (AntORM orm = new AntORM()) // { // orm.db = DataAccessFactory.CreateDataConnection("CyclingItem"); // RequestModel res = new RequestModel // { // newSt = new SqlNote() { Author = "季健国", NewSt = new System.Diagnostics.StackTrace(true), SqlDesc = "获取公告信息" } // }; // var resuser = orm.Save(_userenty, res); // } // } // } // else // { // RequestQueryFence request = new RequestQueryFence(); // request.gid = entity.distributorInfo.FenceID; // var FenceReslut = ToolGPSamap.QueryGeoFence(request); // var list = FenceReslut.Data.RsList; // foreach (RsList mm in list) // { // var fencereslut = ToolGPSamap.UpdateGeofence(lng.ToDou(), lat.ToDou(), entity.distributorInfo.FenceRadius.ToDou(), entity.distributorInfo.NAME, mm.Gid); // } // } // } //} #endregion //判断同一个部门下,是否重名 var predicate = PredicateBuilder.True(); predicate = predicate.And(p => p.PARENTID == _entity.PARENTID); predicate = predicate.And(p => p.NAME == _entity.NAME); predicate = predicate.And(p => p.ID != _entity.ID); if (!this.DepartmentManage.IsExist(predicate)) { if (this.DepartmentManage.SaveOrUpdate(_entity, isEdit)) { json.Status = "y"; try { //string imei = "356802032734930"; string imei = "333333333333333"; string discode = Ant.SuperSocket.Common.DataHelper.StringToHex(_entity.CODE); var str = Ant.SuperSocket.Common.DataHelper.sendCarData(Convert.ToInt64(imei), "9922" + discode); var body = Ant.SuperSocket.Common.DataHelper.HexToByte(str); SocketClient client = new SocketClient(); string ip = System.Web.Configuration.WebConfigurationManager.AppSettings["ip"].ToString(); // string ip = ""; int port = System.Web.Configuration.WebConfigurationManager.AppSettings["port"].ToInt32(); client.Connect(ip, port); var flag = client.SendData(body); client.Disconnect(); } catch (Exception ex) { } } else { json.Msg = "保存失败"; } } else { json.Msg = "经销商" + entity.distributorInfo.NAME + "已存在,不能重复添加"; } } else { json.Msg = "未找到需要保存的经销商信息"; } if (isEdit) { WriteLog(enumOperator.Edit, "修改经销商信息,结果:" + json.Msg, enumLog4net.INFO); } else { WriteLog(enumOperator.Add, "添加经销商信息,结果:" + json.Msg, enumLog4net.INFO); } } catch (Exception e) { json.Msg = "保存经销商信息发生内部错误!"; WriteLog(enumOperator.None, "保存经销商信息:", e); } return Json(json); } /// /// 将地址转GPS /// /// /// private AddressGPS AddressToGPS(string address) { WebClient server = new WebClient(); string url = String.Format("http://restapi.amap.com/v3/geocode/geo?key={0}&address={1}&city={2}", "fa36ec6323075f37020083ceffe8eb24", address, ""); var replyBuffer = server.DownloadData(url); var reply = System.Text.Encoding.UTF8.GetString(replyBuffer); var mod = JsonConvert.DeserializeObject(reply); return mod; } /// /// 删除部门 /// [UserAuthorizeAttribute(ModuleAlias = "Department", OperaAction = "Remove")] public ActionResult Delete(string idList) { JsonHelper json = new JsonHelper() { Msg = "删除经销商成功", ReUrl = "/Department/Index", Status = "n" }; try { if (!string.IsNullOrEmpty(idList)) { idList = idList.TrimEnd(','); //判断是否有下属部门 if (!this.DepartmentManage.DepartmentIsExists(idList)) { //判断是否有用户归属该部门 if (!this.UserDepartmentManage.IsExist(p => idList.Contains(p.DEPARTMENT_ID))) { //判断该部门是否有岗位 if (!this.PostDepartmentManage.IsExist(p => idList.Contains(p.FK_DEPARTMENT_ID))) { var idList1 = idList.Split(',').ToList(); this.DepartmentManage.Delete(p => idList.Contains(p.ID)); json.Status = "y"; } else { json.Msg = "该经销商有岗位信息不能删除,请先取消岗位分配"; } } else { json.Msg = "该经销商存在用户不能删除"; } } else { json.Msg = "该经销商有下属部门不能删除"; } } else { json.Msg = "未找到要删除的部门记录"; } WriteLog(enumOperator.Remove, "删除部门:" + json.Msg, enumLog4net.WARN); } catch (Exception e) { json.Msg = "删除经销商发生内部错误!"; WriteLog(enumOperator.Remove, "删除部门:", e); } return Json(json); } #region 帮助方法及其他控制器调用 /// /// 获取部门导航树 /// public string GetTree() { string type = Request.Form["type"]; JsonHelper json = new JsonHelper() { Msg = "Success", Status = "y" }; try { var query = this.DepartmentManage.LoadAll(null).OrderBy(p => p.SHOWORDER).ToList(); var result = query.Select(m => new { id = m.ID, pId = m.PARENTID, name = m.NAME, open = true, target = "DeployBase", url = GetType(type) + "?dptid=" + m.ID.ToString(CultureInfo.InvariantCulture) }).ToList(); json.Data = result; } catch (Exception e) { json.Status = "Error"; json.Msg = "获取经销商导航树发生内部错误!"; WriteLog(enumOperator.Select, "经销商管理,获取经销商导航树:", e); } return JsonConverter.Serialize(json, true); } private string GetType(string type) { if (type == "0") { return "/Sys/User/Index"; } else { return "/Sys/Department/Index"; } } /// /// 选择部门视图 /// [UserAuthorizeAttribute(ModuleAlias = "Department", OperaAction = "Select")] public ActionResult GetSelectDpt() { return View(); } /// /// 获取部门导航树,带复选框 /// public ActionResult GetSelectTree() { string olddptlist = Request.Form["dptlist"]; JsonHelper json = new JsonHelper() { Msg = "Success", Status = "y" }; try { //获取部门列表 var dptlist = this.DepartmentManage.LoadAll(null).OrderBy(p => p.SHOWORDER).ToList(); if (dptlist != null && dptlist.Count > 0) { var result = new List(); result.AddRange(dptlist.Select(p => new { id = p.ID, name = p.NAME, pId = p.PARENTID, open = true, checkeds = olddptlist.Split(',').Any(c => c.Equals(p.ID)) })); json.Data = JsonConverter.Serialize(result).Replace("checkeds", "checked"); } } catch (Exception e) { json.Status = "n"; json.Msg = "获取经销商导航树发生内部错误!"; WriteLog(enumOperator.Select, "获取经销商导航树(带复选框):", e); } return Json(json); } #endregion } }