FIC_Solar/SolarPower/Controllers/MyBaseController.cs
Kai 716c8d222b 1. 單線圖修改多張上傳
2. 個人專屬logo
2021-09-11 10:50:59 +08:00

292 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using SolarPower.Models.User;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Dapper;
using SolarPower.Models;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using SolarPower.Repository.Interface;
using System.IO;
using System.Text;
using SolarPower.Models.OperatorLogModel;
using Newtonsoft.Json;
using SolarPower.Models.Company;
using SolarPower.Models.Role;
using Microsoft.AspNetCore.Routing;
using SolarPower.Services.Implement;
namespace SolarPower.Controllers
{
public class MyBaseController<T> : Controller where T : MyBaseController<T>
{
private ILogger<T> _logger;
protected ILogger<T> Logger => _logger ?? (_logger = HttpContext?.RequestServices.GetService<ILogger<T>>());
private IUserRepository userRepository => HttpContext?.RequestServices.GetService<IUserRepository>();
private ICompanyRepository companyRepository => HttpContext?.RequestServices.GetService<ICompanyRepository>();
private IRoleRepository roleRepository => HttpContext?.RequestServices.GetService<IRoleRepository>();
private IPowerStationRepository powerStationRepository => HttpContext?.RequestServices.GetService<IPowerStationRepository>();
private IOperatorLogRepository operatorLogRepository => HttpContext?.RequestServices.GetService<IOperatorLogRepository>();
protected MyUser myUser = null;
public string controllerName;
public string actionName;
public string baseURL => HttpContext?.Request.Scheme + "://" + HttpContext?.Request.Host + "/";
public ErrorCode errorCode = new ErrorCode();
public MyPowerStationService myPowerStationService;
public MyBaseController()
{
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//base.OnActionExecuting(filterContext);
this.myPowerStationService = new MyPowerStationService(powerStationRepository);
EDFunction edFunction = new EDFunction();
var myAccount = edFunction.AESDecrypt(HttpContext.Session.GetString("MyAccount")); //取得登入後該位使用者的Account
controllerName = ControllerContext.RouteData.Values["controller"].ToString(); //controller名稱
actionName = ControllerContext.RouteData.Values["action"].ToString(); //action名稱
bool isAjaxCall = filterContext.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
if (string.IsNullOrEmpty(myAccount))
{
if (isAjaxCall)
{
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 499;
return;
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{"controller", "Login"},
{"action", "Index"}
});
return;
}
}
//取得當前登入使用者資訊
myUser = userRepository.GetMyUserInfoByAccount(myAccount);
myUser.Company = companyRepository.GetMyCompanyInfoById(myUser.CompanyId);
//判斷該使用者是否有個人專屬Logo
if (!string.IsNullOrEmpty(myUser.Logo))
{
var fullFilePath = Directory.GetCurrentDirectory() + "/wwwroot/" + Path.Combine("upload", "company_logo", myUser.Logo);
if (System.IO.File.Exists(fullFilePath))
{
myUser.Logo = "/" + Path.Combine("upload", "company_logo", myUser.Logo);
}
}
else
{
//判斷該檔案是否存在
if (!string.IsNullOrEmpty(myUser.Company.Logo))
{
var fullFilePath = Directory.GetCurrentDirectory() + "/wwwroot/" + Path.Combine("upload", "company_logo", myUser.Company.Logo);
if (!System.IO.File.Exists(fullFilePath))
{
myUser.Company.Logo = "/img/logo.png";
}
else
{
myUser.Company.Logo = "/" + Path.Combine("upload", "company_logo", myUser.Company.Logo);
}
}
else
{
myUser.Company.Logo = "/img/logo.png";
}
}
myUser.Role = roleRepository.GetMyRoleInfoById(myUser.RoleId);
List<string> auth_arr = new List<string>();
foreach (var auth in myUser.Role.Auths)
{
var per_auch_arr = auth.Split(',');
foreach (var x in per_auch_arr)
{
if (x.Contains("PowerStation"))
{
auth_arr.Add("PowerStation");
}
if (x.Contains("StationOverview") && !auth_arr.Contains("StationOverview"))
{
auth_arr.Add("StationOverview");
}
auth_arr.Add(x);
}
}
//只排除畫面的情況
var judgeActionName = new List<string>() { "Index", "Info", "Record", "Edit" };
if (myUser.Role.Layer != (int)RoleLayerEnum.PlatformAdmin && !auth_arr.Contains(controllerName) && judgeActionName.Contains(actionName))
{
//排除條件
if (auth_arr.Contains("StationOverview") && !auth_arr.Contains("PowerStation"))
{
//只有電站總覽 且未包含 電站管理
}
else if (controllerName == "User" && (actionName == "ChangePassword" || actionName == "GetPersonalInfo" || actionName == "SavePersonalInfo"))
{
//查詢個人 資訊 及密碼
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{"controller", "Login"},
{"action", "SignOut"}
});
return;
}
}
//取得當前使用者可以查看的電站
MyPowerStationService myPowerStationService = new MyPowerStationService(powerStationRepository);
var myPowerStations = myPowerStationService.GetMyPowerStationsGroupByCity(myUser);
//var myPowerStationSummaries = powerStationRepository.GetMyPowerStationSummary(myUser);
myUser.myPowerStationGroupByCities = myPowerStations;
ViewBag.myPowerStationGroupByCities = myPowerStations;
if (controllerName == "PowerStation" && actionName == "Edit")
{
//電站資訊的各電站
string stationId_param = filterContext.HttpContext.Request.Query["stationId"];
int stationId = stationId_param == "new" ? 0 : int.Parse(stationId_param);
if (stationId > 0)
{
var hasSubTagNum = false;
int i = 0;
foreach (var myPowerStation in myPowerStations)
{
if (hasSubTagNum)
{
break;
}
int j = 0;
foreach (var station in myPowerStation.MyPowerStations)
{
if (station.Id == stationId)
{
ViewData["SubNum"] = i;
ViewData["TagNum"] = j;
hasSubTagNum = true;
break;
}
j++;
}
i++;
}
}
}
ViewBag.auths = auth_arr;
ViewBag.myUser = myUser;
#region
var content = JsonConvert.SerializeObject(filterContext.ActionArguments);
OperatorLog operatorLog = new OperatorLog()
{
ControllerName = controllerName,
ActionName = actionName,
Parameter = content.CompareTo("{}") == 0 ? null : content,
CreatedBy = myUser.Id,
};
List<string> removeParam = new List<string>() { "ChangePassword" }; //移除不紀錄參數的actionName
if (removeParam.Any(x => actionName.Contains(x)))
{
operatorLog.Parameter = "{}";
}
List<string> properties = new List<string>()
{
"ControllerName",
"ActionName",
"Parameter",
"CreatedBy",
};
operatorLogRepository.Add(operatorLog, properties);
#endregion
}
/// <summary>
/// 判斷是否維平台的管理員或平台使用者
/// </summary>
/// <param name="roleLayer"></param>
/// <returns></returns>
public bool IsPlatformLayer(byte roleLayer)
{
if (roleLayer == (int)RoleLayerEnum.PlatformAdmin || roleLayer == (int)RoleLayerEnum.PlatformUser)
{
return true;
}
return false;
}
/// <summary>
/// 取得最新的流水號
/// </summary>
/// <param name="current">當前的</param>
/// <param name="pad"></param>
/// <param name="direction">0: PadLeft1: PadRight</param>
/// <returns></returns>
public string GetLastSerialNumber(string current = "", int pad = 4, byte direction = 0)
{
var tempSerialNumber = 0;
if (!string.IsNullOrEmpty(current))
{
tempSerialNumber = Convert.ToInt32(current) + 1;
}
else
{
tempSerialNumber = 1;
}
if (direction == 0)
{
return tempSerialNumber.ToString().Trim().PadLeft(pad, '0');
}
else
{
return tempSerialNumber.ToString().Trim().PadRight(pad, '0');
}
}
}
}