demo20230512/Areas/admin/Controllers/ARnGWPController.cs
2023-05-12 10:20:28 +08:00

444 lines
19 KiB
C#

using ClosedXML.Excel;
using PagedList;
using Qcarbon.ViewModels.admin;
using Qcarbon.ViewModels.DTO;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Weee.Areas.Admin.ViewModels;
using Weee.DAL;
using Weee.Models;
using Weee.ViewModels;
using Microsoft.AspNet.Identity;
using Resources;
using System.IO;
using System.Net.Mime;
namespace Weee.Areas.Admin.Controllers
{
public class ARnGWPController : AdminControllerBase
{
public ARnGWPController(WeeeDataContext d) : base(d)
{
}
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
}
public ActionResult Index(int page = 1, string arv="AR6")
{
ARnGWPvm viewModel = new ARnGWPvm();
viewModel.arv = arv;
var qry =
(from a in db.AssessmentReportGWP
//join b in db.AssessmentReportVersion on a.ARversion equals b.ARversion
//where a.ARversion == arv
orderby a.ingredientName
select new ARnGWProwViewModel
{
ID=a.ID,
ingredientName=a.ingredientName,
chemicalFormula=a.chemicalFormula,
GWP100=(arv=="AR6"?a.AR6GWP100:(arv=="AR4"?a.AR4GWP100:a.AR5GWP100)),
ChineseName=a.ChineseName,
Alias=a.Alias,
GHGType=a.GHGType,
GWPtype=a.GWPtype
}).AsQueryable();
if (qry == null)
return View(viewModel );
var assessmentReportGWPs = qry.ToList();
var onePage = assessmentReportGWPs.ToPagedList(page, 10);
viewModel.ARnGWPlst = onePage;
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(ARnGWPvm viewModel)
{
switch (viewModel.cmd)
{
case "upload":
// 以下參考來自 c:\_git\weeecarbonfootprint\weee\Areas\admin\Controllers\ParameterController.cs
var errMsg = processExcelUpload(viewModel);
if (!string.IsNullOrEmpty(errMsg))
TempData["ErrMsg"] = viewModel.errMsg;
return RedirectToAction("Index", "ARnGWP", new { viewModel.arv });
case "download":
return processExcelDownload(db.AssessmentReportGWP.ToList());
}
return View(viewModel);
}
public ActionResult AR4()
{
return RedirectToAction("index", new { page = 1, arv = "AR4" });
}
public ActionResult AR5()
{
return RedirectToAction("index", new { page = 1, arv = "AR5" });
}
public ActionResult AR6()
{
return RedirectToAction("index", new { page = 1, arv = "AR6" });
}
public ActionResult Edit(int id, string arv="AR6")
{
var rq = Request.Form;
var qry =
(from a in db.AssessmentReportGWP
//join b in db.AssessmentReportVersion on a.ARversion equals b.ARversion
where a.ID == id
select new ARnGWProwViewModel
{
ID = a.ID,
ingredientName = a.ingredientName,
chemicalFormula = a.chemicalFormula,
GWP100 = (arv == "AR6" ? a.AR6GWP100 : (arv == "AR4" ? a.AR4GWP100 : a.AR5GWP100)),
ChineseName = a.ChineseName,
Alias = a.Alias,
GHGType = a.GHGType,
GWPtype = a.GWPtype
}).AsQueryable();
if (qry == null)
return HttpNotFound();
List<SelectListItem> selectGWPparameterType = new List<SelectListItem>();
selectGWPparameterType.Add(new SelectListItem() { Text = "", Value = "" });
selectGWPparameterType.Add(new SelectListItem() { Text = Resource.OtherCompound, Value = "0" });
selectGWPparameterType.Add(new SelectListItem() { Text = Resource.Refrigerant, Value = "1" });
selectGWPparameterType.Add(new SelectListItem() { Text = Resource.ParamemterCategoriesFireEquipment, Value = "2" });
selectGWPparameterType.Add(new SelectListItem() { Text = Resource.ParamemterCategoriesFireEquipment+'&'+Resource.Refrigerant, Value = "3" });
ViewBag.selectGWPparameterType = selectGWPparameterType;
return View(qry.Single());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, ARnGWProwViewModel viewModel, string arv = "AR6")
{
if (ModelState.IsValid)
{
if (viewModel.cmd=="cancel")
return RedirectToAction("index", new { page = 1, arv });
var ToBeEdit = db.AssessmentReportGWP.Single(x => x.ID == id);
ToBeEdit.ingredientName = viewModel.ingredientName;
ToBeEdit.chemicalFormula = viewModel.chemicalFormula;
switch (arv)
{
case "AR4":
ToBeEdit.AR4GWP100 = viewModel.GWP100;
break;
case "AR5":
ToBeEdit.AR5GWP100 = viewModel.GWP100;
break;
case "AR6":
ToBeEdit.AR6GWP100 = viewModel.GWP100;
break;
}
ToBeEdit.ChineseName = viewModel.ChineseName;
ToBeEdit.Alias = viewModel.Alias;
ToBeEdit.GHGType = viewModel.GHGType != null ? viewModel.GHGType : "";
ToBeEdit.GWPtype = viewModel.GWPtype;
ToBeEdit.modifyTime = DateTime.Now;
ToBeEdit.modifyBy = User.Identity.GetUserName();
db.SaveChanges();
return RedirectToAction("index", new { page = 1, arv });
}
return RedirectToAction("index", new { page = 1, arv });
}
public ActionResult Create(string arv = "AR6")
{
List<SelectListItem> selectGWPparameterType = new List<SelectListItem>();
selectGWPparameterType.Add(new SelectListItem() { Text = "", Value = "" });
selectGWPparameterType.Add(new SelectListItem() { Text = Resource.OtherCompound, Value = "0" });
selectGWPparameterType.Add(new SelectListItem() { Text = Resource.Refrigerant, Value = "1" });
selectGWPparameterType.Add(new SelectListItem() { Text = Resource.ParamemterCategoriesFireEquipment, Value = "2" });
selectGWPparameterType.Add(new SelectListItem() { Text = Resource.ParamemterCategoriesFireEquipment + '&' + Resource.Refrigerant, Value = "3" });
ViewBag.selectGWPparameterType = selectGWPparameterType;
var viewModel = new ARnGWProwViewModel();
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ARnGWProwViewModel viewModel, string arv = "AR6")
{
if (ModelState.IsValid)
{
var ToBeEdit = new AssessmentReportGWP();
ToBeEdit.ingredientName = viewModel.ingredientName;
ToBeEdit.chemicalFormula = viewModel.chemicalFormula;
switch (arv)
{
case "AR4":
ToBeEdit.AR4GWP100 = viewModel.GWP100;
ToBeEdit.AR5GWP100 = 0M;
ToBeEdit.AR6GWP100 = 0M;
break;
case "AR5":
ToBeEdit.AR5GWP100 = viewModel.GWP100;
ToBeEdit.AR4GWP100 = 0M;
ToBeEdit.AR6GWP100 = 0M;
break;
case "AR6":
ToBeEdit.AR6GWP100 = viewModel.GWP100;
ToBeEdit.AR4GWP100 = 0M;
ToBeEdit.AR5GWP100 = 0M;
break;
}
ToBeEdit.ChineseName = viewModel.ChineseName;
ToBeEdit.Alias = viewModel.Alias;
ToBeEdit.GHGType = viewModel.GHGType != null ? viewModel.GHGType : ""; ;
ToBeEdit.GWPtype = viewModel.GWPtype;
ToBeEdit.createTime = DateTime.Now;
ToBeEdit.createBy = User.Identity.GetUserName();
ToBeEdit.modifyTime = DateTime.Now;
ToBeEdit.modifyBy = User.Identity.GetUserName();
db.AssessmentReportGWP.Add(ToBeEdit);
db.SaveChanges();
return RedirectToAction("index", new { page = 1, arv });
}
return RedirectToAction("index", new { page = 1, arv });
}
public ActionResult Delete(int id, string arv = "AR6")
{
var toBeRemove = db.AssessmentReportGWP.Find(id);
db.AssessmentReportGWP.Remove(toBeRemove);
db.SaveChanges();
return RedirectToAction("index", new { page = 1, arv });
}
public ActionResult DeleteAll()
{
try
{
db.AssessmentReportGWP.RemoveRange(db.AssessmentReportGWP.ToList());
db.SaveChanges();
}
catch (Exception ex)
{
TempData["ErrMsg"] = ex.Message;
}
return RedirectToAction("Index", "ARnGWP", new { });
}
private FileStreamResult processExcelDownload(List<AssessmentReportGWP> data)
{
XLWorkbook excelWorkbook = new XLWorkbook(); // 寫資料進excelWorkbook
string sheetName = "All GHG Values";
var worksheet = excelWorkbook.Worksheets.Add(sheetName);
int rowTh;
var provider = ModelMetadataProviders.Current;
worksheet.Cell($"A1").Value = "Chemical Formula";
worksheet.Cell($"B1").Value = "Name";
worksheet.Cell($"C1").Value = "Chinese-Name";
worksheet.Cell($"D1").Value = "AR6-GWP100";
worksheet.Cell($"E1").Value = "AR5-GWP100";
worksheet.Cell($"F1").Value = "AR4-GWP100";
worksheet.Cell($"G1").Value = "Alias";
worksheet.Cell($"H1").Value = "GHG Type";
worksheet.Cell($"I1").Value = "冷媒1/滅火器2/冷媒&滅火器3";
rowTh = 2;
foreach (AssessmentReportGWP oneData in data)
{
worksheet.Cell($"A{rowTh}").Value = $"{oneData.chemicalFormula}";
worksheet.Cell($"B{rowTh}").Value = $"{oneData.ingredientName}";
worksheet.Cell($"C{rowTh}").Value = $"{oneData.ChineseName}";
worksheet.Cell($"D{rowTh}").Value = oneData.AR6GWP100;
worksheet.Cell($"E{rowTh}").Value = oneData.AR5GWP100;
worksheet.Cell($"F{rowTh}").Value = oneData.AR4GWP100;
worksheet.Cell($"G{rowTh}").Value = $"{oneData.Alias}";
worksheet.Cell($"H{rowTh}").Value = $"{oneData.GHGType}";
worksheet.Cell($"I{rowTh}").Value = (int)oneData.GWPtype;
rowTh++;
}
string myName = Server.UrlEncode(Resources.Resource.GWPFactor.Replace(' ', '_')
+ $"_{sheetName}_" + DateTime.Today.ToString("yyyyMMdd") + ".xlsx");
MemoryStream stream = new MemoryStream();
excelWorkbook.SaveAs(stream);
stream.Position = 0;
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + myName);
Response.ContentType = "application/vnd.ms-excel";
Response.BinaryWrite(stream.ToArray());
Response.End();
return new FileStreamResult(stream, MediaTypeNames.Application.Octet);
}
private string processExcelUpload(ARnGWPvm sour)
{
string err = "";
try
{
var exlVmList = GetExcelData(sour.uploadExcelFile);
exlVmList = exlVmList.ToList();
if (exlVmList != null && exlVmList.Count() > 0)
{
if (CkExcelData(exlVmList, out string ckErr))
SaveExelData(exlVmList);
else
throw new Exception(ckErr);
}
}
catch (Exception ex)
{
ex = CScommon.Exceptions.inner(ex);
err = ex.Message;
}
return err;
}
private List<ARnGWPExcelViewModel> GetExcelData(HttpPostedFileBase uploadExcelFile)
{
var re = new List<ARnGWPExcelViewModel>();
if (uploadExcelFile == null || uploadExcelFile.InputStream == null || uploadExcelFile.InputStream.Length == 0)
throw new Exception($"未指定上傳檔案!");
else
{
string extesion = uploadExcelFile.FileName.Substring(uploadExcelFile.FileName.LastIndexOf(".") + 1);
if (extesion.ToLower() != "xlsx")
throw new Exception("僅支持xlsx類型!");
using (XLWorkbook workBook = new XLWorkbook(uploadExcelFile.InputStream))
{
IXLWorksheet workSheet = workBook.Worksheet(1);
if (workSheet == null)
throw new Exception($"檔案錯誤, sheet 不存在!");
int ith = 0;
foreach (IXLRow row in workSheet.Rows())
{
ith++;
if (ith == 1)
continue; // skip first row
var exlIt = new ARnGWPExcelViewModel();
//chemicalFormula
string cellA = workSheet.Cell($"A{ith}").Value.ToString().Trim();
exlIt.chemicalFormula = cellA;
//ingredientName
string cellB = workSheet.Cell($"B{ith}").Value.ToString().Trim();
exlIt.ingredientName = cellB;
//ChineseName
string cellC = workSheet.Cell($"C{ith}").Value.ToString().Trim();
exlIt.ChineseName = cellC;
//AR6GWP100
string cellD = workSheet.Cell($"D{ith}").Value.ToString().Trim();
exlIt.AR6GWP100 = GetFromExcel(cellD);
//AR5GWP100
string cellE = workSheet.Cell($"E{ith}").Value.ToString().Trim();
exlIt.AR5GWP100 = GetFromExcel(cellE);
//AR4GWP100
string cellF = workSheet.Cell($"F{ith}").Value.ToString().Trim(); ;
exlIt.AR4GWP100 = GetFromExcel(cellF);
//Alias
string cellG = workSheet.Cell($"G{ith}").Value.ToString().Trim();
exlIt.Alias = cellG;
//GHGType
string cellH = workSheet.Cell($"H{ith}").Value.ToString().Trim();
exlIt.GHGType = cellH;
//GWPtype
string cellI = workSheet.Cell($"I{ith}").Value.ToString().Trim();
int GWPtype = 0;
int.TryParse(cellI, out GWPtype);
exlIt.GWPtype = GWPtype;
if(!(cellB.Equals("") && exlIt.AR4GWP100 == 0 && exlIt.AR5GWP100 == 0 && exlIt.AR6GWP100 == 0))
{
re.Add(exlIt);
}
}
}
}
return re;
}
private bool CkExcelData(List<ARnGWPExcelViewModel> sour, out string errMsg)
{
errMsg = "";
var errList = new List<string>();
if (sour == null && sour.Count() == 0)
{
errMsg = "資料不可為空";
return false;
}
if (errList != null && errList.Count() > 0)
{
errMsg = String.Join(",", errList);
return false;
}
return true;
}
private void SaveExelData(List<ARnGWPExcelViewModel> sour)
{
string err = "";
var transac = db.Database.BeginTransaction();
try
{
if (sour != null && sour.Count() > 0)
{
foreach (var it in sour)
{
bool existed = true;
var ToBeAdded = db.AssessmentReportGWP.Where(x => x.ingredientName.Equals(it.ingredientName)).FirstOrDefault();
if(ToBeAdded == null)
{
ToBeAdded = new AssessmentReportGWP();
existed = false;
}
ToBeAdded.ingredientName = it.ingredientName;
ToBeAdded.chemicalFormula = it.chemicalFormula;
ToBeAdded.AR4GWP100 = it.AR4GWP100;
ToBeAdded.AR5GWP100 = it.AR5GWP100;
ToBeAdded.AR6GWP100 = it.AR6GWP100;
ToBeAdded.ChineseName = it.ChineseName;
ToBeAdded.Alias = it.Alias;
ToBeAdded.GHGType = it.GHGType;
ToBeAdded.GWPtype = (GWPparameterType) it.GWPtype;
ToBeAdded.modifyTime = DateTime.Now;
ToBeAdded.modifyBy = User.Identity.GetUserName();
if (!existed)
{
ToBeAdded.createTime = DateTime.Now;
ToBeAdded.createBy = User.Identity.GetUserName();
db.AssessmentReportGWP.Add(ToBeAdded);
}
db.SaveChanges();
}
transac.Commit();
}
}
catch (Exception ex)
{
ex = CScommon.Exceptions.inner(ex);
err = ex.Message;
transac.Rollback();
throw ex;
}
}
public decimal GetFromExcel(string sour)
{
if (string.IsNullOrWhiteSpace(sour))
return 0;
if (!Decimal.TryParse(sour, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out decimal Value))
throw new Exception(sour + " not number");
return Value;
}
}
}