using FrontendWebApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace FrontendWebApi.ApiControllers
{
    public class EnergeManageController : MyBaseApiController<EnergeManageController>
    {
        private readonly IBackendRepository backendRepository;
        private readonly IFrontendRepository frontendRepository;

        public EnergeManageController(IBackendRepository backendRepository, IFrontendRepository frontendRepository)
        {
            this.backendRepository = backendRepository;
            this.frontendRepository = frontendRepository;
        }

        [HttpPost]
        [Route("api/Energe/GetElecBySubSysTag")]
        public async Task<ActionResult<ApiResult<List<ElecSubSystem>>>> GetElecBySubSysTag()
        {
            ApiResult<List<ElecSubSystem>> apiResult = new ApiResult<List<ElecSubSystem>>();
            try
            {
                var sqlString = $@"SELECT system_key as MainSubTag ,system_value as system_device_tag,system_priority as priority, system_remark FROM variable 
                                    where system_type = 'meter_for_subsystem' and deleted = '0'";
                var ess = await backendRepository.GetAllAsync<ElecSubSystem>(sqlString);

                apiResult.Code = "0000";
                apiResult.Data = ess;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
                return Ok(apiResult);
            }
            return Ok(apiResult);
        }


        [HttpPost]
        [Route("api/Energe/GetAutDemVal")]
        public async Task<ActionResult<ApiResult<List<Variable>>>> GetAutDemVal()
        {
            ApiResult<List<Variable>> apiResult = new ApiResult<List<Variable>>();
            try
            {
                var sqlString = $@"SELECT system_value,system_key FROM variable 
                                    where system_type = 'automated_demand_response' and deleted = '0'";
                var ess = await backendRepository.GetAllAsync<Variable>(sqlString);

                apiResult.Code = "0000";
                apiResult.Data = ess;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
                return Ok(apiResult);
            }
            return Ok(apiResult);
        }

        [HttpPost]
        [Route("api/Energe/EdiAutDemVal")]
        public async Task<ActionResult<ApiResult<List<int?>>>> EdiAutDemVal([FromBody] List<Variable> variables)
        {
            ApiResult<List<int?>> apiResult = new ApiResult<List<int?>>();

            try
            {
                var sqlString = $@"SELECT system_value,system_key FROM variable 
                                    where system_type = 'automated_demand_response' and deleted = '0'";
                var vs = await backendRepository.GetAllAsync<Variable>(sqlString);

                var autDemKeys = vs.Select(x => x.System_key);
                foreach (var v in variables) {
                    if (autDemKeys.Where(x => x == v.System_key).Count() != 0) {
                        Dictionary<string, object> sqlParam = new Dictionary<string, object>() { 
                            { "@system_key", v.System_key},
                            { "@system_value", v.system_value},
                            { "@updated_by", myUser.userinfo_guid},
                            { "@updated_at", DateTime.Now},
                        };
                 
                        await backendRepository.UpdateOneByCustomTable(sqlParam, "variable", $" system_type = 'automated_demand_response' AND system_key = @system_key");

                    }
                }
                
                apiResult.Code = "0000";
                apiResult.Data = null;
                apiResult.Msg = "編輯成功";
            }
            catch (Exception exception)
            {
              
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。" + exception.Message;
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
                return Ok(apiResult);
            }
            return Ok(apiResult);
        }
    }
}