using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SolarPower.Models; using SolarPower.Models.Company; using SolarPower.Models.PowerStation; using SolarPower.Models.User; using SolarPower.Repository.Interface; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Xml; namespace SolarPower.Controllers { public class PowerStationController : MyBaseController { private readonly IUserRepository userRepository; private readonly ICompanyRepository companyRepository; private readonly IPowerStationRepository powerStationRepository; private string boeFilePath = "/upload/power_station/boe_file/"; private string stationImageFilePath = "/upload/power_station/"; private string powerSationSaveAsPath = ""; public PowerStationController( IUserRepository userRepository, ICompanyRepository companyRepository, IPowerStationRepository powerStationRepository) : base() { this.userRepository = userRepository; this.companyRepository = companyRepository; this.powerStationRepository = powerStationRepository; powerSationSaveAsPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "power_station"); } public IActionResult Index() { return View(); } public IActionResult Edit() { return View("~/Views/PowerStation/PowerStationEdit.cshtml"); } /// /// 取得下拉式公司選單,須為Deleted: 0 /// /// [HttpGet] public async Task>> GetUserSelectOptionListAsync(int powerStationId) { ApiResult> apiResult = new ApiResult>(); try { var companyId = 0; var powerStation = await powerStationRepository.GetOneAsync(powerStationId); if (powerStation == null) { companyId = myUser.CompanyId; } else { companyId = powerStation.CompanyId; } var margeUserSelectItemLists = new List(); if (companyId == 1) { var userSelectItemLists = await userRepository.GetUserSelectOptionListAsync(companyId); foreach (var userSelectItem in userSelectItemLists) { userSelectItem.CanBeSelected = 1; } margeUserSelectItemLists.AddRange(userSelectItemLists); } else { var platformUserSelectItemLists = await userRepository.GetUserSelectOptionListAsync(1); if (IsPlatformLayer(myUser.Role.Layer)) { foreach (var userSelectItem in platformUserSelectItemLists) { userSelectItem.CanBeSelected = 1; } } else { foreach (var userSelectItem in platformUserSelectItemLists) { userSelectItem.CanBeSelected = 0; } } margeUserSelectItemLists.AddRange(platformUserSelectItemLists); var userSelectItemLists = await userRepository.GetUserSelectOptionListAsync(companyId); foreach (var userSelectItem in userSelectItemLists) { userSelectItem.CanBeSelected = 1; } margeUserSelectItemLists.AddRange(userSelectItemLists); } apiResult.Code = "0000"; apiResult.Data = margeUserSelectItemLists; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } [HttpGet] public async Task>> GetCompanySelectOptionListAsync() { ApiResult> apiResult = new ApiResult>(); try { var companySelectItemLists = new List(); if (!IsPlatformLayer(myUser.Role.Layer)) { companySelectItemLists = await powerStationRepository.GetCompanySelectOptionListAsync(myUser.CompanyId); } else { companySelectItemLists = await powerStationRepository.GetCompanySelectOptionListAsync(0); } apiResult.Code = "0000"; apiResult.Data = companySelectItemLists; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } /// /// 取裝置類型下拉選單 /// /// public async Task>> GetDeviceTypeSelectOptionList() { ApiResult> apiResult = new ApiResult>(); try { var userSelectItemLists = await powerStationRepository.DeviceType(); apiResult.Code = "0000"; apiResult.Data = userSelectItemLists; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 取得縣市選單 /// /// [HttpGet] public async Task>> GetCitySelectOptionList() { ApiResult> apiResult = new ApiResult>(); try { var citySelectItemLists = await powerStationRepository.GetCitySelectOptionListAsync(); apiResult.Code = "0000"; apiResult.Data = citySelectItemLists; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } /// /// 取得地區選單 /// /// [HttpPost] public async Task>> GetAreaSelectOptionList(int cityId) { ApiResult> apiResult = new ApiResult>(); try { var areaSelectItemLists = await powerStationRepository.GetAreaSelectOptionListAsync(cityId); apiResult.Code = "0000"; apiResult.Data = areaSelectItemLists; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } [HttpPost] public async Task>> GetOperationPersonnelSelectOptionList(int powerStationId) { ApiResult> apiResult = new ApiResult>(); try { var personnelSelectItemLists = await powerStationRepository.GetOperationPersonnelSelectOptionListAsync(powerStationId); apiResult.Code = "0000"; apiResult.Data = personnelSelectItemLists; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } [HttpPost] public async Task>> GetFirmSelectOptionList(int powerStationId) { ApiResult> apiResult = new ApiResult>(); try { var powerStation = await powerStationRepository.GetOneAsync(powerStationId); var firmSelectItemLists = await powerStationRepository.GetFimlSelectOptionListAsync(powerStationId, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Data = firmSelectItemLists; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } /// /// 取得單一電站基本資料 /// /// /// [HttpPost] public async Task> GetOnePowerStation(int id) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(id); if (powerStation == null) { apiResult.Code = "9992"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } else if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } //替能源局換檔案路徑 if (!string.IsNullOrEmpty(powerStation.BoEFile)) { powerStation.BoEFile = boeFilePath + powerStation.BoEFile; } apiResult.Code = "0000"; apiResult.Data = powerStation; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + "Id=" + id); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } /// /// 新增 / 修改 電站基本資料 /// /// /// public async Task> SavePowerStationInfo(PostPowerStationInfo post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.Id); //取得該公司DB Name var company = await companyRepository.GetOneAsync(post.CompanyId); if (powerStation == null) { if (post.Id != 0) { apiResult.Code = "9992"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } #region 新增電站資訊 //取得電站該縣市的Zipcode var zipcode = await powerStationRepository.GetCityAreaZipcodeAsync(post.AreaId); //取得電站該縣市地區最後流水號 var currentSerialNumber = await powerStationRepository.GetLastSerialNumberByCityAreaIdAsync(post.CityId, post.AreaId); var tempSerialNumber = GetLastSerialNumber(currentSerialNumber); var codeFormat = "{0}{1}{2}"; powerStation = new PowerStation() { CompanyId = post.CompanyId, CityId = post.CityId, AreaId = post.AreaId, Address = post.Address, Name = post.Name, Code = String.Format(codeFormat, zipcode.City, zipcode.Area, tempSerialNumber), SerialNumber = tempSerialNumber, IsEscrow = post.IsEscrow, EscrowName = post.EscrowName, EstimatedRecoveryTime = post.EstimatedRecoveryTime, GeneratingCapacity = post.GeneratingCapacity, Coordinate = post.Coordinate, InverterBrand = post.InverterBrand, InverterProductModel = post.InverterProductModel, InverterAmount = post.InverterAmount, PhotovoltaicPanelBrand = post.PhotovoltaicPanelBrand, PhotovoltaicPanelProductModel = post.PhotovoltaicPanelProductModel, PhotovoltaicPanelSpecification = post.PhotovoltaicPanelSpecification, PhotovoltaicPanelAmount = post.PhotovoltaicPanelAmount, SiteDB = company.SiteDB, SolarType = post.SolarType, line_token = post.line_token, Estimate_kwh = post.Estimate_kwh, EstimateEfficacy = post.EstimateEfficacy, CreatedBy = myUser.Id }; List properties = new List() { "CompanyId", "CityId", "AreaId", "Address", "Name", "Code", "SerialNumber", "IsEscrow", "EscrowName", "EstimatedRecoveryTime", "GeneratingCapacity", "Coordinate", "InverterBrand", "InverterProductModel", "InverterAmount", "PhotovoltaicPanelBrand", "PhotovoltaicPanelProductModel", "PhotovoltaicPanelSpecification", "PhotovoltaicPanelAmount", "SiteDB", "SolarType", "line_token", "Estimate_kwh", "EstimateEfficacy", "CreatedBy" }; var id = await powerStationRepository.AddOnePowerStationAsync(powerStation, properties, company.SiteDB); #region 新增土地與房屋資訊 var city = await powerStationRepository.GetOneCityByIdAsync(post.CityId); var area = await powerStationRepository.GetOneAreaByIdAsync(post.AreaId); LandBuilding landBuilding = new LandBuilding() { Address = city.Name + area.Name + post.Address, PowerStationId = id, CreatedBy = myUser.Id }; List landBuildingProperties = new List() { "Address", "PowerStationId", "CreatedBy" }; await powerStationRepository.AddOneLandBuildingInfo(landBuilding, landBuildingProperties, company.SiteDB); #endregion #region 新增運維人員 //找出要新增的 if (post.OperationPersonnelIds != null) { List insertOperationPersonnels = new List(); foreach (var op in post.OperationPersonnelIds) { PowerStationOperationPersonnel operationPersonnel = new PowerStationOperationPersonnel(); operationPersonnel.PowerStationId = id; operationPersonnel.UserId = op; operationPersonnel.CreatedBy = myUser.Id; insertOperationPersonnels.Add(operationPersonnel); } List operationPersonnelProperties = new List() { "PowerStationId", "UserId", "CreatedBy", }; await powerStationRepository.AddOperationPersonnelAsync(insertOperationPersonnels, operationPersonnelProperties); } #endregion BackFillSchedule backFillSchedule = new BackFillSchedule() { UID = powerStation.Code, DBName = powerStation.SiteDB, TableName = "s" + powerStation.Code + "01_station" }; properties = new List() { "UID", "DBName", "TableName" }; await powerStationRepository.AddAnyThing(backFillSchedule, properties, "back_fill_schedule"); apiResult.Code = "0000"; apiResult.Msg = "儲存成功"; apiResult.Data = await powerStationRepository.GetOneAsync(id); #endregion } else { if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } #region 修改電站資訊 UpdatePowerStationInfo update = new UpdatePowerStationInfo() { Id = post.Id, CityId = post.CityId, AreaId = post.AreaId, Address = post.Address, Name = post.Name, IsEscrow = post.IsEscrow, EscrowName = post.EscrowName, EstimatedRecoveryTime = post.EstimatedRecoveryTime, GeneratingCapacity = post.GeneratingCapacity, Coordinate = post.Coordinate, InverterBrand = post.InverterBrand, InverterProductModel = post.InverterProductModel, InverterAmount = post.InverterAmount, PhotovoltaicPanelBrand = post.PhotovoltaicPanelBrand, PhotovoltaicPanelProductModel = post.PhotovoltaicPanelProductModel, PhotovoltaicPanelSpecification = post.PhotovoltaicPanelSpecification, PhotovoltaicPanelAmount = post.PhotovoltaicPanelAmount, SolarType = post.SolarType, line_token = post.line_token, Estimate_kwh = post.Estimate_kwh, EstimateEfficacy = post.EstimateEfficacy, UpdatedBy = myUser.Id }; List properties = new List() { "Id", "CityId", "AreaId", "Address", "Name", "IsEscrow", "EscrowName", "EstimatedRecoveryTime", "GeneratingCapacity", "Coordinate", "InverterBrand", "InverterProductModel", "InverterAmount", "PhotovoltaicPanelBrand", "PhotovoltaicPanelProductModel", "PhotovoltaicPanelSpecification", "PhotovoltaicPanelAmount", "SolarType", "line_token", "Estimate_kwh", "EstimateEfficacy", "UpdatedBy", }; await powerStationRepository.UpdatePowerStationInfo(update, properties, powerStation.SiteDB); List origOperationPersonnels = null; //原先的運維人員 origOperationPersonnels = await powerStationRepository.GetOperationPersonnelIdsByPowerStatioinId(powerStation.Id); //判斷新進來的資料是否要歸類到新增 or 刪除 #region 刪除電站運維人員編號 //找出要刪除的 List deleteOperationPersonnelIds = origOperationPersonnels.Where(x => !post.OperationPersonnelIds.Contains(x)).ToList(); List deleteOperationPersonnels = new List(); foreach (var opId in deleteOperationPersonnelIds) { PowerStationOperationPersonnel operationPersonnel = new PowerStationOperationPersonnel(); operationPersonnel.PowerStationId = powerStation.Id; operationPersonnel.UserId = opId; deleteOperationPersonnels.Add(operationPersonnel); } //刪除運維人員 await powerStationRepository.DeleteOperationPersonnel(deleteOperationPersonnels); #endregion #region 新增電站運維人員 //找出要新增的 if (post.OperationPersonnelIds != null) { List insertOperationPersonnelIds = post.OperationPersonnelIds.Where(x => !origOperationPersonnels.Contains(x)).ToList(); List insertOperationPersonnels = new List(); foreach (var op in insertOperationPersonnelIds) { PowerStationOperationPersonnel operationPersonnel = new PowerStationOperationPersonnel(); operationPersonnel.PowerStationId = powerStation.Id; operationPersonnel.UserId = op; operationPersonnel.CreatedBy = myUser.Id; insertOperationPersonnels.Add(operationPersonnel); } List operationPersonnelProperties = new List() { "PowerStationId", "UserId", "CreatedBy", }; await powerStationRepository.AddOperationPersonnelAsync(insertOperationPersonnels, operationPersonnelProperties); } #endregion await StationUnStatus(post.Id); apiResult.Code = "0000"; apiResult.Msg = "儲存成功"; apiResult.Data = await powerStationRepository.GetOneAsync(powerStation.Id); #endregion } } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 新增 / 修改 能源局與台電資料 /// /// /// [HttpPost] public async Task> SaveBoETPCInfo([FromForm] PostBoETPCInfo post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.Id); if (powerStation == null) { if (post.Id != 0) { apiResult.Code = "9992"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } } else { if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } #region 修改能源局與台電 //處理檔案 var boeFileName = ""; if (post.BoEFile != null) { var split = post.BoEFile.FileName.Split("."); boeFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "." + split[split.Length - 1]; FolderFunction folderFunction = new FolderFunction(); var fileSaveAsPath = Path.Combine(powerSationSaveAsPath, "boe_file"); folderFunction.CreateFolder(fileSaveAsPath, 0); var fullPath = Path.Combine(fileSaveAsPath, boeFileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { post.BoEFile.CopyTo(stream); } } UpdateBoETPCInfo update = new UpdateBoETPCInfo() { Id = post.Id, BoEFileName = post.BoEFile != null ? post.BoEFile.FileName : null, //原本檔名 BoEFile = boeFileName, //自訂檔名 BoEDiscountRate = post.BoEDiscountRate, BoEDeviceRegisterNumber = post.BoEDeviceRegisterNumber, BoERegisterPostAt = post.BoERegisterPostAt, BoERentRatio = post.BoERentRatio, TPCContractNumber = post.TPCContractNumber, TPCContractAt = post.TPCContractAt, TPCSellDeadline = post.TPCSellDeadline, ElectricityMeterAt = post.ElectricityMeterAt, PowerRate = post.PowerRate, TPCMeterReading = post.TPCMeterReading, TPCPurchaseElectricityAt = post.TPCPurchaseElectricityAt, TPCSellElectricityAt = post.TPCSellElectricityAt, TPCInvoiceBuyer = post.TPCInvoiceBuyer, GUINumber = post.GUINumber, TPCInvoiceAddress = post.TPCInvoiceAddress, TPCMeterNumber = post.TPCMeterNumber, UpdatedBy = myUser.Id }; List properties = new List() { "Id", "BoEFileName", "BoEFile", "BoEDiscountRate", "BoEDeviceRegisterNumber", "BoERegisterPostAt", "BoERentRatio", "TPCContractNumber", "TPCContractAt", "TPCSellDeadline", "ElectricityMeterAt", "PowerRate", "TPCMeterReading", "TPCPurchaseElectricityAt", "TPCSellElectricityAt", "TPCInvoiceBuyer", "GUINumber", "TPCInvoiceAddress", "TPCMeterNumber", "UpdatedBy", }; await powerStationRepository.UpdateBoETPCInfo(update, properties, powerStation.SiteDB); #endregion } //重新取得資料 powerStation = await powerStationRepository.GetOneAsync(powerStation.Id); //替能源局換檔案路徑 if (!string.IsNullOrEmpty(powerStation.BoEFile)) { powerStation.BoEFile = boeFilePath + powerStation.BoEFile; } apiResult.Code = "0000"; apiResult.Msg = "修改成功"; apiResult.Data = powerStation; } catch (Exception exception) { apiResult.Code = "9999"; string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 新增 / 修改 土地與房屋資料 /// /// /// public async Task> SaveLandBuildingInfo(PostLandBuildingInfo post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; LandBuilding landBuilding = null; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); if (powerStation == null) { if (post.PowerStationId != 0) { apiResult.Code = "9992"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } } else { if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } landBuilding = await powerStationRepository.GetOneLandBuildingInfo(post.Id, powerStation.SiteDB); if (landBuilding == null) { if (post.Id != 0) { apiResult.Code = "9991"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } #region 新增土地房屋資訊 //取得公司在該縣市區域當前電站的流水編碼 landBuilding = new LandBuilding() { PowerStationId = powerStation.Id, Address = post.Address, LeaseNotarizationAt = post.LeaseNotarizationAt, Landowner = post.Landowner, Purpose = post.Purpose, LeaseRate = post.LeaseRate, Coordinate = post.Coordinate, Phone = post.Phone, CreatedBy = myUser.Id }; List properties = new List() { "PowerStationId", "Address", "LeaseNotarizationAt", "Landowner", "Purpose", "LeaseRate", "Coordinate", "Phone", "CreatedBy" }; var id = await powerStationRepository.AddOneLandBuildingInfo(landBuilding, properties, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Msg = "儲存成功"; apiResult.Data = await powerStationRepository.GetOneAsync(powerStation.Id); #endregion } else { #region 修改土地房屋資訊 UpdateLandBuilding update = new UpdateLandBuilding() { Id = post.Id, Address = post.Address, LeaseNotarizationAt = post.LeaseNotarizationAt, Landowner = post.Landowner, Purpose = post.Purpose, LeaseRate = post.LeaseRate, Coordinate = post.Coordinate, Phone = post.Phone, UpdatedBy = myUser.Id }; List properties = new List() { "Id", "Address", "LeaseNotarizationAt", "Landowner", "Purpose", "LeaseRate", "Coordinate", "Phone", "UpdatedBy", }; await powerStationRepository.UpdateLandBuildingInfo(update, properties, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Msg = "修改成功"; apiResult.Data = await powerStationRepository.GetOneAsync(powerStation.Id); #endregion } } } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 新增/修改 運維資料 /// /// /// public async Task> SaveOperation(OperationInfo post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); if (post.Id == 0) { OperationInfo operation = new OperationInfo() { Id = post.Id, Email = post.Email, Name = post.Name, Phone = post.Phone, CreatedBy = myUser.Id, ContactPerson = post.ContactPerson, PowerStationId = post.PowerStationId, Type = post.Type, TaxIDNumber = post.TaxIDNumber, Remark = post.Remark }; List properties = new List() { "Id", "Email", "Name", "Phone", "CreatedBy", "ContactPerson", "PowerStationId", "Type", "TaxIDNumber", "Remark", }; await powerStationRepository.AddOperation(operation, properties, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Msg = "新增成功"; } else { OperationInfo operation = new OperationInfo() { Id = post.Id, Email = post.Email, Name = post.Name, Phone = post.Phone, CreatedBy = myUser.Id, ContactPerson = post.ContactPerson, PowerStationId = post.PowerStationId, Type = post.Type, TaxIDNumber = post.TaxIDNumber, Remark = post.Remark }; List properties = new List() { "Id", "Email", "Name", "Phone", "CreatedBy", "ContactPerson", "PowerStationId", "Type", "TaxIDNumber", "Remark", }; await powerStationRepository.UpdateOperation(operation, properties, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Msg = "儲存成功"; } } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 運維資料DataTable /// /// /// public async Task OperationTable(int stationId) { List operationTable = new List(); ApiResult> apiResult = new ApiResult>(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(stationId); operationTable = await powerStationRepository.OperationTable(stationId, powerStation.SiteDB); foreach (OperationTable a in operationTable) { a.Function = @" "; if (a.Type == 0) { a.TypeName = "施工"; } else if (a.Type == 1) { a.TypeName = "清洗"; } else if (a.Type == 2) { a.TypeName = "運維"; } } apiResult.Code = "0000"; apiResult.Data = operationTable; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "stationId = " + stationId); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } var result = Json(new { data = apiResult }); return result; } /// /// 取得一筆 運維 資料 /// /// /// public async Task> GetOneOperation(PostPowerStationIdAndSelectedId post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); apiResult.Code = "0000"; var operation = await powerStationRepository.OneOperationInfo(post.SelectedId, powerStation.SiteDB); apiResult.Data = operation; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 刪除 運維 資料 /// /// /// public async Task> DeleteOneOperation(PostPowerStationIdAndSelectedId post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); var operation = await powerStationRepository.OneOperationInfo(post.SelectedId, powerStation.SiteDB); if (operation == null) { apiResult.Code = "9996"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } await powerStationRepository.DeleteOneByIdWithCustomDBNameAndTable(operation.Id, powerStation.SiteDB, "operation_firm"); apiResult.Code = "0000"; apiResult.Msg = "刪除成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 新增 / 修改 裝置資料 /// /// /// public async Task> SaveDevice(DeviceInfo Device) { ApiResult apiResult = new ApiResult(); try { var powerStation = await powerStationRepository.GetOneAsync(Device.PowerStationId); var tableName = powerStation.SiteDB + ".device"; if (Device.Id == 0) { var Num = await powerStationRepository.GetCurrentSerialNumber(tableName, "PowerStationId =" + Device.PowerStationId); //string Number = await powerStationRepository.GetFinalSerialNumber(Device.PowerStationId, Device.Type,powerStation.SiteDB); var Newnum = GetLastSerialNumber(Num); var deviceController = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync(Device.ControllerId, powerStation.SiteDB, "controller"); Device DeviceInfo = new Device() { Brand = Device.Brand, ColName = Device.ColName, PowerStationId = Device.PowerStationId, DBName = powerStation.SiteDB, Id = Device.Id, Name = Device.Name, ProductModel = Device.ProductModel, TableName = Device.TableName, Type = Device.Type, UID = deviceController.ControllerId + "R" + Newnum, CreatedBy = myUser.Id, TypeName = Device.TypeName, SerialNumber = Newnum, ControllerId = Device.ControllerId, Status = Device.Status, Enabled = Device.Enabled, InstallDate = Device.InstallDate, BrandNum = Device.BrandNum }; List properties = new List() { "Brand", "ColName", "PowerStationId", "DBName", "Name", "ProductModel", "TableName", "Type", "UID", "CreatedBy", "TypeName", "SerialNumber", "ControllerId", "Status", "Enabled", "InstallDate", "BrandNum" }; if (Device.WarrantyDate != "0001-01-01") { DeviceInfo.WarrantyDate = Device.WarrantyDate; properties.Add("WarrantyDate"); } await powerStationRepository.AddDevice(DeviceInfo, properties, powerStation.SiteDB); BackFillSchedule backFillSchedule = new BackFillSchedule() { ColName = Device.ColName, UID = deviceController.ControllerId + "R" + Newnum, DBName = powerStation.SiteDB, TableName = Device.TableName }; properties = new List() { "ColName", "UID", "DBName", "TableName" }; await powerStationRepository.AddAnyThing(backFillSchedule, properties, "back_fill_schedule"); await powerStationRepository.StationStatus(Device.PowerStationId, 0); await powerStationRepository.StationStatus(Device.PowerStationId, 0,powerStation.SiteDB + "."); apiResult.Code = "0000"; apiResult.Msg = "新增成功"; } else { var deviceController = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync(Device.ControllerId, powerStation.SiteDB, "controller"); Device DeviceInfo = new Device() { Brand = Device.Brand, ColName = Device.ColName, PowerStationId = Device.PowerStationId, DBName = powerStation.SiteDB, Id = Device.Id, Name = Device.Name, ProductModel = Device.ProductModel, TableName = Device.TableName, Type = Device.Type, CreatedBy = myUser.Id, TypeName = Device.TypeName, ControllerId = Device.ControllerId, Status = Device.Status, Enabled = Device.Enabled, InstallDate = Device.InstallDate, BrandNum = Device.BrandNum }; List properties = new List() { "Brand", "ColName", "PowerStationId", "DBName", "Id", "Name", "ProductModel", "TableName", "Type", "CreatedBy", "TypeName", "ControllerId", "Status", "Enabled", "InstallDate", "BrandNum" }; if (Device.WarrantyDate != "0001-01-01") { DeviceInfo.WarrantyDate = Device.WarrantyDate; properties.Add("WarrantyDate"); } await powerStationRepository.UpdateDevice(DeviceInfo, properties, powerStation.SiteDB); await powerStationRepository.StationStatus(Device.PowerStationId, 0); await powerStationRepository.StationStatus(Device.PowerStationId, 0, powerStation.SiteDB + "."); apiResult.Code = "0000"; apiResult.Msg = "儲存成功"; } } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = exception.ToString(); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "Device=" + Device); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 設備DataTable /// /// /// public async Task DeviceTable(int stationId) { List deviceTables = new List(); ApiResult> apiResult = new ApiResult>(); try { PowerStation powerStation = null; powerStation = await powerStationRepository.GetOneAsync(stationId); apiResult.Code = "0000"; deviceTables = await powerStationRepository.DeviceTable(stationId, powerStation.SiteDB); foreach (DeviceTable a in deviceTables) { a.Function = @" "; a.StatusName = a.Status switch { 0 => "未啟用", 1 => "正常", 2 => "異常", _ => "無資料", }; switch (a.Enabled) { case 0: a.EnabledName = "未啟用"; break; case 1: a.EnabledName = "啟用"; break; default: a.EnabledName = "無資料"; break; } } apiResult.Data = deviceTables; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = exception.ToString(); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "stationId=" + stationId); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } var result = Json(new { data = apiResult }); return result; } /// /// 軟刪除單一土地房屋資訊 /// /// /// [HttpPost] public async Task> DeleteLandBuildingInfo(PostPowerStationIdAndSelectedId post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; LandBuilding landBuilding; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); landBuilding = await powerStationRepository.GetOneLandBuildingInfo(post.SelectedId, powerStation.SiteDB); if (landBuilding == null) { apiResult.Code = "9991"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } await powerStationRepository.DeleteOneLandBuildingInfo(landBuilding.Id, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Msg = "刪除成功"; apiResult.Data = await powerStationRepository.GetOneAsync(landBuilding.PowerStationId); } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 取單一設備資料 /// /// /// public async Task> GetOneDevice(PostPowerStationIdAndSelectedId id) { DeviceInfo Device = new DeviceInfo(); ApiResult apiResult = new ApiResult(); try { PowerStation powerStation = null; powerStation = await powerStationRepository.GetOneAsync(id.PowerStationId); apiResult.Code = "0000"; Device = await powerStationRepository.OneDeviceInfo(id.SelectedId, powerStation.SiteDB); apiResult.Data = Device; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = exception.ToString(); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "id=" + id); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 刪除設備 /// /// /// public async Task> DeleteOneDevice(PostPowerStationIdAndSelectedId id) { ApiResult apiResult = new ApiResult(); DeviceInfo Device = new DeviceInfo(); try { PowerStation powerStation = null; powerStation = await powerStationRepository.GetOneAsync(id.PowerStationId); Device = await powerStationRepository.OneDeviceInfo(id.SelectedId, powerStation.SiteDB); if (Device == null) { apiResult.Code = "9988"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } //TODO await powerStationRepository.DeleteOneByIdWithCustomDBNameAndTable(Device.Id, powerStation.SiteDB, "device"); apiResult.Code = "0000"; apiResult.Msg = "刪除成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "Id=" + id); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 新增/修改異常 /// /// /// public async Task> SaveException(ExceptionModal exceptionModal) { ApiResult apiResult = new ApiResult(); try { PowerStation powerStation = null; powerStation = await powerStationRepository.GetOneAsync(exceptionModal.PowerStationId); if (exceptionModal.Id == 0) { ExceptionModal Exception = new ExceptionModal() { Alarm = exceptionModal.Alarm, CreatedBy = myUser.Id, PowerStationId = exceptionModal.PowerStationId, Id = exceptionModal.Id, LowerLimit = exceptionModal.LowerLimit, Type = exceptionModal.Type, UpperLimit = exceptionModal.UpperLimit }; List properties = new List() { "Alarm", "CreatedBy", "PowerStationId", "Id", "Type", "LowerLimit", "UpperLimit" }; if(Exception.LowerLimit == -9999) { Exception.LowerLimit = null; } if (Exception.UpperLimit == -9999) { Exception.UpperLimit = null; } await powerStationRepository.AddException(Exception, properties, powerStation.SiteDB); var calllist = await powerStationRepository.GetApicallList(powerStation.Id, exceptionModal.Type); foreach(var call in calllist ) { if(call.LimitValue == 0) { if(exceptionModal.UpperLimit != -9999) { Fetch_PostWithJSONFormat($"http://{call.UrlSite}/obix/config/Solar/S{powerStation.Code}01/API/{call.UrlApi}/set", exceptionModal.UpperLimit.ToString()); } } else if(call.LimitValue == 1) { if (exceptionModal.LowerLimit != -9999) { Fetch_PostWithJSONFormat($"http://{call.UrlSite}/obix/config/Solar/S{powerStation.Code}01/API/{call.UrlApi}/set", exceptionModal.LowerLimit.ToString()); } } } apiResult.Code = "0000"; apiResult.Msg = "新增成功"; } else { ExceptionModal Exception = new ExceptionModal() { Alarm = exceptionModal.Alarm, CreatedBy = myUser.Id, PowerStationId = exceptionModal.PowerStationId, Id = exceptionModal.Id, LowerLimit = exceptionModal.LowerLimit, Type = exceptionModal.Type, UpperLimit = exceptionModal.UpperLimit }; List properties = new List() { "Alarm", "CreatedBy", "PowerStationId", "Id", "Type", "LowerLimit", "UpperLimit" }; if (Exception.LowerLimit == -9999) { Exception.LowerLimit = null; } if (Exception.UpperLimit == -9999) { Exception.UpperLimit = null; } await powerStationRepository.UpdateException(Exception, properties, powerStation.SiteDB); var calllist = await powerStationRepository.GetApicallList(powerStation.Id, exceptionModal.Type); foreach (var call in calllist) { if (call.LimitValue == 0) { if (exceptionModal.UpperLimit != -9999) { Fetch_PostWithJSONFormat($"http://{call.UrlSite}/obix/config/Solar/S{powerStation.Code}01/API/{call.UrlApi}/set", exceptionModal.UpperLimit.ToString()); } } else if (call.LimitValue == 1) { if (exceptionModal.LowerLimit != -9999) { Fetch_PostWithJSONFormat($"http://{call.UrlSite}/obix/config/Solar/S{powerStation.Code}01/API/{call.UrlApi}/set", exceptionModal.LowerLimit.ToString()); } } } apiResult.Code = "0000"; apiResult.Msg = "儲存成功"; } } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = exception.ToString(); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "ExceptionModal=" + exceptionModal); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 異常dataTable /// /// /// public async Task ExceptionTable(int stationId) { List exceptionTable = new List(); ApiResult> apiResult = new ApiResult>(); try { PowerStation powerStation = null; powerStation = await powerStationRepository.GetOneAsync(stationId); apiResult.Code = "0000"; exceptionTable = await powerStationRepository.ExceptionTable(stationId, powerStation.SiteDB); foreach (ExceptionTable a in exceptionTable) { a.Function = @" "; if (a.Alarm == 1) { a.AlarmName = "email通知"; } } apiResult.Data = exceptionTable; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = exception.ToString(); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "stationId=" + stationId); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } var result = Json(new { data = apiResult }); return result; } /// /// 取一筆異常設定 /// /// /// public async Task> GetOneException(PostPowerStationIdAndSelectedId id) { ExceptionModal Exception = new ExceptionModal(); ApiResult apiResult = new ApiResult(); try { PowerStation powerStation = null; powerStation = await powerStationRepository.GetOneAsync(id.PowerStationId); apiResult.Code = "0000"; Exception = await powerStationRepository.OneException(id.SelectedId, powerStation.SiteDB); apiResult.Data = Exception; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = exception.ToString(); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "id=" + id); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 刪除一筆異常設定 /// /// /// public async Task> DeleteOneException(PostPowerStationIdAndSelectedId id) { ApiResult apiResult = new ApiResult(); ExceptionModal Exception = new ExceptionModal(); try { PowerStation powerStation = null; powerStation = await powerStationRepository.GetOneAsync(id.PowerStationId); Exception = await powerStationRepository.OneException(id.SelectedId, powerStation.SiteDB); if (Exception == null) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } //TODO await powerStationRepository.DeleteOneByIdWithCustomDBNameAndTable(Exception.Id, powerStation.SiteDB, "power_station_exception"); //await powerStationRepository.DeleteOneOtherTable(Exception.Id, "power_station_exception"); apiResult.Code = "0000"; apiResult.Msg = "刪除成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "id=" + id); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 取得所有電站圖片 /// /// /// [HttpPost] public async Task>> GetAllPowerStationImage(int powerStationId) { ApiResult> apiResult = new ApiResult>(); List powerStationImages = null; try { var powerStation = await powerStationRepository.GetOneAsync(powerStationId); if (powerStation == null) { apiResult.Code = "9992"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } else { if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } powerStationImages = await powerStationRepository.GetAllPowerStationImageAsync(powerStationId, powerStation.SiteDB); foreach (var stationImage in powerStationImages) { stationImage.Image = Path.Combine(stationImageFilePath, powerStation.Id.ToString()) + "/" + stationImage.Image; } } apiResult.Code = "0000"; apiResult.Data = powerStationImages; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + "PowerStationId=" + powerStationId); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } /// /// 新增 電站圖片 /// /// /// [HttpPost] public async Task>> SavePowerStationImages([FromForm] PostPowerStationImage post) { ApiResult> apiResult = new ApiResult>(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); if (powerStation == null) { apiResult.Code = "9992"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } else { if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } #region 新增圖片 List powerStationImages; if (post.StationImages != null && post.StationImages.Length > 0) { FolderFunction folderFunction = new FolderFunction(); var imageSaveAsPath = Path.Combine(powerSationSaveAsPath, powerStation.Id.ToString()); folderFunction.CreateFolder(imageSaveAsPath, 0); powerStationImages = new List(); foreach (var image in post.StationImages) { var split = image.FileName.Split("."); var fileName = Guid.NewGuid() + "." + split[split.Length - 1]; var fullPath = Path.Combine(imageSaveAsPath, fileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { image.CopyTo(stream); } PowerStationImage powerStationImage = new PowerStationImage() { PowerStationId = powerStation.Id, Image = fileName, CreatedBy = myUser.Id }; powerStationImages.Add(powerStationImage); } List properties = new List() { "PowerStationId", "Image", "CreatedBy" }; await powerStationRepository.AddPowerStationImageAsync(powerStationImages, properties, powerStation.SiteDB); } #endregion #region 重新取得圖片資訊 powerStationImages = null; powerStationImages = await powerStationRepository.GetAllPowerStationImageAsync(powerStation.Id, powerStation.SiteDB); foreach (var stationImage in powerStationImages) { stationImage.Image = Path.Combine(stationImageFilePath, powerStation.Id.ToString()) + "/" + stationImage.Image; } #endregion apiResult.Code = "0000"; apiResult.Msg = "儲存成功"; apiResult.Data = powerStationImages; } } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 軟刪除 單一電站圖片 /// /// /// public async Task> DeletePowerStationImage(PostPowerStationIdAndSelectedId post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation; PowerStationImage powerStationImage; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); powerStationImage = await powerStationRepository.GetOnePowerStationImageAsync(post.SelectedId, powerStation.SiteDB); if (powerStationImage == null) { apiResult.Code = "9990"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } await powerStationRepository.DeleteOnePowerStationImage(powerStationImage.Id, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Msg = "刪除成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 變更主要卡片顯示 /// /// /// public async Task> ChangeMainDisplay(PostChangeMainDisplay post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation; PowerStationImage powerStationImage; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); powerStationImage = await powerStationRepository.GetOnePowerStationImageAsync(post.TargetImageId, powerStation.SiteDB); if (powerStationImage == null) { apiResult.Code = "9990"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } UpdataPowerStationImage updata = new UpdataPowerStationImage(); List properties = new List(); //找出原本的圖片 var origMainDisplay = await powerStationRepository.GetMainDisplayAsync(post.PowerStationId, powerStation.SiteDB); if (origMainDisplay != null) { updata = new UpdataPowerStationImage() { Id = origMainDisplay.Id, IsMainDisplay = 0, UpdatedBy = myUser.Id }; properties = new List() { "Id", "IsMainDisplay", "UpdatedBy" }; await powerStationRepository.UpdatePowerStationImage(updata, properties, powerStation.SiteDB); } // 更新被選擇的圖維卡片顯示圖 updata = new UpdataPowerStationImage() { Id = post.TargetImageId, PowerStationId = post.PowerStationId, IsMainDisplay = 1, Image = powerStationImage.Image, UpdatedBy = myUser.Id }; properties = new List() { "Id", "IsMainDisplay", "UpdatedBy" }; await powerStationRepository.UpdatePowerStationImage(updata, properties, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Msg = "修改卡片顯示圖成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 取得所有單線圖 /// /// /// [HttpPost] public async Task>> GetAllPowerStationSingleLine(int powerStationId) { ApiResult> apiResult = new ApiResult>(); List powerStationSingleLines = null; try { var powerStation = await powerStationRepository.GetOneAsync(powerStationId); if (powerStation == null) { apiResult.Code = "9992"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } else { if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } powerStationSingleLines = await powerStationRepository.GetAllPowerStationSingleLineAsync(powerStationId, powerStation.SiteDB); foreach (var singleLine in powerStationSingleLines) { singleLine.Image = Path.Combine(stationImageFilePath, powerStation.Id.ToString()) + "/" + singleLine.Image; } } apiResult.Code = "0000"; apiResult.Data = powerStationSingleLines; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + "PowerStationId=" + powerStationId); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } /// /// 新增 單線圖 /// /// /// [HttpPost] public async Task>> SavePowerStationSingleLine([FromForm] PostPowerStationSingleLine post) { ApiResult> apiResult = new ApiResult>(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); if (powerStation == null) { apiResult.Code = "9992"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } else { if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } #region 新增圖片 List powerStationSingleLines; if (post.SingleLineImages != null && post.SingleLineImages.Length > 0) { FolderFunction folderFunction = new FolderFunction(); var imageSaveAsPath = Path.Combine(powerSationSaveAsPath, powerStation.Id.ToString()); folderFunction.CreateFolder(imageSaveAsPath, 0); powerStationSingleLines = new List(); foreach (var image in post.SingleLineImages) { var split = image.FileName.Split("."); var fileName = Guid.NewGuid() + "." + split[split.Length - 1]; var fullPath = Path.Combine(imageSaveAsPath, fileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { image.CopyTo(stream); } PowerStationSingleLine powerStationSingleLine = new PowerStationSingleLine() { PowerStationId = powerStation.Id, Image = fileName, CreatedBy = myUser.Id }; powerStationSingleLines.Add(powerStationSingleLine); } List properties = new List() { "PowerStationId", "Image", "CreatedBy" }; await powerStationRepository.AddPowerStationSingleLineAsync(powerStationSingleLines, properties, powerStation.SiteDB); } #endregion #region 重新取得圖片資訊 powerStationSingleLines = null; powerStationSingleLines = await powerStationRepository.GetAllPowerStationSingleLineAsync(powerStation.Id, powerStation.SiteDB); foreach (var singleLine in powerStationSingleLines) { singleLine.Image = Path.Combine(stationImageFilePath, powerStation.Id.ToString()) + "/" + singleLine.Image; } #endregion apiResult.Code = "0000"; apiResult.Msg = "儲存成功"; apiResult.Data = powerStationSingleLines; } } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 軟刪除 單一單線圖 /// /// /// public async Task> DeletePowerStationSingleLine(PostPowerStationIdAndSelectedId post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation; PowerStationSingleLine powerStationSingleLine; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } powerStationSingleLine = await powerStationRepository.GetOnePowerStationSingleLineAsync(post.SelectedId, powerStation.SiteDB); if (powerStationSingleLine == null) { apiResult.Code = "9990"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } await powerStationRepository.DeleteOnePowerStationSingleLine(powerStationSingleLine.Id, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Msg = "刪除成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 取得該使用者可看的所有電站分佈縣市以及各縣市電站數量 /// /// public async Task>> GetSolarCitySummary() { ApiResult> apiResult = new ApiResult>(); List solaramount = new List(); try { apiResult.Code = "0000"; //solaramount = await powerStationRepository.GetSolarCitySummary(myUser); solaramount = myPowerStationService.GetMyCities(myUser, 0); apiResult.Data = solaramount; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = exception.ToString(); } return apiResult; } /// /// 取得該使用者可看的所有電站分佈縣市以及各縣市電站數量 /// /// public async Task>> GetSolarByCity(List cityid) { ApiResult> apiResult = new ApiResult>(); List solaramount = new List(); try { apiResult.Code = "0000"; //solaramount = await powerStationRepository.GetSolarByCity(myUser, cityid); solaramount = myPowerStationService.GetMyPowerStations(myUser, 0, cityid); foreach (var solar in solaramount) { //判斷該檔案是否存在 if (!string.IsNullOrEmpty(solar.MainDisplay)) { var fullFilePath = Directory.GetCurrentDirectory() + "/wwwroot" + Path.Combine(stationImageFilePath, solar.Id.ToString()) + "/" + solar.MainDisplay; if (System.IO.File.Exists(fullFilePath)) { solar.MainDisplay = Path.Combine(stationImageFilePath, solar.Id.ToString()) + "/" + solar.MainDisplay; } else { solar.MainDisplay = Path.Combine("img", "blank.gif"); } } else { solar.MainDisplay = Path.Combine("img", "blank.gif"); } List deviceControllerid = await powerStationRepository.GetAllDeviceControllerId(solar.Id, solar.SiteDB); var InverterTable = await powerStationRepository.InverterTable(deviceControllerid, solar.SiteDB); solar.InverterAmount = InverterTable.Count; } apiResult.Data = solaramount; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = exception.ToString(); } return apiResult; } /// /// 儲存控制器 /// /// /// public async Task> SaveController(DeviceControllerModal post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = new PowerStation(); powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); var tableName = powerStation.SiteDB + ".controller"; try { for (var i = 0; i < post.Count; i++) { var Num = await powerStationRepository.GetCurrentSerialNumber(tableName, "PowerStationId =" + powerStation.Id); var Newnum = GetLastSerialNumber(Num, 2); DeviceController deviceController = new DeviceController() { Id = post.Id, ControllerId = powerStation.Code + Newnum, PowerStationId = powerStation.Id, CreatedBy = myUser.Id, SerialNumber = Newnum }; List properties = new List() { "Id", "ControllerId", "PowerStationId", "CreatedBy", "SerialNumber" }; await powerStationRepository.AddDeviceController(deviceController, properties, powerStation.SiteDB); } apiResult.Code = "0000"; apiResult.Msg = "新增成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 控制器DataTable /// /// /// public async Task DeviceControllerControllerTable(int stationId) { List deviceControllerTable = new List(); ApiResult> apiResult = new ApiResult>(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(stationId); deviceControllerTable = await powerStationRepository.DeviceControllerTable(stationId, powerStation.SiteDB); foreach (DeviceControllerTable a in deviceControllerTable) { a.Function = @" "; } apiResult.Code = "0000"; apiResult.Data = deviceControllerTable; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "stationId = " + stationId); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } var result = Json(new { data = apiResult }); return result; } /// /// 刪除控制器 /// /// /// public async Task> DeleteOneDeviceController(PostPowerStationIdAndSelectedId post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); var deviceController = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync(post.SelectedId, powerStation.SiteDB, "controller"); if (deviceController == null) { apiResult.Code = "9988"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } var inverter = await powerStationRepository.GetoneData("ControllerId = " + post.SelectedId + " AND Deleted = 0", powerStation.SiteDB, "inverter"); var device = await powerStationRepository.GetoneData("ControllerId = " + post.SelectedId + " AND Deleted = 0", powerStation.SiteDB, "device"); if (inverter != null) { apiResult.Code = "0002"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } if (device != null) { apiResult.Code = "0003"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } await powerStationRepository.DeleteOneByIdWithCustomDBNameAndTable(post.SelectedId, powerStation.SiteDB, "controller"); apiResult.Code = "0000"; apiResult.Msg = "刪除成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 新增逆變器 /// /// /// public async Task> SaveInverter(Inverter post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); var inverter1 = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync(post.Id, powerStation.SiteDB, "inverter"); var tableName = powerStation.SiteDB + ".inverter"; try { if (post.Id == 0) { var Num = await powerStationRepository.GetCurrentSerialNumber(tableName, "ControllerId =" + post.ControllerId); var Newnum = GetLastSerialNumber(Num); var deviceController = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync(post.ControllerId, powerStation.SiteDB, "controller"); Inverter inverter = new Inverter() { Status = post.Status, Brand = post.Brand, Capacity = post.Capacity, Enabled = post.Enabled, Model = post.Model, InstallDate = post.InstallDate, InverterName = post.InverterName, Pyrheliometer = post.Pyrheliometer, ControllerId = post.ControllerId, SerialNumber = Newnum, InverterId = deviceController.ControllerId + Newnum, CreatedBy = myUser.Id, BrandNum = post.BrandNum }; List properties = new List() { "Status", "Brand", "Capacity", "Enabled", "Model", "InstallDate", "InverterName", "Pyrheliometer", "ControllerId", "SerialNumber", "CreatedBy", "InverterId", "BrandNum" }; if (post.WarrantyDate != "0001-01-01") { inverter.WarrantyDate = post.WarrantyDate; properties.Add("WarrantyDate"); } await powerStationRepository.AddInverter(inverter, properties, powerStation.SiteDB); BackFillSchedule backFillSchedule = new BackFillSchedule() { UID = deviceController.ControllerId + Newnum, DBName = powerStation.SiteDB, TableName = "s" + deviceController.ControllerId + "_inv" }; properties = new List() { "UID", "DBName", "TableName" }; await powerStationRepository.AddAnyThing(backFillSchedule, properties, "back_fill_schedule"); await powerStationRepository.StationStatus(post.PowerStationId, 0); await powerStationRepository.StationStatus(post.PowerStationId, 0, powerStation.SiteDB + "."); apiResult.Code = "0000"; apiResult.Msg = "新增成功"; } else { if (inverter1 == null) { apiResult.Msg = "找不到資料"; apiResult.Code = "0001"; } else { Inverter inverter = new Inverter() { Id = post.Id, Status = post.Status, Brand = post.Brand, Capacity = post.Capacity, Enabled = post.Enabled, Model = post.Model, InstallDate = post.InstallDate, InverterName = post.InverterName, Pyrheliometer = post.Pyrheliometer, ControllerId = post.ControllerId, UpdatedBy = myUser.Id, BrandNum = post.BrandNum }; List properties = new List() { "Id", "Status", "Brand", "Capacity", "Enabled", "Model", "InstallDate", "InverterName", "Pyrheliometer", "ControllerId", "UpdatedBy", "BrandNum" }; if (post.WarrantyDate != "0001-01-01") { inverter.WarrantyDate = post.WarrantyDate; properties.Add("WarrantyDate"); } await powerStationRepository.UpdateInverter(inverter, properties, powerStation.SiteDB); await powerStationRepository.StationStatus(post.PowerStationId, 0); await powerStationRepository.StationStatus(post.PowerStationId, 0, powerStation.SiteDB + "."); apiResult.Code = "0000"; apiResult.Msg = "更新成功"; } } } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 逆變器Table /// /// /// public async Task InverterTable(int stationId) { ApiResult> apiResult = new ApiResult>(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(stationId); List deviceControllerid = await powerStationRepository.GetAllDeviceControllerId(stationId, powerStation.SiteDB); List InverterTable = new List(); InverterTable = await powerStationRepository.InverterTable(deviceControllerid, powerStation.SiteDB); foreach (InverterTable a in InverterTable) { switch (a.Status) { case 0: a.StatusName = "未啟用"; break; case 1: a.StatusName = "正常"; break; case 2: a.StatusName = "異常"; break; default: a.StatusName = "無資料"; break; } switch (a.Enabled) { case 0: a.EnabledName = "未啟用"; break; case 1: a.EnabledName = "啟用"; break; default: a.EnabledName = "無資料"; break; } if (a.PyrheliometerName == null) { a.PyrheliometerName = "無設備"; } a.Function = @" "; //if(a.WarrantyDate == "0001-01-01") //{ // a.WarrantyDate = ""; //} } apiResult.Code = "0000"; apiResult.Data = InverterTable; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "stationId = " + stationId); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } var result = Json(new { data = apiResult }); return result; } /// /// 刪除逆變器 /// /// /// public async Task> DeleteOneInverter(PostPowerStationIdAndSelectedId post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); var deviceController = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync(post.SelectedId, powerStation.SiteDB, "inverter"); if (deviceController == null) { apiResult.Code = "9988"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } await powerStationRepository.DeleteOneByIdWithCustomDBNameAndTable(post.SelectedId, powerStation.SiteDB, "inverter"); apiResult.Code = "0000"; apiResult.Msg = "刪除成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 其他電站下拉式選單 /// /// public async Task>> GetPowerstationOption(int stationId) { ApiResult> apiResult = new ApiResult>(); try { var powerStation = await powerStationRepository.GetOneAsync(stationId); var PowerstationOption = await powerStationRepository.GetPowerstationOptionAsync(powerStation.SiteDB, stationId); apiResult.Code = "0000"; apiResult.Data = PowerstationOption; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } /// /// 電站裡的設備 /// /// /// public async Task>> GetDeviceUIDList(int stationId) { ApiResult> apiResult = new ApiResult>(); try { var powerStation = await powerStationRepository.GetOneAsync(stationId); var PowerstationOption = await powerStationRepository.GetDeviceUIDListAsync(powerStation.SiteDB, stationId); apiResult.Code = "0000"; apiResult.Data = PowerstationOption; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } /// /// 新增共享設備 /// /// /// public async Task> SaveShareDevice(Sharedevice post) { ApiResult apiResult = new ApiResult(); try { var powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); Sharedevice sharedevice = new Sharedevice() { PowerStationId = post.PowerStationId, DeviceId = post.DeviceId, CreatedBy = myUser.Id }; List properties = new List() { "PowerStationId", "DeviceId", "CreatedBy" }; await powerStationRepository.AddShareDevice(sharedevice, properties, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Msg = "新增成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 共享設備DataTable /// /// /// public async Task ShareDeviceTable(int stationId) { List sharedeviceTables = new List(); ApiResult> apiResult = new ApiResult>(); try { PowerStation powerStation = null; powerStation = await powerStationRepository.GetOneAsync(stationId); sharedeviceTables = await powerStationRepository.shareDeviceTables(stationId, powerStation.SiteDB); foreach (DeviceTable a in sharedeviceTables) { switch (a.Status) { case 0: a.StatusName = "未啟用"; break; case 1: a.StatusName = "正常"; break; case 2: a.StatusName = "異常"; break; default: a.StatusName = "無資料"; break; } switch (a.Enabled) { case 0: a.EnabledName = "未啟用"; break; case 1: a.EnabledName = "啟用"; break; default: a.EnabledName = "無資料"; break; } a.Function = @" "; } apiResult.Code = "0000"; apiResult.Data = sharedeviceTables; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = exception.ToString(); Logger.LogError("【" + controllerName + "/" + actionName + "】" + "stationId=" + stationId); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } var result = Json(new { data = apiResult }); return result; } /// /// 刪除共用裝置資料 /// /// /// public async Task> DeleteOneShareDevice(PostPowerStationIdAndSelectedId post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); var ShareDevice = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync(post.SelectedId, powerStation.SiteDB, "sharedevice"); var div = await powerStationRepository.Getonediv("inv.Deleted = 0 AND con.PowerStationId = sh.PowerStationId", powerStation.SiteDB, $"sharedevice sh INNER JOIN {powerStation.SiteDB}.inverter inv ON inv.Pyrheliometer = sh.DeviceId INNER JOIN {powerStation.SiteDB}.controller con ON con.Id = inv.ControllerId"); if (div != null) { apiResult.Code = "0004"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } if (ShareDevice == null) { apiResult.Code = "9988"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } await powerStationRepository.PurgeOneByIdWithCustomDBNameAndTable(post.SelectedId, powerStation.SiteDB, "sharedevice"); apiResult.Code = "0000"; apiResult.Msg = "刪除成功"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } /// /// 日照計下拉式選單 /// /// /// public async Task>> GetPyrheliometerList(int stationId) { ApiResult> apiResult = new ApiResult>(); try { var powerStation = await powerStationRepository.GetOneAsync(stationId); var PowerstationOption = await powerStationRepository.GetPowerstationPyrheliometerAsync(powerStation.SiteDB, stationId); apiResult.Code = "0000"; apiResult.Data = PowerstationOption; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } public async Task> GetOneInverter(PostPowerStationIdAndSelectedId post) { ApiResult apiResult = new ApiResult(); PowerStation powerStation = null; try { powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId); apiResult.Code = "0000"; var inverter = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync(post.SelectedId, powerStation.SiteDB, "inverter"); apiResult.Data = inverter; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } [HttpPost] public async Task>> GetAllPowerStationsALLImage(List powerStationId) { ApiResult> apiResult = new ApiResult>(); List powerStationImages = null; List ALLpowerStationImages = new List(); try { foreach (var ones in powerStationId) { var powerStation = await powerStationRepository.GetOneAsync(ones); if (powerStation == null) { apiResult.Code = "9992"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } else { if (!IsPlatformLayer(myUser.Role.Layer) && powerStation.CompanyId != myUser.CompanyId) { apiResult.Code = "9993"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } powerStationImages = await powerStationRepository.GetAllPowerStationImageAsync(ones, powerStation.SiteDB); foreach (var stationImage in powerStationImages) { stationImage.Image = Path.Combine(stationImageFilePath, powerStation.Id.ToString()) + "/" + stationImage.Image; } ALLpowerStationImages = ALLpowerStationImages.Concat(powerStationImages).ToList(); } } apiResult.Code = "0000"; apiResult.Data = ALLpowerStationImages; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + "PowerStationId=" + powerStationId); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } public async Task>> GetInverterInfoList (IdAndDB post) { List list = new List(); ApiResult> apiResult = new ApiResult>(); try { var controllers = await powerStationRepository.GetAllDeviceControllerId(post.Id, post.SiteDB); if(controllers.Count == 0) { apiResult.Code = "0001"; apiResult.Msg = "該電站沒有控制器"; return apiResult; } var inverters = await powerStationRepository.InverterTable(controllers, post.SiteDB); if (inverters.Count == 0) { apiResult.Code = "0001"; apiResult.Msg = "該電站沒有啟用的逆變器"; return apiResult; } var inverterIds = inverters.Where(x => x.Enabled == 1).Select(x => new { InverterId = x.InverterId, Type = x.Status,Name = x.InverterName}).ToList(); var inverterIdsname = inverterIds.Select(x => x.InverterId).ToList(); if (inverterIds.Count > 0) { var site = "s" + inverterIds[0].InverterId.Substring(0, 11) + "_inv"; var inverterss = await powerStationRepository.GetAllInverterInfo(inverterIdsname, site, post.SiteDB); foreach(var inverter in inverterss) { var type = inverterIds.Where(a => a.Name == inverter.INVERTERName).Select(x => x.Type).FirstOrDefault(); var info = new InverterInfoList { Input = (inverter.DC1W + inverter.DC2W + inverter.DC3W + inverter.DC4W + inverter.DC5W)/1000, Output = (inverter.AC1W + inverter.AC2W + inverter.AC3W)/1000, PR = inverter.PR, TODAYKWH = inverter.TODAYKWH, Name = inverter.INVERTERName, ID = inverter.ID, Type = type, TIMESTAMP = inverter.TIMESTAMP, UseDB = post.SiteDB, UseTable = site }; list.Add(info); } } //var inverterIdsdd = inverters.Where(x => x.Enabled == 1 && x.Status == 2).Select(x => x.InverterId).ToList(); //if (inverterIdsdd.Count > 0) //{ // var site = "s" + inverterIdsdd[0].Substring(0, 11) + "_inv"; // var inverterss = await powerStationRepository.GetAllInverterInfo(inverterIdsdd, site, post.SiteDB); // foreach (var inverter in inverterss) // { // var info = new InverterInfoList // { // Input = (inverter.DC1W + inverter.DC2W + inverter.DC3W + inverter.DC4W + inverter.DC5W) / 1000, // Output = (inverter.AC1W + inverter.AC2W + inverter.AC3W) / 1000, // PR = inverter.PR, // TODAYKWH = inverter.TODAYKWH, // Name = inverter.INVERTERName, // ID = inverter.ID, // Type = 2, // TIMESTAMP = inverter.TIMESTAMP, // UseDB = post.SiteDB, // UseTable = site // }; // list.Add(info); // } //} //foreach (var inverter in inverterIdsdd) //{ // var info = new InverterInfoList // { // Input = (inverter.DC1W + inverter.DC2W + inverter.DC3W + inverter.DC4W + inverter.DC5W) / 1000, // Output = (inverter.AC1W + inverter.AC2W + inverter.AC3W) / 1000, // PR = inverter.PR, // TODAYKWH = 0, // Name = inverter.name, // ID = inverter.id, // Type = 2 // }; // list.Add(info); //} //list.OrderBy(a => a.ID); apiResult.Code = "0000"; apiResult.Data = list; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } public async Task> GetInverterInfoModal (TimeAndID post) { InverterDetailModal detailModal = new InverterDetailModal(); ApiResult apiResult = new ApiResult(); try { detailModal = await powerStationRepository.GetInverterInfoModal(post.Id, post.Time, post.UseDB, post.UseTable); apiResult.Data = detailModal; apiResult.Code = "0000"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); string json = System.Text.Json.JsonSerializer.Serialize(post); Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } [HttpPost] public async Task>> GetApicallItemList(int powerStationId) { ApiResult> apiResult = new ApiResult>(); try { var powerStation = await powerStationRepository.GetOneAsync(powerStationId); var ItemLists = await powerStationRepository.GetApicallItemList(powerStationId, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Data = ItemLists; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } public async Task> DeletePowerStation (int stationId) { ApiResult apiResult = new ApiResult(); try { var powerstation = await powerStationRepository.GetOneAsync(stationId); if (powerstation == null) { apiResult.Code = "9992"; apiResult.Msg = errorCode.GetString(apiResult.Code); return apiResult; } await powerStationRepository.DeleteOneByIdWithCustomDBNameAndTable(stationId, powerstation.SiteDB, "power_station"); await powerStationRepository.DropShareDevice(stationId, powerstation.SiteDB); await powerStationRepository.DeleteALLPowerStationOperationPersonnel(stationId); await powerStationRepository.DeleteOne(stationId); apiResult.Msg = "刪除成功"; apiResult.Code = "0000"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = errorCode.GetString(apiResult.Code); Logger.LogError("【" + controllerName + "/" + actionName + "】" + stationId); Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } public JObject Fetch_PostWithJSONFormat(string url, string paramter) { try { string username = "SolarAPI"; string password = "Admin123456"; string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(url); Postrequest.Method = "POST"; Postrequest.Headers.Add("Authorization", "Basic " + encoded); Postrequest.PreAuthenticate = true; using (var streamWriter = new StreamWriter(Postrequest.GetRequestStream())) { string json = ""; streamWriter.Write(json); } HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(responseString); string jsonText = JsonConvert.SerializeXmlNode(xmlDoc); JObject resultVal = (JObject)JsonConvert.DeserializeObject(jsonText); return resultVal; } catch (Exception ex) { Logger.LogError("【" + controllerName + "/" + actionName + "】" + "Fetch_PostWithJSONFormat:" + ex ); throw ex; } } public async Task>> GetShareDevicePowerstationName (int Id) { ApiResult> apiResult = new ApiResult>(); List names = new List(); try { var powerStation = await powerStationRepository.GetOneAsync(Id); names = await powerStationRepository.GetShareDevicePowerstationName(Id, powerStation.SiteDB); apiResult.Code = "0000"; apiResult.Data = names; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } public async Task>> CheckStationStatus (int Id) { ApiResult> apiResult = new ApiResult>(); List status = new List(); try { var powerStation = await powerStationRepository.GetOneAsync(Id); status = await powerStationRepository.CheckStationStatus(powerStation.Code, powerStation.SiteDB); if(status.Count > 0) { apiResult.Code = "0099"; apiResult.Data = status; } else { await powerStationRepository.StationStatus(Id,1); await powerStationRepository.StationStatus(Id, 1, powerStation.SiteDB + "."); apiResult.Msg = "電站啟用成功"; apiResult.Code = "0000"; } } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } public async Task> StationUnStatus(int Id) { ApiResult apiResult = new ApiResult(); try { var powerstation = await powerStationRepository.GetOneAsync(Id); await powerStationRepository.StationStatus(Id, 0); await powerStationRepository.StationStatus(Id, 0,powerstation.SiteDB + "."); apiResult.Msg = "電站停用成功"; apiResult.Code = "0000"; } catch (Exception exception) { apiResult.Code = "9999"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); } return apiResult; } //public async Task> SetApiforLineToken (int PowerStationId,string Token) //{ //} } }