using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using SolarPower.Models;
using SolarPower.Models.PowerStation;
using SolarPower.Models.Role;
using SolarPower.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SolarPower.Controllers
{
    public class StationReportController : MyBaseController<StationReportController>
    {
        private readonly IPowerStationRepository powerStationRepository;
        private readonly IStationReportRepository stationReportRepository;

        public StationReportController(IPowerStationRepository powerStationRepository, IStationReportRepository stationReportRepository) : base()
        {
            this.powerStationRepository = powerStationRepository;
            this.stationReportRepository = stationReportRepository;
        }
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ApiResult<Dictionary<string,List<PowerStation>>> GetPowerStationCollapse(string filter)
        {
            ApiResult<Dictionary<string, List<PowerStation>>> apiResult = new ApiResult<Dictionary<string, List<PowerStation>>>();
            try
            {
                List<string> where = new List<string>();
                Dictionary<string, object> where_entities = new Dictionary<string, object>();
                if (!string.IsNullOrEmpty(filter))
                {
                    var temp_psname_where = $@" ps.Name LIKE CONCAT('%', @Filter, '%')";
                    where.Add(temp_psname_where);

                    where_entities.Add("Filter", filter);
                }

                var powerStations = myPowerStationService.GetMyPowerStations(myUser, 1, null, where, where_entities);

                var siteDBNamePowerStationId = new Dictionary<string, List<PowerStation>>();

                var powerStation_Group = powerStations.GroupBy(x => x.CityName).ToList();
                foreach (var stations in powerStation_Group)
                {
                    siteDBNamePowerStationId.Add(stations.Key, stations.ToList());
                }

                apiResult.Code = "0000";

                apiResult.Data = siteDBNamePowerStationId;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                Logger.LogError("【" + controllerName + "/" + actionName + "】");
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            apiResult.Msg = errorCode.GetString(apiResult.Code);
            return apiResult;
        }

        public async Task<ApiResult<InvAndMoney>> GetTableHead(Select_table post)
        {
            ApiResult<InvAndMoney> apiResult = new ApiResult<InvAndMoney>();
            InvAndMoney inverter = new InvAndMoney();
            bool Showmoney;
            if(post.Userid == 0)
            {
                Showmoney = myUser.Role.Auths.Contains("ShowMoney");
            }
            else
            {
                Showmoney = await powerStationRepository.CheckShowMoney(post.Userid);
            }


            try
            {
                var powerStation = await powerStationRepository.GetOneAsync(post.PowerStation);
                if(powerStation == null)
                {
                    apiResult.Code = "0001";
                    apiResult.Msg = "需加入查詢電站";
                    return apiResult;
                }

                if(post.FormType != 2)
                {
                    inverter.Inv = await stationReportRepository.GetInverterId(powerStation.SiteDB, post);
                    for (int i = 0; i < inverter.Inv.Count; i++)
                    {
                        inverter.Inv[i] = "inv_" + inverter.Inv[i].Substring(inverter.Inv[i].Length - 2, 2);
                    }
                }
                if (Showmoney)
                {
                    inverter.ShowMoney = 1;
                }else
                {
                    inverter.ShowMoney = 0;
                }
                apiResult.Code = "0000";
                apiResult.Data = inverter;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                Logger.LogError("【" + controllerName + "/" + actionName + "】");
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return apiResult;
        }

        public async Task<ApiResult<dynamic>> GetForm(Select_table post)
        {
            ApiResult<dynamic> apiResult = new ApiResult<dynamic>();
            try
            {
                
                var checkinv = stationReportRepository.Findhaveinv(post);
                var getinvsql = checkinv.Result[0] as IDictionary<string, object>;
                if (getinvsql["mySelect"] == null)
                {
                    apiResult.Code = "9985";
                    apiResult.Msg = errorCode.GetString(apiResult.Code);
                }
                else
                {
                    var a = await stationReportRepository.Gettablebody(post);
                    apiResult.Code = "0000";
                    apiResult.Data = a;
                }
                
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                Logger.LogError("【" + controllerName + "/" + actionName + "】");
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return apiResult;
        }

        public FileResult ExportExcel(string post)
        {
            var postObject = JsonConvert.DeserializeObject<Excel>(post);
            var workbook = new XSSFWorkbook();
            #region excel設定
            IFont font12 = workbook.CreateFont();
            font12.FontName = "新細明體";
            font12.FontHeightInPoints = 12;
            ICellStyle style12 = workbook.CreateCellStyle();
            style12.SetFont(font12);
            style12.Alignment = HorizontalAlignment.Center;
            style12.VerticalAlignment = VerticalAlignment.Center;
            IFont font12Times = workbook.CreateFont();
            font12Times.FontName = "Times New Roman";
            font12Times.FontHeightInPoints = 12;
            IFont font18 = workbook.CreateFont();
            font18.FontName = "新細明體";
            font18.FontHeightInPoints = 18;
            font18.IsBold = true;
            ICellStyle styleTitle18 = workbook.CreateCellStyle();
            styleTitle18.SetFont(font18);
            styleTitle18.Alignment = HorizontalAlignment.Center;
            styleTitle18.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLeft12 = workbook.CreateCellStyle();
            styleLeft12.SetFont(font12);
            styleLeft12.Alignment = HorizontalAlignment.Left;
            styleLeft12.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLine12 = workbook.CreateCellStyle();
            styleLine12.SetFont(font12);
            styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            styleLine12.VerticalAlignment = VerticalAlignment.Center;
            styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            ICellStyle stylein12 = workbook.CreateCellStyle();
            stylein12.SetFont(font12Times);
            stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
            stylein12.VerticalAlignment = VerticalAlignment.Center;
            stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.WrapText = true;
            #endregion
            foreach (var powerstationid in postObject.PowerStation)
            {
                var sheet = workbook.CreateSheet(powerstationid.Name);
                Select_table select_Table = new Select_table
                {
                    FormType = postObject.FormType,
                    SearchType = postObject.SearchType,
                    Time = postObject.Time,
                    PowerStation = Convert.ToInt32(powerstationid.Value),
                    Userid = postObject.Userid
                };
                var Formbody = GetForm(select_Table);//取body
                var Formhead = GetTableHead(select_Table);//取head
                int RowPosition = 0;

                switch (postObject.FormType)
                {
                    case 0: //日報表
                        #region 顯示head //RowPosition = 0
                        IRow row = sheet.CreateRow(RowPosition);
                        ICell cell = row.CreateCell(0);
                        int index = 0;
                        cell.SetCellValue("Date");
                        cell.CellStyle = styleLine12;
                        sheet.SetColumnWidth(index, 4 * 160 * 8);
                        index++;

                        foreach (var head in Formhead.Result.Data.Inv)
                        {
                            cell = row.CreateCell(index);
                            cell.SetCellValue(head);
                            cell.CellStyle = styleLine12;
                            sheet.SetColumnWidth(index, 4 * 160 * 6);
                            index++;
                        }

                        List<string> lasthead = new List<string>()
                        {
                            "小時發電量(kWh)",
                            "小時發電量百分比(%)",
                            "累積日照度(Wh/㎡)",
                            "小時平均模組溫度(°C)"
                        };
                        if(Formhead.Result.Data.ShowMoney == 1)
                        {
                            lasthead.Add("小時售電金額(NTD)");
                        }



                        foreach (var head in lasthead)
                        {
                            cell = row.CreateCell(index);
                            cell.SetCellValue(head);
                            cell.CellStyle = styleLine12;
                            sheet.SetColumnWidth(index, 4 * 160 * 12);
                            index++;
                        }
                        #endregion

                        #region 顯示body //RowPosition = 1
                        RowPosition++;
                        var thour = ""; var tpr = ""; var tkwh = ""; var kWhkwp = ""; var ntd = ""; var ntdone = "";var GeneratingCapacity = "";var AverageDailyProfit = "";
                        foreach (dynamic body in Formbody.Result.Data)
                        {
                            index = 0;
                            var dbody = body as IDictionary<string, object>;
                            thour = Checknull(Math.Round(Convert.ToDouble(dbody["tothour"]), 2).ToString());
                            tpr = Checknull(Math.Round(Convert.ToDouble(dbody["pr"]), 2).ToString());
                            tkwh = Checknull(Math.Round(Convert.ToDouble(dbody["totKWH"]), 2).ToString());
                            kWhkwp = Checknull(Math.Round(Convert.ToDouble(dbody["totKWHKWP"]), 2).ToString());
                            ntd = Checknull(Math.Round(Convert.ToDouble(dbody["totmoney"]), 2).ToString());
                            GeneratingCapacity = Checknull(Math.Round(Convert.ToDouble(dbody["GeneratingCapacity"]), 2).ToString());

                            double onemoney = Convert.ToDouble(ntd) / Convert.ToDouble(tkwh);
                            if (double.IsNaN(onemoney))
                            {
                                onemoney = 0;
                            }
                            ntdone = Checknull(Math.Round(onemoney, 4).ToString());
                            AverageDailyProfit = Checknull(Math.Round((Convert.ToDouble(ntd) / Convert.ToDouble(GeneratingCapacity)), 2).ToString());

                            row = sheet.CreateRow(RowPosition);
                            cell = row.CreateCell(index);
                            var b = dbody["report_date"].ToString();
                            cell.SetCellValue(b);
                            cell.CellStyle = styleLine12;
                            index++;
                            foreach (var head in Formhead.Result.Data.Inv)
                            {
                                cell = row.CreateCell(index);
                                cell.SetCellValue(dbody[head] == null ? 0 : Convert.ToDouble(dbody[head].ToString()));
                                cell.CellStyle = styleLine12;
                                index++;
                            }
                            List<string> bodynames = new List<string>(){
                                "hourKWH",
                                "hourKWHp",
                                "irradiance",
                                "temperature"
                                };
                            if (Formhead.Result.Data.ShowMoney == 1)
                            {
                                bodynames.Add("hourmoney");
                            }
                            foreach (var bodyname in bodynames)
                            {
                                cell = row.CreateCell(index);
                                if (dbody[bodyname] == null)
                                {
                                    cell.SetCellValue(0);
                                }
                                else
                                {
                                    var c = dbody[bodyname].ToString();
                                    cell.SetCellValue(Convert.ToDouble(c));
                                }
                                cell.CellStyle = styleLine12;
                                index++;
                            }
                            RowPosition++;
                        }
                        #endregion

                        #region 顯示總量//RowPosition = body + 2
                        RowPosition += 2;//空兩行
                        //index = 0;
                        //row = sheet.CreateRow(RowPosition);
                        //cell = row.CreateCell(index);
                        //cell.SetCellValue("日照小時:");
                        //cell.CellStyle = styleLine12;
                        //cell = row.CreateCell(1);
                        //cell.SetCellValue(Convert.ToDouble(thour));
                        //cell.CellStyle = styleLine12;
                        //RowPosition++;

                        index = 0;
                        row = sheet.CreateRow(RowPosition);
                        cell = row.CreateCell(index);
                        cell.SetCellValue("日均發電度數:");
                        cell.CellStyle = styleLine12;
                        cell = row.CreateCell(1);
                        cell.SetCellValue(Convert.ToDouble(kWhkwp));
                        cell.CellStyle = styleLine12;
                        RowPosition++;

                        index = 0;
                        row = sheet.CreateRow(RowPosition);
                        cell = row.CreateCell(index);
                        cell.SetCellValue("PR%:");
                        cell.CellStyle = styleLine12;
                        cell = row.CreateCell(1);
                        cell.SetCellValue(Convert.ToDouble(tpr));
                        cell.CellStyle = styleLine12;
                        RowPosition++;


                        index = 0;
                        row = sheet.CreateRow(RowPosition);
                        cell = row.CreateCell(index);
                        cell.SetCellValue("日發電量(kWh):");
                        cell.CellStyle = styleLine12;
                        cell = row.CreateCell(1);
                        cell.SetCellValue(Convert.ToDouble(tkwh));
                        cell.CellStyle = styleLine12;
                        RowPosition++;

                        index = 0;
                        row = sheet.CreateRow(RowPosition);
                        cell = row.CreateCell(index);
                        cell.SetCellValue("裝置容量:");
                        cell.CellStyle = styleLine12;
                        cell = row.CreateCell(1);
                        cell.SetCellValue(Convert.ToDouble(GeneratingCapacity));
                        cell.CellStyle = styleLine12;
                        RowPosition++;

                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            index = 0;
                            row = sheet.CreateRow(RowPosition);
                            cell = row.CreateCell(index);
                            cell.SetCellValue("日售電金額(NTD):");
                            cell.CellStyle = styleLine12;
                            cell = row.CreateCell(1);
                            cell.SetCellValue(Convert.ToDouble(ntd));
                            cell.CellStyle = styleLine12;
                            RowPosition++;

                            index = 0;
                            row = sheet.CreateRow(RowPosition);
                            cell = row.CreateCell(index);
                            cell.SetCellValue("日售電單價(NTD):");
                            cell.CellStyle = styleLine12;
                            cell = row.CreateCell(1);
                            cell.SetCellValue(Convert.ToDouble(ntdone));
                            cell.CellStyle = styleLine12;
                            RowPosition++;

                            index = 0;
                            row = sheet.CreateRow(RowPosition);
                            cell = row.CreateCell(index);
                            cell.SetCellValue("日均獲利(NTD):");
                            cell.CellStyle = styleLine12;
                            cell = row.CreateCell(1);
                            cell.SetCellValue(Convert.ToDouble(AverageDailyProfit));
                            cell.CellStyle = styleLine12;
                        }

                        

                        #endregion
                        break;
                    case 1: // 月報表
                        #region 顯示head //RowPosition = 0
                        IRow row2 = sheet.CreateRow(RowPosition);
                        ICell cell2 = row2.CreateCell(0);
                        int index2 = 0;
                        cell2.SetCellValue("Date");
                        cell2.CellStyle = styleLine12;
                        sheet.SetColumnWidth(index2, 4 * 160 * 8);
                        index2++;

                        foreach (var head in Formhead.Result.Data.Inv)
                        {
                            cell2 = row2.CreateCell(index2);
                            cell2.SetCellValue(head);
                            cell2.CellStyle = styleLine12;
                            sheet.SetColumnWidth(index2, 4 * 160 * 8);
                            index2++;
                        }

                        List<string> lasthead2 = new List<string>()
                        {
                            "日發電量(kWh)",
                            "日發電量百分比(%)",
                            "日照小時(hr)",
                            "日均發電度數",
                            "PR%",
                            "累積日照度(Wh/㎡)",
                            "日平均模組溫度(°C)"
                            
                        };
                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            lasthead2.Add("日售電金額(NTD)");
                        }
                        foreach (var head in lasthead2)
                        {
                            cell2 = row2.CreateCell(index2);
                            cell2.SetCellValue(head);
                            cell2.CellStyle = styleLine12;
                            sheet.SetColumnWidth(index2, 4 * 160 * 12);
                            index2++;
                        }
                        #endregion

                        #region 顯示body //RowPosition = 1
                        RowPosition++;
                        var avghour = "0"; var avgKWHKWP = "0"; var avgdayKWH = "0"; var monthKWH = "0"; var monthmoney = "0"; var monthmoneyone = "0";
                        var monthGeneratingCapacity = "";
                        var check_hire = false;
                        var sitedb = "";
                        foreach (dynamic body in Formbody.Result.Data)
                        {
                            index2 = 0;
                            var dbody = body as IDictionary<string, object>;

                            avghour = (Convert.ToDouble(dbody["tothour"].ToString()) + Convert.ToDouble(avghour)).ToString();
                            avgKWHKWP = (Convert.ToDouble(dbody["KWHKWP"].ToString()) + Convert.ToDouble(avgKWHKWP)).ToString();
                            avgdayKWH = (Convert.ToDouble(dbody["dayKWH"].ToString()) + Convert.ToDouble(avgdayKWH)).ToString();
                            monthKWH = dbody["monthKWH"] == null ? "0": dbody["monthKWH"].ToString();
                            monthmoney = dbody["monthmoney"] == null ? "0" : dbody["monthmoney"].ToString();
                            monthmoneyone = (Convert.ToDouble(dbody["monthmoneyone"].ToString()) + Convert.ToDouble(monthmoneyone)).ToString();
                            monthGeneratingCapacity = Checknull(Math.Round(Convert.ToDouble(dbody["GeneratingCapacity"]), 2).ToString());
                            if (dbody["SolarType"].ToString() == "1" && Formhead.Result.Data.ShowMoney == 1)//檢驗是否為租用
                            {
                                check_hire = true;
                                sitedb = dbody["SiteDB"].ToString();
                            }

                            row2 = sheet.CreateRow(RowPosition);
                            cell2 = row2.CreateCell(index2);
                            var b = dbody["report_date"].ToString();
                            cell2.SetCellValue(b);
                            cell2.CellStyle = styleLine12;
                            index2++;
                            foreach (var head in Formhead.Result.Data.Inv)
                            {
                                cell2 = row2.CreateCell(index2);
                                cell2.SetCellValue(dbody[head] == null ? 0 : Convert.ToDouble(dbody[head].ToString()));
                                cell2.CellStyle = styleLine12;
                                index2++;
                            }
                            List<string> bodynames = new List<string>(){
                                "dayKWH",
                                "dayKWHp",
                                "tothour",
                                "KWHKWP",
                                "PR",
                                "IrrDay",
                                "temperature"
                                };
                            if (Formhead.Result.Data.ShowMoney == 1)
                            {
                                bodynames.Add("soldmoney");
                            }
                            foreach (var bodyname in bodynames)
                            {
                                cell2 = row2.CreateCell(index2);
                                if (dbody[bodyname] == null)
                                {
                                    cell2.SetCellValue(0);
                                }
                                else
                                {
                                    var c = dbody[bodyname].ToString();
                                    cell2.SetCellValue(Convert.ToDouble(c));
                                }
                                cell2.CellStyle = styleLine12;
                                index2++;
                            }
                            RowPosition++;
                        }
                        #endregion

                        #region 顯示總量//RowPosition = body + 2
                        RowPosition += 2;//空兩行
                        index = 0;
                        var Useday = Formbody.Result.Data.Count;
                        row = sheet.CreateRow(RowPosition);

                        //cell = row.CreateCell(index);
                        //cell.SetCellValue("日照平均(日)");
                        //cell.CellStyle = styleLine12;
                        //index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("日均發電度數(日)");
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("發電量平均(kWh)(日)");
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("發電量(kWh)(月)");
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("裝置容量");
                        cell.CellStyle = styleLine12;
                        index++;
                        
                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            cell = row.CreateCell(index);
                            cell.SetCellValue("每度獲利");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("售電金額(NTD)(月)");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("售電單價(NTD)(月)");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("日均獲利(NTD)");
                            cell.CellStyle = styleLine12;
                            index++;
                        }
                        cell = row.CreateCell(index);
                        cell.SetCellValue("售電天數(月)");
                        cell.CellStyle = styleLine12;



                        index = 0;
                        RowPosition++;
                        row = sheet.CreateRow(RowPosition);

                        //cell = row.CreateCell(index);
                        //cell.SetCellValue(Math.Round(Convert.ToDouble(avghour)/Useday,2));
                        //cell.CellStyle = styleLine12;
                        //index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Math.Round(Convert.ToDouble(avgKWHKWP) / Useday,2));
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Math.Round(Convert.ToDouble(avgdayKWH) / Useday,2));
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Convert.ToDouble(monthKWH));
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Convert.ToDouble(monthGeneratingCapacity));
                        cell.CellStyle = styleLine12;
                        index++;
                        
                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) / Convert.ToDouble(monthGeneratingCapacity), 3));
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Convert.ToDouble(monthmoney));
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoneyone) / Useday, 4));
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) / Convert.ToDouble(monthGeneratingCapacity) / Useday, 2));
                            cell.CellStyle = styleLine12;
                            index++;
                        }
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Useday);
                        cell.CellStyle = styleLine12;
                        #endregion

                        #region 顯示租用//RowPosition = 總量 + 2
                        if (check_hire == true)
                        {
                            RowPosition += 2;//空兩行
                            PsIdAndSiteDB set = new PsIdAndSiteDB()
                            {
                                PowerstationId = Convert.ToInt32(powerstationid.Value),
                                SiteDB = sitedb
                            };
                            var info = GetHireInfo(set);
                            index = 0;
                            row = sheet.CreateRow(RowPosition);

                            cell = row.CreateCell(index);
                            cell.SetCellValue("出租人");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("租金比例");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("租金金額(未稅)");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("租金金額(含稅)");
                            cell.CellStyle = styleLine12;

                            foreach(var a in info.Result.Data)
                            {
                                RowPosition++;
                                index = 0;
                                row = sheet.CreateRow(RowPosition);

                                cell = row.CreateCell(index);
                                cell.SetCellValue(a.Landowner);
                                cell.CellStyle = styleLine12;
                                index++;
                                cell = row.CreateCell(index);
                                cell.SetCellValue(a.LeaseRate + "%");
                                cell.CellStyle = styleLine12;
                                index++;
                                cell = row.CreateCell(index);
                                cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) * Convert.ToDouble(a.LeaseRate) /100,2));
                                cell.CellStyle = styleLine12;
                                index++;
                                cell = row.CreateCell(index);
                                cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) * Convert.ToDouble(a.LeaseRate) / 100 * 1.05, 2));
                                cell.CellStyle = styleLine12;
                                index++;
                            }


                            
                            
                            
                        }
                        #endregion
                        break;
                    case 3: // 年報表
                        #region 顯示head //RowPosition = 0
                        IRow row3 = sheet.CreateRow(RowPosition);
                        ICell cell3 = row3.CreateCell(0);
                        int index3 = 0;
                        cell3.SetCellValue("Date");
                        cell3.CellStyle = styleLine12;
                        sheet.SetColumnWidth(index3, 4 * 160 * 8);
                        index3++;

                        foreach (var head in Formhead.Result.Data.Inv)
                        {
                            cell3 = row3.CreateCell(index3);
                            cell3.SetCellValue(head);
                            cell3.CellStyle = styleLine12;
                            sheet.SetColumnWidth(index3, 4 * 160 * 8);
                            index3++;
                        }

                        List<string> lasthead3 = new List<string>()
                        {
                            "月發電量(kWh)",
                            "月發電量百分比(%)",
                            "日照小時(hr)",
                            "日均發電度數",
                            "PR%",
                            "累積日照度(Wh/㎡)",
                            "月平均模組溫度(°C)"

                        };
                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            lasthead3.Add("月售電金額(NTD)");
                        }
                        foreach (var head in lasthead3)
                        {
                            cell3 = row3.CreateCell(index3);
                            cell3.SetCellValue(head);
                            cell3.CellStyle = styleLine12;
                            sheet.SetColumnWidth(index3, 4 * 160 * 12);
                            index3++;
                        }
                        #endregion

                        #region 顯示body //RowPosition = 1
                        RowPosition++;
                        avghour = "0"; avgKWHKWP = "0"; avgdayKWH = "0"; monthKWH = "0"; monthmoney = "0"; monthmoneyone = "0";
                         check_hire = false;
                        sitedb = "";
                        monthGeneratingCapacity = "";
                        foreach (dynamic body in Formbody.Result.Data)
                        {
                            index3 = 0;
                            var dbody = body as IDictionary<string, object>;

                            avghour = (Convert.ToDouble(dbody["tothour"].ToString()) + Convert.ToDouble(avghour)).ToString();
                            avgKWHKWP = (Convert.ToDouble(dbody["KWHKWP"].ToString()) + Convert.ToDouble(avgKWHKWP)).ToString();
                            avgdayKWH = (Convert.ToDouble(dbody["dayKWH"].ToString()) + Convert.ToDouble(avgdayKWH)).ToString();
                            monthKWH = dbody["monthKWH"] == null ? "0" : dbody["monthKWH"].ToString();
                            monthmoney = dbody["monthmoney"] == null ? "0" : dbody["monthmoney"].ToString();
                            monthmoneyone = (Convert.ToDouble(dbody["monthmoneyone"].ToString()) + Convert.ToDouble(monthmoneyone)).ToString();
                            monthGeneratingCapacity = Checknull(Math.Round(Convert.ToDouble(dbody["GeneratingCapacity"]), 2).ToString());
                            if (dbody["SolarType"].ToString() == "1" && Formhead.Result.Data.ShowMoney == 1)//檢驗是否為租用
                            {
                                check_hire = true;
                                sitedb = dbody["SiteDB"].ToString();
                            }

                            row3 = sheet.CreateRow(RowPosition);
                            cell3 = row3.CreateCell(index3);
                            var b = dbody["report_date"].ToString();
                            cell3.SetCellValue(b);
                            cell3.CellStyle = styleLine12;
                            index3++;
                            foreach (var head in Formhead.Result.Data.Inv)
                            {
                                cell3 = row3.CreateCell(index3);
                                cell3.SetCellValue(dbody[head] == null ? 0 : Convert.ToDouble(dbody[head].ToString()));
                                cell3.CellStyle = styleLine12;
                                index3++;
                            }
                            List<string> bodynames = new List<string>(){
                                "dayKWH",
                                "dayKWHp",
                                "tothour",
                                "KWHKWP",
                                "PR",
                                "irradiance",
                                "temperature"
                                };
                            if (Formhead.Result.Data.ShowMoney == 1)
                            {
                                bodynames.Add("soldmoney");
                            }
                            foreach (var bodyname in bodynames)
                            {
                                cell3 = row3.CreateCell(index3);
                                if (dbody[bodyname] == null)
                                {
                                    cell3.SetCellValue(0);
                                }
                                else
                                {
                                    var c = dbody[bodyname].ToString();
                                    cell3.SetCellValue(Convert.ToDouble(c));
                                }
                                cell3.CellStyle = styleLine12;
                                index3++;
                            }
                            RowPosition++;
                        }
                        #endregion

                        #region 顯示總量//RowPosition = body + 2
                        RowPosition += 2;//空兩行
                        index = 0;
                        Useday = Formbody.Result.Data.Count;
                        row = sheet.CreateRow(RowPosition);

                        cell = row.CreateCell(index);
                        cell.SetCellValue("日照平均(月)");
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("平均日均發電度數(月)");
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("發電量平均(kWh)(月)");
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("發電量(kWh)(年)");
                        cell.CellStyle = styleLine12;
                        index++;
                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            cell = row.CreateCell(index);
                            cell.SetCellValue("售電金額(NTD)(年)");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("售電單價(NTD)(年)");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("日均獲利(NTD)");
                            cell.CellStyle = styleLine12;
                            index++;
                        }
                        cell = row.CreateCell(index);
                        cell.SetCellValue("售電月數(年)");
                        cell.CellStyle = styleLine12;



                        index = 0;
                        RowPosition++;
                        row = sheet.CreateRow(RowPosition);

                        cell = row.CreateCell(index);
                        cell.SetCellValue(Math.Round(Convert.ToDouble(avghour) / Useday, 2));
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Math.Round(Convert.ToDouble(avgKWHKWP) / Useday, 2));
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Math.Round(Convert.ToDouble(avgdayKWH) / Useday, 2));
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Convert.ToDouble(monthKWH));
                        cell.CellStyle = styleLine12;
                        index++;
                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Convert.ToDouble(monthmoney));
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoneyone) / Useday, 2));
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) / Convert.ToDouble(monthGeneratingCapacity) / Useday / 30, 2));//一個月為30天
                            cell.CellStyle = styleLine12;
                            index++;
                        }
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Useday);
                        cell.CellStyle = styleLine12;
                        #endregion

                        #region 顯示租用//RowPosition = 總量 + 2
                        if (check_hire == true)
                        {
                            RowPosition += 2;//空兩行
                            PsIdAndSiteDB set = new PsIdAndSiteDB()
                            {
                                PowerstationId = Convert.ToInt32(powerstationid.Value),
                                SiteDB = sitedb
                            };
                            var info = GetHireInfo(set);
                            index = 0;
                            row = sheet.CreateRow(RowPosition);

                            cell = row.CreateCell(index);
                            cell.SetCellValue("出租人");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("租金比例");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("租金金額(未稅)");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("租金金額(含稅)");
                            cell.CellStyle = styleLine12;

                            foreach (var a in info.Result.Data)
                            {
                                RowPosition++;
                                index = 0;
                                row = sheet.CreateRow(RowPosition);

                                cell = row.CreateCell(index);
                                cell.SetCellValue(a.Landowner);
                                cell.CellStyle = styleLine12;
                                index++;
                                cell = row.CreateCell(index);
                                cell.SetCellValue(a.LeaseRate + "%");
                                cell.CellStyle = styleLine12;
                                index++;
                                cell = row.CreateCell(index);
                                cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) * Convert.ToDouble(a.LeaseRate) / 100, 2));
                                cell.CellStyle = styleLine12;
                                index++;
                                cell = row.CreateCell(index);
                                cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) * Convert.ToDouble(a.LeaseRate) / 100 * 1.05, 2));
                                cell.CellStyle = styleLine12;
                                index++;
                            }





                        }
                        #endregion
                        break;
                }

            }
            var name = "";
            if(postObject.FormType == 0)
            {
                name = "日";
            }
            else if(postObject.FormType == 1)
            {
                if(postObject.SearchType == 2)
                {
                    name = "月";
                }
                else
                {
                    name = "區間";
                }
                
            }
            else if (postObject.FormType == 3)
            {
                name = "年";
            }

            var ms = new NpoiMemoryStream
            {
                AllowClose = false
            };
            string companyName = postObject.PowerStation[0].Name;
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            var Datename = postObject.Time.Replace("-", "");
            return File(ms, "application/vnd.ms-excel", companyName + "_" + name + "報表" + "_" + postObject.Userid + Datename + ".xlsx");
        }

        public string Checknull(string a)
        {
            if(a == null)
            {
                return "0";

            }else
            {
                return a;
            }
        }

        public async Task<ApiResult<List<Landinfo>>> GetHireInfo(PsIdAndSiteDB post)
        {
            ApiResult<List<Landinfo>> apiResult = new ApiResult<List<Landinfo>>();
            try
            {
                var a = await stationReportRepository.GetHire(post);
                apiResult.Code = "0000";
                apiResult.Data = a;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                Logger.LogError("【" + controllerName + "/" + actionName + "】");
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return apiResult;
        }

        public string ExportExcelBackDownload(string post)
        {
            var postObject = JsonConvert.DeserializeObject<Excel>(post);
            var workbook = new XSSFWorkbook();
            #region excel設定
            IFont font12 = workbook.CreateFont();
            font12.FontName = "新細明體";
            font12.FontHeightInPoints = 12;
            ICellStyle style12 = workbook.CreateCellStyle();
            style12.SetFont(font12);
            style12.Alignment = HorizontalAlignment.Center;
            style12.VerticalAlignment = VerticalAlignment.Center;
            IFont font12Times = workbook.CreateFont();
            font12Times.FontName = "Times New Roman";
            font12Times.FontHeightInPoints = 12;
            IFont font18 = workbook.CreateFont();
            font18.FontName = "新細明體";
            font18.FontHeightInPoints = 18;
            font18.IsBold = true;
            ICellStyle styleTitle18 = workbook.CreateCellStyle();
            styleTitle18.SetFont(font18);
            styleTitle18.Alignment = HorizontalAlignment.Center;
            styleTitle18.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLeft12 = workbook.CreateCellStyle();
            styleLeft12.SetFont(font12);
            styleLeft12.Alignment = HorizontalAlignment.Left;
            styleLeft12.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLine12 = workbook.CreateCellStyle();
            styleLine12.SetFont(font12);
            styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            styleLine12.VerticalAlignment = VerticalAlignment.Center;
            styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            ICellStyle stylein12 = workbook.CreateCellStyle();
            stylein12.SetFont(font12Times);
            stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
            stylein12.VerticalAlignment = VerticalAlignment.Center;
            stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.WrapText = true;
            #endregion
            foreach (var powerstationid in postObject.PowerStation)
            {
                Select_table select_Table = new Select_table
                {
                    FormType = postObject.FormType,
                    SearchType = postObject.SearchType,
                    Time = postObject.Time,
                    PowerStation = Convert.ToInt32(powerstationid.Value),
                    Userid = postObject.Userid
                };
                var k = stationReportRepository.Findhaveinv(select_Table);
                var getinvsql = k.Result[0] as IDictionary<string, object>;
                if (getinvsql["mySelect"] == null)
                {
                    if(postObject.PowerStation.Count > 1)
                    {
                        continue;
                    }
                    else
                    {
                        return "";
                    }
                }
                var sheet = workbook.CreateSheet(powerstationid.Name);
                var Formbody = GetForm(select_Table);//取body
                if(Formbody.Result.Data.Count == 0)
                {
                    continue;
                }
                var Formhead = GetTableHead(select_Table);//取head
                int RowPosition = 0;

                switch (postObject.FormType)
                {
                    case 0: //日報表
                        #region 顯示head //RowPosition = 0
                        IRow row = sheet.CreateRow(RowPosition);
                        ICell cell = row.CreateCell(0);
                        int index = 0;
                        cell.SetCellValue("Date");
                        cell.CellStyle = styleLine12;
                        sheet.SetColumnWidth(index, 4 * 160 * 8);
                        index++;

                        foreach (var head in Formhead.Result.Data.Inv)
                        {
                            cell = row.CreateCell(index);
                            cell.SetCellValue(head);
                            cell.CellStyle = styleLine12;
                            sheet.SetColumnWidth(index, 4 * 160 * 6);
                            index++;
                        }

                        List<string> lasthead = new List<string>()
                        {
                            "小時發電量(kWh)",
                            "小時發電量百分比(%)",
                            "累積日照度(Wh/㎡)",
                            "小時平均模組溫度(°C)"
                        };
                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            lasthead.Add("小時售電金額(NTD)");
                        }



                        foreach (var head in lasthead)
                        {
                            cell = row.CreateCell(index);
                            cell.SetCellValue(head);
                            cell.CellStyle = styleLine12;
                            sheet.SetColumnWidth(index, 4 * 160 * 12);
                            index++;
                        }
                        #endregion

                        #region 顯示body //RowPosition = 1
                        RowPosition++;
                        var thour = ""; var tpr = ""; var tkwh = ""; var kWhkwp = ""; var ntd = ""; var ntdone = ""; var GeneratingCapacity = ""; var AverageDailyProfit = "";
                        foreach (dynamic body in Formbody.Result.Data)
                        {
                            
                            index = 0;
                            var dbody = body as IDictionary<string, object>;
                            thour = Checknull(Math.Round(Convert.ToDouble(dbody["tothour"]), 2).ToString());
                            tpr = Checknull(Math.Round(Convert.ToDouble(dbody["pr"]), 2).ToString());
                            tkwh = Checknull(Math.Round(Convert.ToDouble(dbody["totKWH"]), 2).ToString());
                            kWhkwp = Checknull(Math.Round(Convert.ToDouble(dbody["totKWHKWP"]), 2).ToString());
                            ntd = Checknull(Math.Round(Convert.ToDouble(dbody["totmoney"]), 2).ToString());
                            GeneratingCapacity = Checknull(Math.Round(Convert.ToDouble(dbody["GeneratingCapacity"]), 2).ToString());

                            double onemoney = Convert.ToDouble(ntd) / Convert.ToDouble(tkwh);
                            if (double.IsNaN(onemoney))
                            {
                                onemoney = 0;
                            }
                            ntdone = Checknull(Math.Round(onemoney, 4).ToString());
                            AverageDailyProfit = Checknull(Math.Round((Convert.ToDouble(ntd) / Convert.ToDouble(GeneratingCapacity)), 2).ToString());

                            row = sheet.CreateRow(RowPosition);
                            cell = row.CreateCell(index);
                            var b = dbody["report_date"].ToString();
                            cell.SetCellValue(b);
                            cell.CellStyle = styleLine12;
                            index++;
                            foreach (var head in Formhead.Result.Data.Inv)
                            {
                                cell = row.CreateCell(index);
                                cell.SetCellValue(dbody[head] == null ? 0 : Convert.ToDouble(dbody[head].ToString()));
                                cell.CellStyle = styleLine12;
                                index++;
                            }
                            List<string> bodynames = new List<string>(){
                                "hourKWH",
                                "hourKWHp",
                                "irradiance",
                                "temperature"
                                };
                            if (Formhead.Result.Data.ShowMoney == 1)
                            {
                                bodynames.Add("hourmoney");
                            }
                            foreach (var bodyname in bodynames)
                            {
                                cell = row.CreateCell(index);
                                if (dbody[bodyname] == null)
                                {
                                    cell.SetCellValue(0);
                                }
                                else
                                {
                                    var c = dbody[bodyname].ToString();
                                    cell.SetCellValue(Convert.ToDouble(Convert.ToDouble(c)));
                                }
                                cell.CellStyle = styleLine12;
                                index++;
                            }
                            RowPosition++;
                        }
                        #endregion

                        #region 顯示總量//RowPosition = body + 2
                        RowPosition += 2;//空兩行
                        //index = 0;
                        //row = sheet.CreateRow(RowPosition);
                        //cell = row.CreateCell(index);
                        //cell.SetCellValue("日照小時:");
                        //cell.CellStyle = styleLine12;
                        //cell = row.CreateCell(1);
                        //cell.SetCellValue(!string.IsNullOrEmpty(thour)? Convert.ToDouble(thour) : 0);
                        //cell.CellStyle = styleLine12;
                        //RowPosition++;

                        index = 0;
                        row = sheet.CreateRow(RowPosition);
                        cell = row.CreateCell(index);
                        cell.SetCellValue("日均發電度數:");
                        cell.CellStyle = styleLine12;
                        cell = row.CreateCell(1);
                        cell.SetCellValue(!string.IsNullOrEmpty(kWhkwp) ? Convert.ToDouble(kWhkwp) : 0);
                        cell.CellStyle = styleLine12;
                        RowPosition++;

                        index = 0;
                        row = sheet.CreateRow(RowPosition);
                        cell = row.CreateCell(index);
                        cell.SetCellValue("PR%:");
                        cell.CellStyle = styleLine12;
                        cell = row.CreateCell(1);
                        cell.SetCellValue(!string.IsNullOrEmpty(tpr) ? Convert.ToDouble(tpr) : 0);
                        cell.CellStyle = styleLine12;
                        RowPosition++;


                        index = 0;
                        row = sheet.CreateRow(RowPosition);
                        cell = row.CreateCell(index);
                        cell.SetCellValue("日發電量(kWh):");
                        cell.CellStyle = styleLine12;
                        cell = row.CreateCell(1);
                        cell.SetCellValue(!string.IsNullOrEmpty(tkwh) ? Convert.ToDouble(tkwh) : 0);
                        cell.CellStyle = styleLine12;
                        RowPosition++;

                        index = 0;
                        row = sheet.CreateRow(RowPosition);
                        cell = row.CreateCell(index);
                        cell.SetCellValue("裝置容量:");
                        cell.CellStyle = styleLine12;
                        cell = row.CreateCell(1);
                        cell.SetCellValue(Convert.ToDouble(GeneratingCapacity));
                        cell.CellStyle = styleLine12;
                        RowPosition++;


                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            index = 0;
                            row = sheet.CreateRow(RowPosition);
                            cell = row.CreateCell(index);
                            cell.SetCellValue("日售電金額(NTD):");
                            cell.CellStyle = styleLine12;
                            cell = row.CreateCell(1);
                            cell.SetCellValue(!string.IsNullOrEmpty(ntd) ? Convert.ToDouble(ntd) : 0);
                            cell.CellStyle = styleLine12;
                            RowPosition++;

                            index = 0;
                            row = sheet.CreateRow(RowPosition);
                            cell = row.CreateCell(index);
                            cell.SetCellValue("日售電單價(NTD):");
                            cell.CellStyle = styleLine12;
                            cell = row.CreateCell(1);
                            cell.SetCellValue(!string.IsNullOrEmpty(ntdone) ? Convert.ToDouble(ntdone) : 0);
                            cell.CellStyle = styleLine12;
                            RowPosition++;

                            index = 0;
                            row = sheet.CreateRow(RowPosition);
                            cell = row.CreateCell(index);
                            cell.SetCellValue("日均獲利(NTD):");
                            cell.CellStyle = styleLine12;
                            cell = row.CreateCell(1);
                            cell.SetCellValue(!string.IsNullOrEmpty(AverageDailyProfit) ? Convert.ToDouble(AverageDailyProfit) : 0);
                            cell.CellStyle = styleLine12;
                        }



                        #endregion
                        break;
                    case 1: // 月報表
                        #region 顯示head //RowPosition = 0
                        IRow row2 = sheet.CreateRow(RowPosition);
                        ICell cell2 = row2.CreateCell(0);
                        int index2 = 0;
                        cell2.SetCellValue("Date");
                        cell2.CellStyle = styleLine12;
                        sheet.SetColumnWidth(index2, 4 * 160 * 8);
                        index2++;

                        foreach (var head in Formhead.Result.Data.Inv)
                        {
                            cell2 = row2.CreateCell(index2);
                            cell2.SetCellValue(head);
                            cell2.CellStyle = styleLine12;
                            sheet.SetColumnWidth(index2, 4 * 160 * 8);
                            index2++;
                        }

                        List<string> lasthead2 = new List<string>()
                        {
                            "日發電量(kWh)",
                            "日發電量百分比(%)",
                            "日照小時(hr)",
                            "有效發電小時",
                            "PR%",
                            "累積日照量(Wh/㎡)",
                            "日平均模組溫度(°C)"

                        };
                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            lasthead2.Add("日售電金額(NTD)");
                        }
                        foreach (var head in lasthead2)
                        {
                            cell2 = row2.CreateCell(index2);
                            cell2.SetCellValue(head);
                            cell2.CellStyle = styleLine12;
                            sheet.SetColumnWidth(index2, 4 * 160 * 12);
                            index2++;
                        }
                        #endregion

                        #region 顯示body //RowPosition = 1
                        RowPosition++;
                        var avghour = "0"; var avgKWHKWP = "0"; var avgdayKWH = "0"; var monthKWH = "0"; var monthmoney = "0"; var monthmoneyone = "0";
                        var monthGeneratingCapacity = "";
                        var check_hire = false;
                        var sitedb = "";
                        foreach (dynamic body in Formbody.Result.Data)
                        {
                            index2 = 0;
                            var dbody = body as IDictionary<string, object>;

                            avghour = (Convert.ToDouble(dbody["tothour"].ToString()) + Convert.ToDouble(avghour)).ToString();
                            avgKWHKWP = (Convert.ToDouble(dbody["KWHKWP"].ToString()) + Convert.ToDouble(avgKWHKWP)).ToString();
                            avgdayKWH = (Convert.ToDouble(dbody["dayKWH"].ToString()) + Convert.ToDouble(avgdayKWH)).ToString();
                            monthKWH = dbody["monthKWH"] == null ? "0" : dbody["monthKWH"].ToString();
                            monthmoney = dbody["monthmoney"] == null ? "0" : dbody["monthmoney"].ToString();
                            monthmoneyone = (Convert.ToDouble(dbody["monthmoneyone"].ToString()) + Convert.ToDouble(monthmoneyone)).ToString();
                            monthGeneratingCapacity = Checknull(Math.Round(Convert.ToDouble(dbody["GeneratingCapacity"]), 2).ToString());
                            if (dbody["SolarType"].ToString() == "1" && Formhead.Result.Data.ShowMoney == 1)//檢驗是否為租用
                            {
                                check_hire = true;
                                sitedb = dbody["SiteDB"].ToString();
                            }

                            row2 = sheet.CreateRow(RowPosition);
                            cell2 = row2.CreateCell(index2);
                            var b = dbody["report_date"].ToString();
                            cell2.SetCellValue(b);
                            cell2.CellStyle = styleLine12;
                            index2++;
                            foreach (var head in Formhead.Result.Data.Inv)
                            {
                                cell2 = row2.CreateCell(index2);
                                cell2.SetCellValue(dbody[head] == null ? 0 : Convert.ToDouble(dbody[head].ToString()));
                                cell2.CellStyle = styleLine12;
                                index2++;
                            }
                            List<string> bodynames = new List<string>(){
                                "dayKWH",
                                "dayKWHp",
                                "tothour",
                                "KWHKWP",
                                "PR",
                                "IrrDay",
                                "temperature"
                                };
                            if (Formhead.Result.Data.ShowMoney == 1)
                            {
                                bodynames.Add("soldmoney");
                            }
                            foreach (var bodyname in bodynames)
                            {
                                cell2 = row2.CreateCell(index2);
                                if (dbody[bodyname] == null)
                                {
                                    cell2.SetCellValue(0);
                                }
                                else
                                {
                                    var c = dbody[bodyname].ToString();
                                    cell2.SetCellValue(Convert.ToDouble(c));
                                }
                                cell2.CellStyle = styleLine12;
                                index2++;
                            }
                            RowPosition++;
                        }
                        #endregion

                        #region 顯示總量//RowPosition = body + 2
                        RowPosition += 2;//空兩行
                        index = 0;
                        var Useday = Formbody.Result.Data.Count;
                        row = sheet.CreateRow(RowPosition);

                        //cell = row.CreateCell(index);
                        //cell.SetCellValue("日日照小時平均");
                        //cell.CellStyle = styleLine12;
                        //index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("日均發電度數(日)");
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("發電量平均(kWh)(日)");
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("發電量(kWh)(月)");
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue("裝置容量");
                        cell.CellStyle = styleLine12;
                        index++;
                        
                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            cell = row.CreateCell(index);
                            cell.SetCellValue("每度獲利");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("月售電金額(NTD)");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("月售電單價(NTD)");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("日均獲利(NTD)");
                            cell.CellStyle = styleLine12;
                            index++;
                        }
                        cell = row.CreateCell(index);
                        cell.SetCellValue("月售電天數");
                        cell.CellStyle = styleLine12;



                        index = 0;
                        RowPosition++;
                        row = sheet.CreateRow(RowPosition);

                        //cell = row.CreateCell(index);
                        //cell.SetCellValue(Math.Round(Convert.ToDouble(avghour) / Useday, 2));
                        //cell.CellStyle = styleLine12;
                        //index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Math.Round(Convert.ToDouble(avgKWHKWP) / Useday, 2));
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Math.Round(Convert.ToDouble(avgdayKWH) / Useday, 2));
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Convert.ToDouble(monthKWH));
                        cell.CellStyle = styleLine12;
                        index++;
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Convert.ToDouble(monthGeneratingCapacity));
                        cell.CellStyle = styleLine12;
                        index++;
                        
                        if (Formhead.Result.Data.ShowMoney == 1)
                        {
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) / Convert.ToDouble(monthGeneratingCapacity), 3));
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Convert.ToDouble(monthmoney));
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoneyone) / Useday, 4));
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) / Convert.ToDouble(monthGeneratingCapacity) / Useday, 2));
                            cell.CellStyle = styleLine12;
                            index++;
                        }
                        cell = row.CreateCell(index);
                        cell.SetCellValue(Useday);
                        cell.CellStyle = styleLine12;
                        #endregion

                        #region 顯示租用//RowPosition = 總量 + 2
                        if (check_hire == true)
                        {
                            RowPosition += 2;//空兩行
                            PsIdAndSiteDB set = new PsIdAndSiteDB()
                            {
                                PowerstationId = Convert.ToInt32(powerstationid.Value),
                                SiteDB = sitedb
                            };
                            var info = GetHireInfo(set);
                            index = 0;
                            row = sheet.CreateRow(RowPosition);

                            cell = row.CreateCell(index);
                            cell.SetCellValue("出租人");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("租金比例");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("租金金額(未稅)");
                            cell.CellStyle = styleLine12;
                            index++;
                            cell = row.CreateCell(index);
                            cell.SetCellValue("租金金額(含稅)");
                            cell.CellStyle = styleLine12;

                            foreach (var a in info.Result.Data)
                            {
                                RowPosition++;
                                index = 0;
                                row = sheet.CreateRow(RowPosition);

                                cell = row.CreateCell(index);
                                cell.SetCellValue(a.Landowner);
                                cell.CellStyle = styleLine12;
                                index++;
                                cell = row.CreateCell(index);
                                cell.SetCellValue(a.LeaseRate + "%");
                                cell.CellStyle = styleLine12;
                                index++;
                                cell = row.CreateCell(index);
                                cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) * Convert.ToDouble(a.LeaseRate) / 100, 2).ToString());
                                cell.CellStyle = styleLine12;
                                index++;
                                cell = row.CreateCell(index);
                                cell.SetCellValue(Math.Round(Convert.ToDouble(monthmoney) * Convert.ToDouble(a.LeaseRate) / 100 * 1.05, 2).ToString());
                                cell.CellStyle = styleLine12;
                                index++;
                            }
                        }
                        #endregion
                        break;
                }

            }
            var name = "";
            if (postObject.FormType == 0)
            {
                name = "日";
            }
            else
            {
                if(postObject.SearchType == 2)
                {
                    name = "月";
                }
                else
                {
                    name = "區間";
                }
            }
            var Datename = postObject.Time.Replace("-", "");

            if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "report")))
            {
                Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "report"));
            }


            if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "report", Datename)))
            {
                Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "report", Datename));
            }
            string companyName = postObject.PowerStation[0].Name;
            var n = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "report", Datename, companyName + "_" + name + "報表" + "_" + postObject.Userid + Datename + ".xlsx");
            FileStream FS = new FileStream(n, FileMode.Create, FileAccess.Write);
            workbook.Write(FS);
            FS.Close();
            return Path.Combine("\\" + "upload" ,"report", Datename, companyName + "_" + name + "報表" + "_" + postObject.Userid+ Datename + ".xlsx");
        }

        public async Task<ApiResult<List<MaxFormbody>>> GetMaxForm(Select_table2 post)
        {
            ApiResult<List<MaxFormbody>> apiResult = new ApiResult<List<MaxFormbody>>();
            List<MaxFormbody> body = new List<MaxFormbody>();
            try
            {
                var a = await stationReportRepository.GetMaxtablebody(post);
                apiResult.Code = "0000";
                apiResult.Data = a;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                Logger.LogError("【" + controllerName + "/" + actionName + "】");
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return apiResult;
        }

        public FileResult ExportExcelmaxtable(string post)
        {
            var postObject = JsonConvert.DeserializeObject<Select_table2>(post);
            var workbook = new XSSFWorkbook();
            #region excel設定
            IFont font12 = workbook.CreateFont();
            font12.FontName = "新細明體";
            font12.FontHeightInPoints = 12;
            ICellStyle style12 = workbook.CreateCellStyle();
            style12.SetFont(font12);
            style12.Alignment = HorizontalAlignment.Center;
            style12.VerticalAlignment = VerticalAlignment.Center;
            IFont font12Times = workbook.CreateFont();
            font12Times.FontName = "Times New Roman";
            font12Times.FontHeightInPoints = 12;
            IFont font18 = workbook.CreateFont();
            font18.FontName = "新細明體";
            font18.FontHeightInPoints = 18;
            font18.IsBold = true;
            ICellStyle styleTitle18 = workbook.CreateCellStyle();
            styleTitle18.SetFont(font18);
            styleTitle18.Alignment = HorizontalAlignment.Center;
            styleTitle18.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLeft12 = workbook.CreateCellStyle();
            styleLeft12.SetFont(font12);
            styleLeft12.Alignment = HorizontalAlignment.Left;
            styleLeft12.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLine12 = workbook.CreateCellStyle();
            styleLine12.SetFont(font12);
            styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            styleLine12.VerticalAlignment = VerticalAlignment.Center;
            styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            ICellStyle stylein12 = workbook.CreateCellStyle();
            stylein12.SetFont(font12Times);
            stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
            stylein12.VerticalAlignment = VerticalAlignment.Center;
            stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.WrapText = true;
            #endregion
            var Formbody = GetMaxForm(postObject);
            Select_table select_Table = new Select_table
            {
                FormType = postObject.FormType,
                SearchType = postObject.SearchType,
                Time = postObject.Time,
                PowerStation = 1,
                Userid = postObject.Userid
            };
            var Formhead = GetTableHead(select_Table);//取head
            
            var sheet = workbook.CreateSheet("綜合比較");
            int RowPosition = 0;
            int index = 0;
            var citycount = Formbody.Result.Data.GroupBy(a => a.CityName).Count();
            RowPosition = citycount + 6;
            IRow row;
            ICell cell;
            double kwhkwp = 0;
            double kwp = 0;
            double totalGeneratingCapacity = 0;
            CellRangeAddress region;
            List<CityArray> cityArrays = new List<CityArray>();
            foreach (var form in Formbody.Result.Data)
            {
                index = 0;
                row = sheet.CreateRow(RowPosition);
                cell = row.CreateCell(index);
                cell.SetCellValue(form.CityName+form.AreaName);
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(form.PowerstationName);
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                switch (form.PowerstationType)
                {
                    case 0:
                        cell.SetCellValue("自建躉售");
                        break;
                    case 1:
                        cell.SetCellValue("租建躉售");
                        break;
                    case 2:
                        cell.SetCellValue("自發自用");
                        break;
                }
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(form.ElectricityMeterAt);
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(form.PowerRate, 2));
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(form.TodayMoney/form.GeneratingCapacity/form.Days, 2));//日均獲利
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(form.AvgKWHKWP, 2));//日均發電度數
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(form.Kwh,2));//發電量
                cell.CellStyle = styleLine12;

                //index++;
                //cell = row.CreateCell(index);
                //cell.SetCellValue(Math.Round(form.Irradiance,2));
                //cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(form.AvgPR,2));
                cell.CellStyle = styleLine12;


                if (Formhead.Result.Data.ShowMoney == 1)
                {
                    index++;
                    cell = row.CreateCell(index);
                    cell.SetCellValue(Math.Round(form.TodayMoney, 2));
                    cell.CellStyle = styleLine12;

                    PsIdAndSiteDB psIdAndSiteDB = new PsIdAndSiteDB()
                    {
                        PowerstationId = form.PowerstationId,
                        SiteDB = form.PowerstationDB
                    };
                    Double LeaseRate = 0;
                    if(form.PowerstationType == 1)
                    {
                        var Hire = GetHireInfo(psIdAndSiteDB);

                        foreach (var a in Hire.Result.Data)
                        {
                            LeaseRate += Convert.ToDouble(a.LeaseRate);
                        }
                    }


                    index++;
                    cell = row.CreateCell(index);
                    cell.SetCellValue(Math.Round(form.TodayMoney * LeaseRate *0.01, 2));
                    cell.CellStyle = styleLine12;

                    index++;
                    cell = row.CreateCell(index);
                    cell.SetCellValue(Math.Round(form.TodayMoney, 2));
                    cell.CellStyle = styleLine12;
                }

                


                kwp += form.Kwh;
                kwhkwp += form.AvgKWHKWP;
                totalGeneratingCapacity += form.GeneratingCapacity;
                RowPosition++;
                CityArray cityinfo = new CityArray
                {
                    City = form.CityName,
                    Count = 1,
                    Kwh = form.TotalKWH,
                    SolarHour = form.SolarHour,
                    Kwhkwp = form.AvgKWHKWP,
                    GeneratingCapacity = form.GeneratingCapacity
                };
                if( cityArrays.Where(a=>a.City == form.CityName).Count() > 0)
                {
                    var city = cityArrays.Where(a => a.City == form.CityName).FirstOrDefault();
                    city.Count += cityinfo.Count;
                    city.Kwh += cityinfo.Kwh;
                    city.SolarHour += cityinfo.SolarHour;
                    city.Kwhkwp += cityinfo.Kwhkwp;
                    city.GeneratingCapacity += cityinfo.GeneratingCapacity;
                }
                else
                {
                    cityArrays.Add(cityinfo);
                }
                

            }
            RowPosition = citycount + 6;
            RowPosition--;
            row = sheet.CreateRow(RowPosition);
            index = 0;
            List<string> lasthead = new List<string>()
            {
                "區域",
                "電站名稱",
                "電站類型",
                "掛錶日期",
                "躉售費率",
                "每kw日均獲利",
                "日均發電度數",
                "發電量",
                //"平均日照",
                "PR"
            };
            if (Formhead.Result.Data.ShowMoney == 1)
            {
                lasthead.Add("發電金額");
                lasthead.Add("租金收入");
                lasthead.Add("省電費用");
            }
            foreach (var head in lasthead)
            {
                sheet.SetColumnWidth(index, 4 * 160 * 8);
                cell = row.CreateCell(index);
                cell.SetCellValue(head);
                cell.CellStyle = styleLine12;
                index++;
            }

            RowPosition--;
            RowPosition -= citycount;
            var cityRowPosition = RowPosition;
            index = 0;
            foreach(var cityArray in cityArrays)
            {
                index = 0;
                row = sheet.CreateRow(cityRowPosition);
                cell = row.CreateCell(index);
                cell.SetCellValue(cityArray.City);
                cell.CellStyle = styleLine12;
                region = new CellRangeAddress(cityRowPosition, cityRowPosition, index, index + 1);
                sheet.AddMergedRegion(region);
                index++;
                cell = row.CreateCell(index);
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(cityArray.GeneratingCapacity, 2));
                cell.CellStyle = styleLine12;
                region = new CellRangeAddress(cityRowPosition, cityRowPosition, index, index + 1);
                sheet.AddMergedRegion(region);
                index++;
                cell = row.CreateCell(index);
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(cityArray.Kwh, 3));
                cell.CellStyle = styleLine12;
                region = new CellRangeAddress(cityRowPosition, cityRowPosition, index, index + 1);
                sheet.AddMergedRegion(region);
                index++;
                cell = row.CreateCell(index);
                cell.CellStyle = styleLine12;


                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round((cityArray.Kwh / cityArray.GeneratingCapacity), 2));
                cell.CellStyle = styleLine12;
                region = new CellRangeAddress(cityRowPosition, cityRowPosition, index, index + 1);
                sheet.AddMergedRegion(region);
                index++;
                cell = row.CreateCell(index);
                cell.CellStyle = styleLine12;
                cityRowPosition++;
            }

            index = 0;
            RowPosition--;
            row = sheet.CreateRow(RowPosition);
            cell = row.CreateCell(index);
            cell.SetCellValue("縣市");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue("裝置容量");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue("總發電量");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue("日均發電度數");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            RowPosition = 0;
            index = 0;
            row = sheet.CreateRow(RowPosition);
            cell = row.CreateCell(index);
            cell.SetCellValue("時間");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index ++;
            cell = row.CreateCell(index);
            cell.SetCellValue("發電量");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue("日均發電度數");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;


            

            RowPosition++;
            row = sheet.CreateRow(RowPosition);

            index = 0;
            cell = row.CreateCell(index);
            cell.SetCellValue(postObject.Time);
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue(Math.Round(kwp,2));
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index ++;
            cell = row.CreateCell(index);
            cell.SetCellValue(Math.Round(kwp / totalGeneratingCapacity, 2));
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;




            var ms = new NpoiMemoryStream
            {
                AllowClose = false
            };
            string companyName = postObject.PowerStation[0].Name;
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            var Datename = postObject.Time.Replace("-", "");
            return File(ms, "application/vnd.ms-excel", companyName + "_" + "綜合比較" + "_" + postObject.Userid + Datename + ".xlsx");
        }

        public string ExportExcelmaxtableBackDownload(string post)
        {
            var postObject = JsonConvert.DeserializeObject<Select_table2>(post);
            var workbook = new XSSFWorkbook();
            #region excel設定
            IFont font12 = workbook.CreateFont();
            font12.FontName = "新細明體";
            font12.FontHeightInPoints = 12;
            ICellStyle style12 = workbook.CreateCellStyle();
            style12.SetFont(font12);
            style12.Alignment = HorizontalAlignment.Center;
            style12.VerticalAlignment = VerticalAlignment.Center;
            IFont font12Times = workbook.CreateFont();
            font12Times.FontName = "Times New Roman";
            font12Times.FontHeightInPoints = 12;
            IFont font18 = workbook.CreateFont();
            font18.FontName = "新細明體";
            font18.FontHeightInPoints = 18;
            font18.IsBold = true;
            ICellStyle styleTitle18 = workbook.CreateCellStyle();
            styleTitle18.SetFont(font18);
            styleTitle18.Alignment = HorizontalAlignment.Center;
            styleTitle18.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLeft12 = workbook.CreateCellStyle();
            styleLeft12.SetFont(font12);
            styleLeft12.Alignment = HorizontalAlignment.Left;
            styleLeft12.VerticalAlignment = VerticalAlignment.Center;
            ICellStyle styleLine12 = workbook.CreateCellStyle();
            styleLine12.SetFont(font12);
            styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            styleLine12.VerticalAlignment = VerticalAlignment.Center;
            styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            ICellStyle stylein12 = workbook.CreateCellStyle();
            stylein12.SetFont(font12Times);
            stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
            stylein12.VerticalAlignment = VerticalAlignment.Center;
            stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            stylein12.WrapText = true;
            #endregion
            var Formbody = GetMaxForm(postObject);
            Select_table select_Table = new Select_table
            {
                FormType = postObject.FormType,
                SearchType = postObject.SearchType,
                Time = postObject.Time,
                PowerStation = 1,
                Userid = postObject.Userid
            };
            var Formhead = GetTableHead(select_Table);//取head

            var sheet = workbook.CreateSheet("綜合比較");
            int RowPosition = 0;
            int index = 0;
            var citycount = Formbody.Result.Data.GroupBy(a => a.CityName).Count();
            RowPosition = citycount + 6;
            IRow row;
            ICell cell;
            double kwhkwp = 0;
            double kwp = 0;
            double totalGeneratingCapacity = 0;
            CellRangeAddress region;
            List<CityArray> cityArrays = new List<CityArray>();
            foreach (var form in Formbody.Result.Data)
            {
                index = 0;
                row = sheet.CreateRow(RowPosition);
                cell = row.CreateCell(index);
                cell.SetCellValue(form.CityName + form.AreaName);
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(form.PowerstationName);
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                switch (form.PowerstationType)
                {
                    case 0:
                        cell.SetCellValue("自建躉售");
                        break;
                    case 1:
                        cell.SetCellValue("租建躉售");
                        break;
                    case 2:
                        cell.SetCellValue("自發自用");
                        break;
                }
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(form.ElectricityMeterAt);
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(form.PowerRate, 2));
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(form.TodayMoney / form.GeneratingCapacity / form.Days, 2));//日均獲利
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(form.AvgKWHKWP, 2));//日均發電度數
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(form.Kwh, 2));//發電量
                cell.CellStyle = styleLine12;

                //index++;
                //cell = row.CreateCell(index);
                //cell.SetCellValue(Math.Round(form.Irradiance, 2));
                //cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(form.AvgPR, 2));
                cell.CellStyle = styleLine12;


                if (Formhead.Result.Data.ShowMoney == 1)
                {
                    index++;
                    cell = row.CreateCell(index);
                    cell.SetCellValue(Math.Round(form.TodayMoney, 2));
                    cell.CellStyle = styleLine12;

                    PsIdAndSiteDB psIdAndSiteDB = new PsIdAndSiteDB()
                    {
                        PowerstationId = form.PowerstationId,
                        SiteDB = form.PowerstationDB
                    };
                    double LeaseRate = 0;
                    if (form.PowerstationType == 1)
                    {
                        var Hire = GetHireInfo(psIdAndSiteDB);

                        foreach (var a in Hire.Result.Data)
                        {

                            LeaseRate += Convert.ToDouble(a.LeaseRate);
                        }
                    }

                    index++;
                    cell = row.CreateCell(index);
                    cell.SetCellValue(Math.Round(form.TodayMoney * LeaseRate * 0.01, 2));
                    cell.CellStyle = styleLine12;

                    index++;
                    cell = row.CreateCell(index);
                    cell.SetCellValue(Math.Round(form.TodayMoney, 2));
                    cell.CellStyle = styleLine12;
                }




                kwp += form.Kwh;
                kwhkwp += form.AvgKWHKWP;
                totalGeneratingCapacity += form.GeneratingCapacity;
                RowPosition++;
                CityArray cityinfo = new CityArray
                {
                    City = form.CityName,
                    Count = 1,
                    Kwh = form.Kwh,
                    SolarHour = form.SolarHour,
                    Kwhkwp = form.AvgKWHKWP,
                    GeneratingCapacity = form.GeneratingCapacity
                };
                if (cityArrays.Where(a => a.City == form.CityName).Count() > 0)
                {
                    var city = cityArrays.Where(a => a.City == form.CityName).FirstOrDefault();
                    city.Count += cityinfo.Count;
                    city.Kwh += cityinfo.Kwh;
                    city.SolarHour += cityinfo.SolarHour;
                    city.Kwhkwp += cityinfo.Kwhkwp;
                    city.GeneratingCapacity += cityinfo.GeneratingCapacity;
                }
                else
                {
                    cityArrays.Add(cityinfo);
                }


            }
            RowPosition = citycount + 6;
            RowPosition--;
            row = sheet.CreateRow(RowPosition);
            index = 0;
            List<string> lasthead = new List<string>()
            {
                "區域",
                "電站名稱",
                "電站類型",
                "掛錶日期",
                "躉售費率",
                "每kw日均獲利",
                "日均發電度數",
                "發電量",
                //"平均日照",
                "PR"
            };
            if (Formhead.Result.Data.ShowMoney == 1)
            {
                lasthead.Add("發電金額");
                lasthead.Add("租金收入");
                lasthead.Add("省電費用");
            }
            foreach (var head in lasthead)
            {
                sheet.SetColumnWidth(index, 4 * 160 * 8);
                cell = row.CreateCell(index);
                cell.SetCellValue(head);
                cell.CellStyle = styleLine12;
                index++;
            }

            RowPosition--;
            RowPosition -= citycount;
            var cityRowPosition = RowPosition;
            index = 0;
            foreach (var cityArray in cityArrays)
            {
                index = 0;
                row = sheet.CreateRow(cityRowPosition);
                cell = row.CreateCell(index);
                cell.SetCellValue(cityArray.City);
                cell.CellStyle = styleLine12;
                region = new CellRangeAddress(cityRowPosition, cityRowPosition, index, index + 1);
                sheet.AddMergedRegion(region);
                index++;
                cell = row.CreateCell(index);
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(cityArray.GeneratingCapacity, 2));
                cell.CellStyle = styleLine12;
                region = new CellRangeAddress(cityRowPosition, cityRowPosition, index, index + 1);
                sheet.AddMergedRegion(region);
                index++;
                cell = row.CreateCell(index);
                cell.CellStyle = styleLine12;

                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round(cityArray.Kwh, 3));
                cell.CellStyle = styleLine12;
                region = new CellRangeAddress(cityRowPosition, cityRowPosition, index, index + 1);
                sheet.AddMergedRegion(region);
                index++;
                cell = row.CreateCell(index);
                cell.CellStyle = styleLine12;


                index++;
                cell = row.CreateCell(index);
                cell.SetCellValue(Math.Round((cityArray.Kwh / cityArray.GeneratingCapacity), 2));
                cell.CellStyle = styleLine12;
                region = new CellRangeAddress(cityRowPosition, cityRowPosition, index, index + 1);
                sheet.AddMergedRegion(region);
                index++;
                cell = row.CreateCell(index);
                cell.CellStyle = styleLine12;
                cityRowPosition++;
            }

            index = 0;
            RowPosition--;
            row = sheet.CreateRow(RowPosition);
            cell = row.CreateCell(index);
            cell.SetCellValue("縣市");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue("裝置容量");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue("總發電量");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue("日均發電度數");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            RowPosition = 0;
            index = 0;
            row = sheet.CreateRow(RowPosition);
            cell = row.CreateCell(index);
            cell.SetCellValue("時間");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue("發電量");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue("日均發電度數");
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;




            RowPosition++;
            row = sheet.CreateRow(RowPosition);

            index = 0;
            cell = row.CreateCell(index);
            cell.SetCellValue(postObject.Time);
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue(Math.Round(kwp, 2));
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;

            index++;
            cell = row.CreateCell(index);
            cell.SetCellValue(Math.Round(kwp / totalGeneratingCapacity, 2));
            cell.CellStyle = styleLine12;
            region = new CellRangeAddress(RowPosition, RowPosition, index, index + 1);
            sheet.AddMergedRegion(region);
            index++;
            cell = row.CreateCell(index);
            cell.CellStyle = styleLine12;



            var Datename = postObject.Time.Replace("-", "");
            if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "report")))
            {
                Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "report"));
            }
            if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "report", Datename)))
            {
                Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "report", Datename));
            }
            string companyName = postObject.PowerStation[0].Name;
            var n = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "report", Datename, companyName + "_" + "綜合比較" + "_" + postObject.Userid + Datename + ".xlsx");
            FileStream FS = new FileStream(n, FileMode.Create, FileAccess.Write);
            workbook.Write(FS);
            FS.Close();

            return Path.Combine("\\" + "upload", "report", Datename, companyName + "_" + "綜合比較" + "_" + postObject.Userid + Datename + ".xlsx");
        }

        public async Task<ApiResult<List<string>>> CheckExcel(Select_table2 post)
        {
            var ApiResult = new ApiResult<List<string>>();
            var ErrorMessage = new List<string>();
            foreach (var station in post.PowerStation)
            {
                var Id = Convert.ToInt32(station.Value);
                var table = new Select_table()
                {
                    FormType = post.FormType,
                    SearchType = post.SearchType,
                    PowerStation = Id,
                    Time = post.Time,
                    Userid = post.Userid
                };
                var checkinv = await stationReportRepository.Findhaveinv(table);
                var getinvsql = checkinv[0] as IDictionary<string, object>;
                if (getinvsql["mySelect"] == null)
                {
                    ErrorMessage.Add(station.Name + "此時段無逆變器資料");
                }
                else
                {
                    var cid = await stationReportRepository.CheckExcelAsync(table);
                    if (cid == 0)
                    {
                        ErrorMessage.Add(station.Name + "此時段資料未建立");
                    }
                }
            }
            if(ErrorMessage.Count > 0)
            {
                ApiResult.Code = "9999";
                ApiResult.Data = ErrorMessage;
            }
            else
            {
                ApiResult.Code = "0000";
            }
            return ApiResult;
        }
    }
}
