FIC_Solar/SolarPower/Controllers/PowerStationController.cs
2021-09-02 10:52:03 +08:00

3160 lines
130 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.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<PowerStationController>
{
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");
}
/// <summary>
/// 取得下拉式公司選單須為Deleted: 0
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<ApiResult<List<UserSelectItemList>>> GetUserSelectOptionListAsync(int powerStationId)
{
ApiResult<List<UserSelectItemList>> apiResult = new ApiResult<List<UserSelectItemList>>();
try
{
var companyId = 0;
var powerStation = await powerStationRepository.GetOneAsync(powerStationId);
if (powerStation == null)
{
companyId = myUser.CompanyId;
}
else
{
companyId = powerStation.CompanyId;
}
var margeUserSelectItemLists = new List<UserSelectItemList>();
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<ApiResult<List<CompanySelectItemList>>> GetCompanySelectOptionListAsync()
{
ApiResult<List<CompanySelectItemList>> apiResult = new ApiResult<List<CompanySelectItemList>>();
try
{
var companySelectItemLists = new List<CompanySelectItemList>();
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;
}
/// <summary>
/// 取裝置類型下拉選單
/// </summary>
/// <returns></returns>
public async Task<ApiResult<List<UserSelectItemList>>> GetDeviceTypeSelectOptionList()
{
ApiResult<List<UserSelectItemList>> apiResult = new ApiResult<List<UserSelectItemList>>();
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;
}
/// <summary>
/// 取得縣市選單
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<ApiResult<List<CitySelectItemList>>> GetCitySelectOptionList()
{
ApiResult<List<CitySelectItemList>> apiResult = new ApiResult<List<CitySelectItemList>>();
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;
}
/// <summary>
/// 取得地區選單
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<ApiResult<List<AreaSelectItemList>>> GetAreaSelectOptionList(int cityId)
{
ApiResult<List<AreaSelectItemList>> apiResult = new ApiResult<List<AreaSelectItemList>>();
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<ApiResult<List<OperationPersonnelSelectItemList>>> GetOperationPersonnelSelectOptionList(int powerStationId)
{
ApiResult<List<OperationPersonnelSelectItemList>> apiResult = new ApiResult<List<OperationPersonnelSelectItemList>>();
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<ApiResult<List<FirmlSelectItemList>>> GetFirmSelectOptionList(int powerStationId)
{
ApiResult<List<FirmlSelectItemList>> apiResult = new ApiResult<List<FirmlSelectItemList>>();
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;
}
/// <summary>
/// 取得單一電站基本資料
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost]
public async Task<ApiResult<PowerStation>> GetOnePowerStation(int id)
{
ApiResult<PowerStation> apiResult = new ApiResult<PowerStation>();
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;
}
/// <summary>
/// 新增 / 修改 電站基本資料
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<PowerStation>> SavePowerStationInfo(PostPowerStationInfo post)
{
ApiResult<PowerStation> apiResult = new ApiResult<PowerStation>();
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<string> properties = new List<string>()
{
"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<string> landBuildingProperties = new List<string>()
{
"Address",
"PowerStationId",
"CreatedBy"
};
await powerStationRepository.AddOneLandBuildingInfo(landBuilding, landBuildingProperties, company.SiteDB);
#endregion
#region
//找出要新增的
if (post.OperationPersonnelIds != null)
{
List<PowerStationOperationPersonnel> insertOperationPersonnels = new List<PowerStationOperationPersonnel>();
foreach (var op in post.OperationPersonnelIds)
{
PowerStationOperationPersonnel operationPersonnel = new PowerStationOperationPersonnel();
operationPersonnel.PowerStationId = id;
operationPersonnel.UserId = op;
operationPersonnel.CreatedBy = myUser.Id;
insertOperationPersonnels.Add(operationPersonnel);
}
List<string> operationPersonnelProperties = new List<string>()
{
"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<string>()
{
"UID",
"DBName",
"TableName"
};
await powerStationRepository.AddAnyThing<BackFillSchedule>(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<string> properties = new List<string>()
{
"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<int> origOperationPersonnels = null; //原先的運維人員
origOperationPersonnels = await powerStationRepository.GetOperationPersonnelIdsByPowerStatioinId(powerStation.Id);
//判斷新進來的資料是否要歸類到新增 or 刪除
#region
//找出要刪除的
List<int> deleteOperationPersonnelIds = origOperationPersonnels.Where(x => !post.OperationPersonnelIds.Contains(x)).ToList();
List<PowerStationOperationPersonnel> deleteOperationPersonnels = new List<PowerStationOperationPersonnel>();
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<int> insertOperationPersonnelIds = post.OperationPersonnelIds.Where(x => !origOperationPersonnels.Contains(x)).ToList();
List<PowerStationOperationPersonnel> insertOperationPersonnels = new List<PowerStationOperationPersonnel>();
foreach (var op in insertOperationPersonnelIds)
{
PowerStationOperationPersonnel operationPersonnel = new PowerStationOperationPersonnel();
operationPersonnel.PowerStationId = powerStation.Id;
operationPersonnel.UserId = op;
operationPersonnel.CreatedBy = myUser.Id;
insertOperationPersonnels.Add(operationPersonnel);
}
List<string> operationPersonnelProperties = new List<string>()
{
"PowerStationId",
"UserId",
"CreatedBy",
};
await powerStationRepository.AddOperationPersonnelAsync(insertOperationPersonnels, operationPersonnelProperties);
}
#endregion
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;
}
/// <summary>
/// 新增 / 修改 能源局與台電資料
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
[HttpPost]
public async Task<ApiResult<PowerStation>> SaveBoETPCInfo([FromForm] PostBoETPCInfo post)
{
ApiResult<PowerStation> apiResult = new ApiResult<PowerStation>();
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<string> properties = new List<string>()
{
"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;
}
/// <summary>
/// 新增 / 修改 土地與房屋資料
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<PowerStation>> SaveLandBuildingInfo(PostLandBuildingInfo post)
{
ApiResult<PowerStation> apiResult = new ApiResult<PowerStation>();
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<string> properties = new List<string>()
{
"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<string> properties = new List<string>()
{
"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;
}
/// <summary>
/// 新增/修改 運維資料
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<string>> SaveOperation(OperationInfo post)
{
ApiResult<string> apiResult = new ApiResult<string>();
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
};
List<string> properties = new List<string>()
{
"Id",
"Email",
"Name",
"Phone",
"CreatedBy",
"ContactPerson",
"PowerStationId",
"Type"
};
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
};
List<string> properties = new List<string>()
{
"Id",
"Email",
"Name",
"Phone",
"CreatedBy",
"ContactPerson",
"PowerStationId",
"Type"
};
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;
}
/// <summary>
/// 運維資料DataTable
/// </summary>
/// <param name="stationId"></param>
/// <returns></returns>
public async Task<ActionResult> OperationTable(int stationId)
{
List<OperationTable> operationTable = new List<OperationTable>();
ApiResult<List<OperationTable>> apiResult = new ApiResult<List<OperationTable>>();
PowerStation powerStation = null;
try
{
powerStation = await powerStationRepository.GetOneAsync(stationId);
operationTable = await powerStationRepository.OperationTable(stationId, powerStation.SiteDB);
foreach (OperationTable a in operationTable)
{
a.Function = @"
<button type='button' class='btn btn-primary btn-pills waves-effect waves-themed edit-btn'>修改</button>
<button type='button' class='btn btn-danger btn-pills waves-effect waves-themed del-btn'>刪除</button>";
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;
}
/// <summary>
/// 取得一筆 運維 資料
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<OperationInfo>> GetOneOperation(PostPowerStationIdAndSelectedId post)
{
ApiResult<OperationInfo> apiResult = new ApiResult<OperationInfo>();
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;
}
/// <summary>
/// 刪除 運維 資料
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<ApiResult<string>> DeleteOneOperation(PostPowerStationIdAndSelectedId post)
{
ApiResult<string> apiResult = new ApiResult<string>();
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;
}
/// <summary>
/// 新增 / 修改 裝置資料
/// </summary>
/// <param name="Device"></param>
/// <returns></returns>
public async Task<ApiResult<string>> SaveDevice(DeviceInfo Device)
{
ApiResult<string> apiResult = new ApiResult<string>();
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<DeviceController>(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<string> properties = new List<string>()
{
"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<string>()
{
"ColName",
"UID",
"DBName",
"TableName"
};
await powerStationRepository.AddAnyThing<BackFillSchedule>(backFillSchedule, properties, "back_fill_schedule");
apiResult.Code = "0000";
apiResult.Msg = "新增成功";
}
else
{
var deviceController = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync<DeviceController>(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<string> properties = new List<string>()
{
"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);
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;
}
/// <summary>
/// 設備DataTable
/// </summary>
/// <param name="stationId"></param>
/// <returns></returns>
public async Task<ActionResult> DeviceTable(int stationId)
{
List<DeviceTable> deviceTables = new List<DeviceTable>();
ApiResult<List<DeviceTable>> apiResult = new ApiResult<List<DeviceTable>>();
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 = @"
<button type='button' class='btn btn-primary btn-pills waves-effect waves-themed edit-btn'>修改</button>
<button type='button' class='btn btn-danger btn-pills waves-effect waves-themed del-btn'>刪除</button>";
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;
}
/// <summary>
/// 軟刪除單一土地房屋資訊
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost]
public async Task<ApiResult<PowerStation>> DeleteLandBuildingInfo(PostPowerStationIdAndSelectedId post)
{
ApiResult<PowerStation> apiResult = new ApiResult<PowerStation>();
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;
}
/// <summary>
/// 取單一設備資料
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<ApiResult<DeviceInfo>> GetOneDevice(PostPowerStationIdAndSelectedId id)
{
DeviceInfo Device = new DeviceInfo();
ApiResult<DeviceInfo> apiResult = new ApiResult<DeviceInfo>();
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;
}
/// <summary>
/// 刪除設備
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<ApiResult<string>> DeleteOneDevice(PostPowerStationIdAndSelectedId id)
{
ApiResult<string> apiResult = new ApiResult<string>();
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;
}
/// <summary>
/// 新增/修改異常
/// </summary>
/// <param name="exceptionModal"></param>
/// <returns></returns>
public async Task<ApiResult<string>> SaveException(ExceptionModal exceptionModal)
{
ApiResult<string> apiResult = new ApiResult<string>();
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<string> properties = new List<string>()
{
"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<string> properties = new List<string>()
{
"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;
}
/// <summary>
/// 異常dataTable
/// </summary>
/// <param name="stationId"></param>
/// <returns></returns>
public async Task<ActionResult> ExceptionTable(int stationId)
{
List<ExceptionTable> exceptionTable = new List<ExceptionTable>();
ApiResult<List<ExceptionTable>> apiResult = new ApiResult<List<ExceptionTable>>();
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 = @"
<button type='button' class='btn btn-primary btn-pills waves-effect waves-themed edit-btn'>修改</button>
<button type='button' class='btn btn-danger btn-pills waves-effect waves-themed del-btn'>刪除</button>";
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;
}
/// <summary>
/// 取一筆異常設定
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<ApiResult<ExceptionModal>> GetOneException(PostPowerStationIdAndSelectedId id)
{
ExceptionModal Exception = new ExceptionModal();
ApiResult<ExceptionModal> apiResult = new ApiResult<ExceptionModal>();
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;
}
/// <summary>
/// 刪除一筆異常設定
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<ApiResult<string>> DeleteOneException(PostPowerStationIdAndSelectedId id)
{
ApiResult<string> apiResult = new ApiResult<string>();
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;
}
/// <summary>
/// 取得所有電站圖片
/// </summary>
/// <param name="powerStationId"></param>
/// <returns></returns>
[HttpPost]
public async Task<ApiResult<List<PowerStationImage>>> GetAllPowerStationImage(int powerStationId)
{
ApiResult<List<PowerStationImage>> apiResult = new ApiResult<List<PowerStationImage>>();
List<PowerStationImage> 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;
}
/// <summary>
/// 新增 電站圖片
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
[HttpPost]
public async Task<ApiResult<List<PowerStationImage>>> SavePowerStationImages([FromForm] PostPowerStationImage post)
{
ApiResult<List<PowerStationImage>> apiResult = new ApiResult<List<PowerStationImage>>();
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<PowerStationImage> 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<PowerStationImage>();
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<string> properties = new List<string>()
{
"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;
}
/// <summary>
/// 軟刪除 單一電站圖片
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<ApiResult<string>> DeletePowerStationImage(PostPowerStationIdAndSelectedId post)
{
ApiResult<string> apiResult = new ApiResult<string>();
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;
}
/// <summary>
/// 變更主要卡片顯示
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<string>> ChangeMainDisplay(PostChangeMainDisplay post)
{
ApiResult<string> apiResult = new ApiResult<string>();
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<string> properties = new List<string>();
//找出原本的圖片
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<string>()
{
"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<string>()
{
"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;
}
/// <summary>
/// 取得所有單線圖
/// </summary>
/// <param name="powerStationId"></param>
/// <returns></returns>
[HttpPost]
public async Task<ApiResult<List<PowerStationSingleLine>>> GetAllPowerStationSingleLine(int powerStationId)
{
ApiResult<List<PowerStationSingleLine>> apiResult = new ApiResult<List<PowerStationSingleLine>>();
List<PowerStationSingleLine> 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;
}
/// <summary>
/// 新增 單線圖
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
[HttpPost]
public async Task<ApiResult<List<PowerStationSingleLine>>> SavePowerStationSingleLine([FromForm] PostPowerStationSingleLine post)
{
ApiResult<List<PowerStationSingleLine>> apiResult = new ApiResult<List<PowerStationSingleLine>>();
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<PowerStationSingleLine> 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<PowerStationSingleLine>();
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<string> properties = new List<string>()
{
"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;
}
/// <summary>
/// 軟刪除 單一單線圖
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<ApiResult<string>> DeletePowerStationSingleLine(PostPowerStationIdAndSelectedId post)
{
ApiResult<string> apiResult = new ApiResult<string>();
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;
}
/// <summary>
/// 取得該使用者可看的所有電站分佈縣市以及各縣市電站數量
/// </summary>
/// <returns></returns>
public async Task<ApiResult<List<SolarCityAmount>>> GetSolarCitySummary()
{
ApiResult<List<SolarCityAmount>> apiResult = new ApiResult<List<SolarCityAmount>>();
List<SolarCityAmount> solaramount = new List<SolarCityAmount>();
try
{
apiResult.Code = "0000";
solaramount = await powerStationRepository.GetSolarCitySummary(myUser);
apiResult.Data = solaramount;
}
catch (Exception exception)
{
apiResult.Code = "9999";
apiResult.Msg = exception.ToString();
}
return apiResult;
}
/// <summary>
/// 取得該使用者可看的所有電站分佈縣市以及各縣市電站數量
/// </summary>
/// <returns></returns>
public async Task<ApiResult<List<PowerStation>>> GetSolarByCity(List<int> cityid)
{
ApiResult<List<PowerStation>> apiResult = new ApiResult<List<PowerStation>>();
List<PowerStation> solaramount = new List<PowerStation>();
try
{
apiResult.Code = "0000";
solaramount = await powerStationRepository.GetSolarByCity(myUser, 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<int> 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;
}
/// <summary>
/// 儲存控制器
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<string>> SaveController(DeviceControllerModal post)
{
ApiResult<string> apiResult = new ApiResult<string>();
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<string> properties = new List<string>()
{
"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;
}
/// <summary>
/// 控制器DataTable
/// </summary>
/// <param name="stationId"></param>
/// <returns></returns>
public async Task<ActionResult> DeviceControllerControllerTable(int stationId)
{
List<DeviceControllerTable> deviceControllerTable = new List<DeviceControllerTable>();
ApiResult<List<DeviceControllerTable>> apiResult = new ApiResult<List<DeviceControllerTable>>();
PowerStation powerStation = null;
try
{
powerStation = await powerStationRepository.GetOneAsync(stationId);
deviceControllerTable = await powerStationRepository.DeviceControllerTable(stationId, powerStation.SiteDB);
foreach (DeviceControllerTable a in deviceControllerTable)
{
a.Function = @"
<button type='button' class='btn btn-danger btn-pills waves-effect waves-themed del-btn'>刪除</button>";
}
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;
}
/// <summary>
/// 刪除控制器
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<string>> DeleteOneDeviceController(PostPowerStationIdAndSelectedId post)
{
ApiResult<string> apiResult = new ApiResult<string>();
PowerStation powerStation = null;
try
{
powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId);
var deviceController = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync<DeviceController>(post.SelectedId, powerStation.SiteDB, "controller");
if (deviceController == null)
{
apiResult.Code = "9988";
apiResult.Msg = errorCode.GetString(apiResult.Code);
return apiResult;
}
var inverter = await powerStationRepository.GetoneData<Inverter>("ControllerId = " + post.SelectedId + " AND Deleted = 0", powerStation.SiteDB, "inverter");
var device = await powerStationRepository.GetoneData<DeviceInfo>("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;
}
/// <summary>
/// 新增逆變器
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<string>> SaveInverter(Inverter post)
{
ApiResult<string> apiResult = new ApiResult<string>();
PowerStation powerStation = null;
powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId);
var inverter1 = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync<Inverter>(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<DeviceController>(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<string> properties = new List<string>()
{
"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<string>()
{
"UID",
"DBName",
"TableName"
};
await powerStationRepository.AddAnyThing<BackFillSchedule>(backFillSchedule, properties, "back_fill_schedule");
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<string> properties = new List<string>()
{
"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);
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;
}
/// <summary>
/// 逆變器Table
/// </summary>
/// <param name="stationId"></param>
/// <returns></returns>
public async Task<ActionResult> InverterTable(int stationId)
{
ApiResult<List<InverterTable>> apiResult = new ApiResult<List<InverterTable>>();
PowerStation powerStation = null;
try
{
powerStation = await powerStationRepository.GetOneAsync(stationId);
List<int> deviceControllerid = await powerStationRepository.GetAllDeviceControllerId(stationId, powerStation.SiteDB);
List<InverterTable> InverterTable = new List<InverterTable>();
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 = @"
<button type='button' class='btn btn-primary btn-pills waves-effect waves-themed edit-btn'>修改</button>
<button type='button' class='btn btn-danger btn-pills waves-effect waves-themed del-btn'>刪除</button>";
//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;
}
/// <summary>
/// 刪除逆變器
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<string>> DeleteOneInverter(PostPowerStationIdAndSelectedId post)
{
ApiResult<string> apiResult = new ApiResult<string>();
PowerStation powerStation = null;
try
{
powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId);
var deviceController = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync<Inverter>(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;
}
/// <summary>
/// 其他電站下拉式選單
/// </summary>
/// <returns></returns>
public async Task<ApiResult<List<PowerstationOptionAndName>>> GetPowerstationOption(int stationId)
{
ApiResult<List<PowerstationOptionAndName>> apiResult = new ApiResult<List<PowerstationOptionAndName>>();
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;
}
/// <summary>
/// 電站裡的設備
/// </summary>
/// <param name="stationId"></param>
/// <returns></returns>
public async Task<ApiResult<List<PowerstationOptionAndName>>> GetDeviceUIDList(int stationId)
{
ApiResult<List<PowerstationOptionAndName>> apiResult = new ApiResult<List<PowerstationOptionAndName>>();
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;
}
/// <summary>
/// 新增共享設備
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<string>> SaveShareDevice(Sharedevice post)
{
ApiResult<string> apiResult = new ApiResult<string>();
try
{
var powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId);
Sharedevice sharedevice = new Sharedevice()
{
PowerStationId = post.PowerStationId,
DeviceId = post.DeviceId,
CreatedBy = myUser.Id
};
List<string> properties = new List<string>()
{
"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;
}
/// <summary>
/// 共享設備DataTable
/// </summary>
/// <param name="stationId"></param>
/// <returns></returns>
public async Task<ActionResult> ShareDeviceTable(int stationId)
{
List<DeviceTable> sharedeviceTables = new List<DeviceTable>();
ApiResult<List<DeviceTable>> apiResult = new ApiResult<List<DeviceTable>>();
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 = @"
<button type='button' class='btn btn-danger btn-pills waves-effect waves-themed del-btn'>刪除</button>";
}
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;
}
/// <summary>
/// 刪除共用裝置資料
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
public async Task<ApiResult<string>> DeleteOneShareDevice(PostPowerStationIdAndSelectedId post)
{
ApiResult<string> apiResult = new ApiResult<string>();
PowerStation powerStation = null;
try
{
powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId);
var ShareDevice = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync<Sharedevice>(post.SelectedId, powerStation.SiteDB, "sharedevice");
var div = await powerStationRepository.Getonediv<DeviceInfo>("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;
}
/// <summary>
/// 日照計下拉式選單
/// </summary>
/// <param name="stationId"></param>
/// <returns></returns>
public async Task<ApiResult<List<PowerstationOption>>> GetPyrheliometerList(int stationId)
{
ApiResult<List<PowerstationOption>> apiResult = new ApiResult<List<PowerstationOption>>();
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<ApiResult<Inverter>> GetOneInverter(PostPowerStationIdAndSelectedId post)
{
ApiResult<Inverter> apiResult = new ApiResult<Inverter>();
PowerStation powerStation = null;
try
{
powerStation = await powerStationRepository.GetOneAsync(post.PowerStationId);
apiResult.Code = "0000";
var inverter = await powerStationRepository.GetOneWithCustomDBNameAndTableAsync<Inverter>(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<ApiResult<List<PowerStationImage>>> GetAllPowerStationsALLImage(List<int> powerStationId)
{
ApiResult<List<PowerStationImage>> apiResult = new ApiResult<List<PowerStationImage>>();
List<PowerStationImage> powerStationImages = null;
List<PowerStationImage> ALLpowerStationImages = new List<PowerStationImage>();
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<ApiResult<List<InverterInfoList>>> GetInverterInfoList (IdAndDB post)
{
List<InverterInfoList> list = new List<InverterInfoList>();
ApiResult<List<InverterInfoList>> apiResult = new ApiResult<List<InverterInfoList>>();
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 && x.Status == 1).Select(x => x.InverterId).ToList();
if(inverterIds.Count > 0)
{
var site = "s" + inverterIds[0].Substring(0, 11) + "_inv";
var inverterss = await powerStationRepository.GetAllInverterInfo(inverterIds, 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 = 1,
TIMESTAMP = inverter.TIMESTAMP,
UseDB = post.SiteDB,
UseTable = site
};
list.Add(info);
}
}
var inverterIdsdd = inverters.Where(x => x.Enabled == 1 && x.Status == 2).Select(x => new { name = x.InverterName , id = x.Id } ).ToList();
foreach (var inverter in inverterIdsdd)
{
var info = new InverterInfoList
{
Input = 0,
Output = 0,
PR = 0,
TODAYKWH = 0,
Name = inverter.name,
ID = inverter.id,
Type = 2
};
list.Add(info);
}
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<ApiResult<InverterDetailModal>> GetInverterInfoModal (TimeAndID post)
{
InverterDetailModal detailModal = new InverterDetailModal();
ApiResult<InverterDetailModal> apiResult = new ApiResult<InverterDetailModal>();
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<ApiResult<List<AreaSelectItemList>>> GetApicallItemList(int powerStationId)
{
ApiResult<List<AreaSelectItemList>> apiResult = new ApiResult<List<AreaSelectItemList>>();
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<ApiResult<string>> DeletePowerStation (int stationId)
{
ApiResult<string> apiResult = new ApiResult<string>();
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.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 = "<real val=\"" + paramter + "\"/>";
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<ApiResult<List<string>>> GetShareDevicePowerstationName (int Id)
{
ApiResult<List<string>> apiResult = new ApiResult<List<string>>();
List<string> names = new List<string>();
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;
}
}
}