using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SolarPower.Repository.Interface;
using SolarPower.Services.Interface;
using System.IO;
using SolarPower.Models;
using SolarPower.Models.SensorType;
using SolarPower.Models.SensorDetail;

namespace SolarPower.Controllers
{
    public class SensorTypeController : MyBaseController<SensorTypeController>
    {
        private readonly ISensorTypeRepository sensorTypeRepository;
        private readonly ISensorDetailRepository sensorDetailRepository;
        private string sensorTypeSaveAsPath = "";

        public SensorTypeController(ISensorTypeRepository sensorTypeRepository, ISensorDetailRepository sensorDetailRepository) : base()
        {
            this.sensorTypeRepository = sensorTypeRepository;
            this.sensorDetailRepository = sensorDetailRepository;

            sensorTypeSaveAsPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "sensor_type");
        }

        public IActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 新增 / 修改 設備資料
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<string>> SaveSensorType(SensorType post)
        {
            ApiResult<string> apiResult = new ApiResult<string>();

            SensorType sensor = null;
            string nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            try
            {
                sensor = await sensorTypeRepository.GetOneAsync(post.Id);

                if (sensor == null)
                {

                    if (post.Id != 0)
                    {
                        apiResult.Code = "9998";//待定
                        apiResult.Msg = errorCode.GetString(apiResult.Code);
                        return apiResult;
                    }

                    #region 新增設備
                    sensor = new SensorType()
                    {
                        Deleted = 0,
                        Enabled = post.Enabled,
                        SensorName = post.SensorName,
                        SensorEName = post.SensorEName,
                        CreatedBy = myUser.Id,
                        CreatedAt = nowTime,
                    };

                    List<string> properties = new List<string>()
                    {
                        "Deleted",
                        "Enabled",
                        "SensorName",
                        "SensorEName",
                        "CreatedBy",
                        "CreatedAt"
                    };

                    var id = await sensorTypeRepository.AddOneAsync(sensor, properties);


                    //var website_url = await powerStationRepository.GetOneVariableByName("WebSiteUrl");


                    //var sendSubject = "新增設備成功";
                    apiResult.Code = "0000";
                    apiResult.Msg = "儲存成功";
                    #endregion
                }
                else
                {
                    #region 修改設備
                    SensorType update = new SensorType()
                    {
                        Id = sensor.Id,
                        Enabled = post.Enabled,
                        SensorName = post.SensorName,
                        SensorEName = post.SensorEName,
                        UpdatedBy = myUser.Id,
                        UpdatedAt = nowTime,
                    };


                    List<string> properties = new List<string>()
                    {
                        "Id",
                        "Enabled",
                        "SensorName",
                        "SensorEName",
                        "UpdatedBy",
                        "UpdatedAt"
                    };
                    

                    await sensorTypeRepository.UpdateSensorInfo(update, properties);
                    apiResult.Code = "0000";
                    apiResult.Msg = "儲存成功";
                    #endregion
                }
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = errorCode.GetString(apiResult.Code);
                string json = System.Text.Json.JsonSerializer.Serialize(post);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return apiResult;
        }

        /// <summary>
        /// 控制器DataTable
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public async Task<ActionResult> SensorTypeDeviceTable()
        {
            ApiResult<List<SensorType>> apiResult = new ApiResult<List<SensorType>>();
            List<SensorType> sensorTypes = null;

            try
            {
                sensorTypes = await sensorTypeRepository.GetAllSensorAsync();
                foreach (SensorType a in sensorTypes)
                {
                    switch (a.Enabled)
                    {
                        case 0:
                            a.EnabledName = "未啟用";
                            break;
                        case 1:
                            a.EnabledName = "啟用";
                            break;
                        default:
                            a.EnabledName = "無資料";
                            break;
                    }
                }
                apiResult.Code = "0000";
                apiResult.Data = sensorTypes;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            apiResult.Msg = errorCode.GetString(apiResult.Code);
            var result = Json(new
            {
                data = apiResult
            });

            return result;
        }

        /// <summary>
        /// 軟刪除單一裝置類型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<string>> DeleteOneSensorType(int id)
        {
            ApiResult<string> apiResult = new ApiResult<string>();

            SensorType sensor = null;

            try
            {
                sensor = await sensorTypeRepository.GetOneSensorType(id);

                if (sensor == null)
                {
                    apiResult.Code = "9998";
                    apiResult.Msg = errorCode.GetString(apiResult.Code);
                    return apiResult;
                }

                await sensorTypeRepository.DeleteOne(sensor.Id);

                apiResult.Code = "0000";
                apiResult.Msg = "刪除成功";
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = errorCode.GetString(apiResult.Code);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + "Id=" + id);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            return apiResult;
        }

        /// <summary>
        /// 取得單一裝置類型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<SensorType>> GetOneSensorType(int id)
        {
            ApiResult<SensorType> apiResult = new ApiResult<SensorType>();

            SensorType simpleSensorType = null;

            try
            {
                simpleSensorType = await sensorTypeRepository.GetOneSensorType(id);

                if (simpleSensorType == null)
                {
                    apiResult.Code = "9998";
                    apiResult.Msg = errorCode.GetString(apiResult.Code);
                    return apiResult;
                }

                apiResult.Code = "0000";
                apiResult.Data = simpleSensorType;

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

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

        /// <summary>
        /// 取得單一裝置類型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<SensorDetail>> GetOneSensorTypeDetail(int id)
        {
            ApiResult<SensorDetail> apiResult = new ApiResult<SensorDetail>();

            SensorDetail simpleSensorType = null;

            try
            {
                simpleSensorType = await sensorDetailRepository.GetOneDetailByIdAsync(id);
                switch (simpleSensorType.HourType)
                {
                    case "Sum":
                        simpleSensorType.HourTypeName = "總數";
                        break;
                    case "Max":
                        simpleSensorType.HourTypeName = "最大值";
                        break;
                    case "Min":
                        simpleSensorType.HourTypeName = "最小值";
                        break;
                    case "Avg":
                        simpleSensorType.HourTypeName = "平均值";
                        break;
                    default:
                        simpleSensorType.HourTypeName = "無資料";
                        break;
                }
                switch (simpleSensorType.DayType)
                {
                    case "Sum":
                        simpleSensorType.DayTypeName = "總數";
                        break;
                    case "Max":
                        simpleSensorType.DayTypeName = "最大值";
                        break;
                    case "Min":
                        simpleSensorType.DayTypeName = "最小值";
                        break;
                    case "Avg":
                        simpleSensorType.DayTypeName = "平均值";
                        break;
                    default:
                        simpleSensorType.DayTypeName = "無資料";
                        break;
                }
                switch (simpleSensorType.MonthType)
                {
                    case "Sum":
                        simpleSensorType.MonthTypeName = "總數";
                        break;
                    case "Max":
                        simpleSensorType.MonthTypeName = "最大值";
                        break;
                    case "Min":
                        simpleSensorType.MonthTypeName = "最小值";
                        break;
                    case "Avg":
                        simpleSensorType.MonthTypeName = "平均值";
                        break;
                    default:
                        simpleSensorType.MonthTypeName = "無資料";
                        break;
                }

                if (simpleSensorType == null)
                {
                    apiResult.Code = "9998";
                    apiResult.Msg = errorCode.GetString(apiResult.Code);
                    return apiResult;
                }

                apiResult.Code = "0000";
                apiResult.Data = simpleSensorType;

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

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

        /// <summary>
        /// 新增 / 修改 設備-細項資料
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<string>> SaveSensorDetail(SensorDetail post)
        {
            ApiResult<string> apiResult = new ApiResult<string>();

            SensorDetail sensorDetail = null;

            string nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            try
            {
                sensorDetail = await sensorDetailRepository.GetOneAsync(post.Id);

                if (sensorDetail == null)
                {

                    if (post.Id != 0)
                    {
                        apiResult.Code = "9998";//待定
                        apiResult.Msg = errorCode.GetString(apiResult.Code);
                        return apiResult;
                    }

                    #region 新增設備-細項
                    sensorDetail = new SensorDetail()
                    {
                        Deleted = 0,
                        SensorTypeId = post.SensorTypeId,
                        ItemName = post.ItemName,
                        ItemEName = post.ItemEName,
                        HourType = post.HourType,
                        DayType = post.DayType,
                        MonthType = post.MonthType,
                        WarningURL = post.WarningURL,
                        UpperValue = post.UpperValue,
                        LowerValue = post.LowerValue,
                        CreatedBy = myUser.Id,
                        CreatedAt = nowTime
                    };

                    List<string> properties = new List<string>()
                    {
                        "Deleted",
                        "SensorTypeId",
                        "ItemName",
                        "ItemEName",
                        "HourType",
                        "DayType",
                        "MonthType",
                        "WarningURL",
                        "UpperValue",
                        "LowerValue",
                        "CreatedBy",
                        "CreatedAt"
                    };

                    var id = await sensorDetailRepository.AddOneAsync(sensorDetail, properties);

                    apiResult.Code = "0000";
                    apiResult.Msg = "儲存成功";
                    #endregion
                }
                else
                {
                    #region 修改設備-細項
                    SensorDetail update = new SensorDetail()
                    {
                        Id = sensorDetail.Id,
                        //SensorTypeId = post.SensorTypeId,
                        ItemName = post.ItemName,
                        ItemEName = post.ItemEName,
                        HourType = post.HourType,
                        DayType = post.DayType,
                        MonthType = post.MonthType,
                        WarningURL = post.WarningURL,
                        UpperValue = post.UpperValue,
                        LowerValue = post.LowerValue,
                        UpdatedBy = myUser.Id,
                        UpdatedAt = nowTime
                    };


                    List<string> properties = new List<string>()
                    {
                        "Id",
                        //"SensorTypeId",
                        "ItemName",
                        "ItemEName",
                        "HourType",
                        "DayType",
                        "MonthType",
                        "WarningURL",
                        "UpperValue",
                        "LowerValue",
                        "UpdatedBy",
                        "UpdatedAt"
                    };

                    await sensorDetailRepository.UpdateSensorDetailInfo(update, properties);
                    apiResult.Code = "0000";
                    apiResult.Msg = "儲存成功";
                    #endregion
                }
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = errorCode.GetString(apiResult.Code);
                string json = System.Text.Json.JsonSerializer.Serialize(post);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return apiResult;
        }

        [HttpPost]
        public async Task<ApiResult<List<SensorDetail>>> GetSensorDetail(int id)
        {
            ApiResult<List<SensorDetail>> apiResult = new ApiResult<List<SensorDetail>>();

            List<SensorDetail> sensorDetails = null;

            try
            {
                sensorDetails = await sensorDetailRepository.GetAllSensorDetailAsync(id);
                foreach (SensorDetail a in sensorDetails)
                {
                    switch (a.HourType)
                    {
                        case "Sum":
                            a.HourTypeName = "總數";
                            break;
                        case "Max":
                            a.HourTypeName = "最大值";
                            break;
                        case "Min":
                            a.HourTypeName = "最小值";
                            break;
                        case "Avg":
                            a.HourTypeName = "平均值";
                            break;
                        default:
                            a.HourTypeName = "無資料";
                            break;
                    }
                    switch (a.DayType)
                    {
                        case "Sum":
                            a.DayTypeName = "總數";
                            break;
                        case "Max":
                            a.DayTypeName = "最大值";
                            break;
                        case "Min":
                            a.DayTypeName = "最小值";
                            break;
                        case "Avg":
                            a.DayTypeName = "平均值";
                            break;
                        default:
                            a.DayTypeName = "無資料";
                            break;
                    }
                    switch (a.MonthType)
                    {
                        case "Sum":
                            a.MonthTypeName = "總數";
                            break;
                        case "Max":
                            a.MonthTypeName = "最大值";
                            break;
                        case "Min":
                            a.MonthTypeName = "最小值";
                            break;
                        case "Avg":
                            a.MonthTypeName = "平均值";
                            break;
                        default:
                            a.MonthTypeName = "無資料";
                            break;
                    }
                }

                if (sensorDetails == null)
                {
                    apiResult.Code = "9988";
                    apiResult.Msg = errorCode.GetString(apiResult.Code);
                    return apiResult;
                }

                apiResult.Code = "0000";
                apiResult.Data = sensorDetails;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = errorCode.GetString(apiResult.Code);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + "Id=" + id);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            return apiResult;
        }

        [HttpPost]
        public async Task<ApiResult<string>> DeleteOneSensorDetail(int id)
        {
            ApiResult<string> apiResult = new ApiResult<string>();

            try
            {
                var userPowerStation = sensorDetailRepository.GetOneAsync(id);

                if (userPowerStation == null)
                {
                    apiResult.Code = "9988";
                    apiResult.Msg = errorCode.GetString(apiResult.Code);
                    return apiResult;
                }

                await sensorDetailRepository.DeleteOne(id);

                apiResult.Code = "0000";
                apiResult.Msg = "刪除成功";
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = errorCode.GetString(apiResult.Code);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + "Id=" + id);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            return apiResult;
        }

    }
}
