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

namespace SolarPower.Controllers
{
    public class OperationController : MyBaseController<OperationController>
    {
        private readonly IOperationRepository operationRepository;
        private string operationRecodeFilePath = "/upload/operation_recode/";
        private string operationRecodeSaveAsPath = "";


        public OperationController(
            IOperationRepository operationRepository) : base()
        {
            this.operationRepository = operationRepository;

            operationRecodeSaveAsPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "upload", "operation_recode");
        }

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

        public IActionResult Record()
        {
            return View("~/Views/Operation/OperationRecord.cshtml");
        }

        /// <summary>
        /// 取得電站Option
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<PowerStationIdList>>> GetPowerStationSelectOption()
        {
            ApiResult<List<PowerStationIdList>> apiResult = new ApiResult<List<PowerStationIdList>>();
            try
            {
                var PowerStationIdLists = new List<PowerStationIdList>();
                PowerStationIdLists = await operationRepository.GetPowerStationIdList(myUser.Id);
                apiResult.Code = "0000";
                apiResult.Data = PowerStationIdLists;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

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

        /// <summary>
        /// 儲存計畫
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> SaveOperationPlan(OperationCreatePlanModal post)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            try
            {
                if(Convert.ToDateTime(post.StartTime) < Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")))
                {
                    apiResult.Msg = "開始時間不能選擇過去";
                    apiResult.Code = "0099";
                    return apiResult;
                }


                if (post.Id == 0)
                {
                    var now = DateTime.Now.ToString("yyyy-MM-dd");
                    var finalid = await operationRepository.GetCurrentSerialNumber("operation_plan_create", $"PowerStationId = {post.PowerStationId} AND CreatedAt LIKE '%{now}%'");
                    var newSerialNumber = GetLastSerialNumber(finalid);
                    var OperationPlan = new OperationCreatePlan()
                    {
                        EmailType = post.EmailType,
                        ScheduleNum = post.ScheduleNum,
                        Description = post.Description,
                        WorkDay = post.WorkDay,
                        ScheduleType = post.ScheduleType,
                        SerialNumber = newSerialNumber,
                        StartTime = post.StartTime,
                        PowerStationId = post.PowerStationId,
                        Type = post.Type,
                        PlanId = DateTime.Now.ToString("yyyyMMdd") + newSerialNumber,
                        CreatedBy = myUser.Id
                    };
                    List<string> properties = new List<string>()
                    {
                        "EmailType",
                        "ScheduleNum",
                        "Description",
                        "WorkDay",
                        "ScheduleType",
                        "SerialNumber",
                        "StartTime",
                        "PowerStationId",
                        "Type",
                        "PlanId",
                        "CreatedBy"
                    };

                    
                    
                    if(post.StartTime == DateTime.Now.ToString("yyyy-MM-dd"))
                    {
                        string endtime = "";
                        switch (post.ScheduleType)
                        {
                            case 0:
                                endtime = (Convert.ToDateTime(post.StartTime).AddDays(post.ScheduleNum)).ToString("yyyy-MM-dd 00:00:00");break;
                            case 1:
                                endtime = (Convert.ToDateTime(post.StartTime).AddDays(post.ScheduleNum * 7)).ToString("yyyy-MM-dd 00:00:00"); break;
                            case 2:
                                endtime = (Convert.ToDateTime(post.StartTime).AddMonths(post.ScheduleNum)).ToString("yyyy-MM-dd 00:00:00"); break;
                            case 3:
                                endtime = (Convert.ToDateTime(post.StartTime).AddMonths(post.ScheduleNum * 3)).ToString("yyyy-MM-dd 00:00:00"); break;
                            case 4:
                                endtime = (Convert.ToDateTime(post.StartTime).AddYears(post.ScheduleNum * 3)).ToString("yyyy-MM-dd 00:00:00"); break;
                        }
                        var record = new PlanToRecord()
                        {
                            WorkType = post.Type,
                            PowerStationId = post.PowerStationId,
                            StartTime = post.StartTime,
                            CreatedBy = myUser.Id,
                            EndTime = endtime
                        };
                        List<string> properties2 = new List<string>()
                        {
                            "WorkType",
                            "PowerStationId",
                            "StartTime",
                            "CreatedBy",
                            "EndTime"
                        };
                        OperationPlan.LastCreateTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                        properties.Add("LastCreateTime");

                        await operationRepository.AddToRecord(record, properties2);
                    }
                    await operationRepository.AddOperationPlan(OperationPlan, properties);
                    apiResult.Code = "0000";
                    apiResult.Msg = "新增成功";
                }
                else
                {
                    var OperationPlan = new OperationCreatePlan()
                    {
                        Id = post.Id,
                        EmailType = post.EmailType,
                        ScheduleNum = post.ScheduleNum,
                        Description = post.Description,
                        WorkDay = post.WorkDay,
                        ScheduleType = post.ScheduleType,
                        StartTime = post.StartTime,
                        PowerStationId = post.PowerStationId,
                        Type = post.Type,
                        UpdatedBy = myUser.Id
                    };
                    List<string> properties = new List<string>()
                    {
                        "Id",
                        "EmailType",
                        "ScheduleNum",
                        "Description",
                        "WorkDay",
                        "ScheduleType",
                        "StartTime",
                        "PowerStationId",
                        "Type",
                        "UpdatedBy"
                    };
                    if (post.StartTime == DateTime.Now.ToString("yyyy-MM-dd"))
                    {
                        string endtime = "";
                        switch (post.ScheduleType)
                        {
                            case 0:
                                endtime = (Convert.ToDateTime(post.StartTime).AddDays(post.ScheduleNum)).ToString("yyyy-MM-dd 00:00:00"); break;
                            case 1:
                                endtime = (Convert.ToDateTime(post.StartTime).AddDays(post.ScheduleNum * 7)).ToString("yyyy-MM-dd 00:00:00"); break;
                            case 2:
                                endtime = (Convert.ToDateTime(post.StartTime).AddMonths(post.ScheduleNum)).ToString("yyyy-MM-dd 00:00:00"); break;
                            case 3:
                                endtime = (Convert.ToDateTime(post.StartTime).AddMonths(post.ScheduleNum * 3)).ToString("yyyy-MM-dd 00:00:00"); break;
                            case 4:
                                endtime = (Convert.ToDateTime(post.StartTime).AddYears(post.ScheduleNum * 3)).ToString("yyyy-MM-dd 00:00:00"); break;
                        }
                        var record = new PlanToRecord()
                        {
                            WorkType = post.Type,
                            PowerStationId = post.PowerStationId,
                            StartTime = post.StartTime,
                            CreatedBy = myUser.Id,
                            EndTime = endtime
                        };
                        List<string> properties2 = new List<string>()
                        {
                            "WorkType",
                            "PowerStationId",
                            "StartTime",
                            "CreatedBy",
                            "EndTime"
                        };
                        OperationPlan.LastCreateTime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                        properties.Add("LastCreateTime");

                        await operationRepository.AddToRecord(record, properties2);
                    }

                    await operationRepository.UpdateOperationPlan(OperationPlan, properties);
                    apiResult.Code = "0000";
                    apiResult.Msg = "編輯成功";
                }



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

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

        /// <summary>
        /// 定時計畫datatable
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> OperationPlanTable(List<int> id, int type)
        {
            List<OperationPlanTable> OperationPlanTable = new List<OperationPlanTable>();
            ApiResult<List<OperationPlanTable>> apiResult = new ApiResult<List<OperationPlanTable>>();
            try
            {
                apiResult.Code = "0000";
                OperationPlanTable = await operationRepository.OperationPlanTable(id, type);
                foreach (OperationPlanTable a in OperationPlanTable)
                {
                    if (a.Type == 0)
                    {
                        a.TypeName = "清洗";
                    }
                    else
                    {
                        a.TypeName = "巡檢";
                    }

                    if (a.ScheduleType == 0)
                    {
                        a.Schedule = "每" + a.ScheduleNum.ToString() + "天";
                    }
                    else if (a.ScheduleType == 1)
                    {
                        a.Schedule = "每" + a.ScheduleNum.ToString() + "周";
                    }
                    else if (a.ScheduleType == 2)
                    {
                        a.Schedule = "每" + a.ScheduleNum.ToString() + "月";
                    }
                    else if (a.ScheduleType == 3)
                    {
                        a.Schedule = "每" + a.ScheduleNum.ToString() + "季";
                    }
                    else if (a.ScheduleType == 4)
                    {
                        a.Schedule = "每" + a.ScheduleNum.ToString() + "年";
                    }

                    a.StartTimeString = a.StartTime;
                    var crst = a.CreatedAt.Split(" ");
                    a.CreateTimeString = crst[0];

                    if (a.EmailType == 0)
                    {
                        a.EmailTypeName = "當天";
                    }
                    else if (a.EmailType == 1)
                    {
                        a.EmailTypeName = "前一天";
                    }
                    else if (a.EmailType == 2)
                    {
                        a.EmailTypeName = "前兩天";
                    }
                    else if (a.EmailType == 3)
                    {
                        a.EmailTypeName = "前三天";
                    }

                    a.Function = @"
                                <button type='button' class='btn btn-primary btn-pills waves-effect waves-themed edit-btn'>修改</button>
                                <button type='button' class='btn btn-danger btn-pills waves-effect waves-themed del-btn'>刪除</button>";
                }

                apiResult.Data = OperationPlanTable;

            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = exception.ToString();
            }
            var result = Json(new
            {
                data = apiResult
            });

            return result;
        }
        /// <summary>
        /// 刪除定時計畫
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> DeleteOneOperationPlan(int Id)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            OperationCreatePlan operation = new OperationCreatePlan();
            try
            {
                operation = await operationRepository.GetOneOperation(Id);

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

                await operationRepository.DeleteOneByIdWithCustomTable(Id, "operation_plan_create");

                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;
        }

        public async Task<ApiResult<OperationCreatePlan>> GetOneOperationPlan(int Id)
        {
            ApiResult<OperationCreatePlan> apiResult = new ApiResult<OperationCreatePlan>();
            OperationCreatePlan operationCreatePlan = new OperationCreatePlan();
            try
            {
                apiResult.Code = "0000";
                operationCreatePlan = await operationRepository.GetOneOperation(Id);
                apiResult.Data = operationCreatePlan;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = exception.ToString();
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + "Id=" + Id);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return apiResult;
        }

        /// <summary>
        /// 運維作業記錄列表
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> OperationRecodeListAsync(PostOperationRecodeFilter post)
        {
            ApiResult<List<OperationRecodeDataTable>> apiResult = new ApiResult<List<OperationRecodeDataTable>>();

            int totalRecords = 0; //總資料筆數
            int recFilter = 0; //過濾後資料筆數

            List<OperationRecodeDataTable> recodes = null;

            try
            {

                recodes = await operationRepository.GetAllRecodeByFilterAsync(post);

                foreach (var recode in recodes)
                {
                    if (string.IsNullOrEmpty(recode.FormId))
                    {
                        recode.FormId = @$"<a href='javascript:;' class='btn btn-success waves-effect waves-themed mb-3 mr-2 edit-btn'>填寫表單</a>";
                    }
                    else
                    {
                        recode.FormId = @$"<a href='javascript:;' class='waves-effect waves-themed mb-3 mr-2 edit-btn'>{recode.FormId}</a>";
                    }

                    if (recode.RecodeFiles != null && recode.RecodeFiles.Count > 0)
                    {
                        foreach (var file in recode.RecodeFiles)
                        {
                            file.FileName = Path.Combine(operationRecodeFilePath, recode.Id.ToString()) + "/" + file.FileName;
                        }
                    }
                }

                totalRecords = recodes.Count();
                recFilter = recodes.Count();

                apiResult.Code = "0000";
                apiResult.Data = recodes;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                string json = System.Text.Json.JsonSerializer.Serialize(post);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            apiResult.Msg = errorCode.GetString(apiResult.Code);
            var result = Json(new
            {
                recordsTotal = totalRecords,
                recordsFiltered = recFilter,
                data = apiResult
            });

            return result;
        }

        /// <summary>
        /// 取得單一運維作業記錄列表
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<OperationRecode>> GetOneOperationRecode(int id)
        {
            ApiResult<OperationRecode> apiResult = new ApiResult<OperationRecode>();

            OperationRecode operationRecode;

            try
            {

                //if (!IsPlatformLayer(myUser.Role.Layer))
                //{   //如果只是身分公司管理員 或 公司使用者，就只能看自己公司的資料
                //    post.SelectedCompanyId = myUser.CompanyId;
                //}

                operationRecode = await operationRepository.GetOneOperationRecodeAsync(id);

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

                foreach (var recodeFile in operationRecode.RecodeFiles)
                {
                    recodeFile.FileName = Path.Combine(operationRecodeFilePath, operationRecode.Id.ToString()) + "/" + recodeFile.FileName;
                }

                apiResult.Code = "0000";
                apiResult.Data = operationRecode;
            }
            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="post"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> SaveOperationRecode([FromForm] PostOperationRecode post)
        {
            ApiResult<int> apiResult = new ApiResult<int>();

            OperationRecode operationRecode = null;

            try
            {
                operationRecode = await operationRepository.GetOneOperationRecodeAsync(post.Id);

                //取得運維作業記錄最後流水號
                var currentSerialNumber = await operationRepository.GetCurrentSerialNumber("operation_record");

                if (operationRecode == null)
                {
                    if (post.Id != 0)
                    {
                        apiResult.Code = "9989";
                        apiResult.Msg = errorCode.GetString(apiResult.Code);
                        return apiResult;
                    }

                    #region 新增運維作業記錄 - 維修單

                    var tempSerialNumber = GetLastSerialNumber(currentSerialNumber);

                    var finishTime = string.Empty;
                    if (post.Status == (int)OperationRecodeStatusEnum.Complete)
                    {
                        finishTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    }

                    operationRecode = new OperationRecode()
                    {
                        FormId = "op" + DateTime.Now.ToString("yyyyMMdd") + tempSerialNumber,
                        SerialNumber = tempSerialNumber,
                        PowerStationId = post.PowerStationId,
                        WorkType = (int)OperationRecodeWorkTypeEnum.Fix,
                        ErrorCode = post.ErrorCode,
                        FixDo = post.FixDo,
                        Status = post.Status,
                        WorkPersonId = post.WorkPersonId,
                        FinishTime = finishTime,
                        WorkTime = post.WorkTime,
                        Notice = post.Notice,
                        Description = post.Description,
                        CreatedBy = myUser.Id
                    };

                    List<string> properties = new List<string>()
                    {
                        "FormId",
                        "SerialNumber",
                        "PowerStationId",
                        "WorkType",
                        "ErrorCode",
                        "FixDo",
                        "Status",
                        "WorkPersonId",
                        "FinishTime",
                        "WorkTime",
                        "Notice",
                        "Description",
                        "CreatedBy"
                    };

                    var id = await operationRepository.AddOneOperationRecodeAsync(operationRecode, properties);

                    apiResult.Code = "0000";
                    apiResult.Msg = "儲存成功";
                    apiResult.Data = id;
                    #endregion
                }
                else
                {

                    #region 修改運維作業記錄

                    var finishTime = string.Empty;
                    if (post.Status == (int)OperationRecodeStatusEnum.Complete)
                    {
                        finishTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    }

                    if (operationRecode.WorkType != (int)OperationRecodeWorkTypeEnum.Fix)
                    {   //針對清洗、巡檢
                        var now = DateTime.Now;

                        var startTime = DateTime.Parse(post.StartTime + " 00:00:00");
                        var endTime = DateTime.Parse(post.EndTime + " 23:59:59");

                        if (now > endTime)
                        {
                            if (post.Status == (int)OperationRecodeStatusEnum.NoneComplete)
                            {   //超過時間修改成 未完成-過期
                                post.Status = (int)OperationRecodeStatusEnum.NoneCompleteExpired;
                            }
                            else if (post.Status == (int)OperationRecodeStatusEnum.Complete)
                            {   //超過時間修改成 完成-過期
                                post.Status = (int)OperationRecodeStatusEnum.CompleteExpired;
                            }
                        }
                    }

                    UpdateOperationRecode update = new UpdateOperationRecode()
                    {
                        Id = post.Id,
                        ErrorCode = post.ErrorCode,
                        FixDo = post.FixDo,
                        Status = post.Status,
                        FinishTime = !string.IsNullOrEmpty(finishTime) ? finishTime : null,
                        WorkPersonId = post.WorkPersonId,
                        WorkTime = post.WorkTime,
                        Notice = post.Notice,
                        Description = post.Description,
                        UpdatedBy = myUser.Id
                    };



                    List<string> properties = new List<string>()
                    {
                        "Id",
                        "ErrorCode",
                        "FixDo",
                        "Status",
                        "FinishTime",
                        "WorkTime",
                        "Notice",
                        "Description",
                        "WorkPersonId",
                        "UpdatedBy",
                    };

                    if (string.IsNullOrEmpty(operationRecode.FormId))
                    {
                        var tempSerialNumber = GetLastSerialNumber(currentSerialNumber);

                        update.FormId = "op" + DateTime.Now.ToString("yyyyMMdd") + tempSerialNumber;
                        update.SerialNumber = tempSerialNumber;

                        properties.Add("FormId");
                        properties.Add("SerialNumber");
                    }

                    await operationRepository.UpdateOperationRecodeAsync(update, properties);

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

            return apiResult;
        }

        public async Task<ApiResult<string>> DeleteOneOperationRecode(int id)
        {
            ApiResult<string> apiResult = new ApiResult<string>();

            try
            {
               var  operationRecode = await operationRepository.GetOneOperationRecodeAsync(id);

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

                await operationRepository.DeleteOneOperationRecodeAsync(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="post"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<OperationRecode>> SaveOperationRecodeFile([FromForm] PostOperationRecode post)
        {
            ApiResult<OperationRecode> apiResult = new ApiResult<OperationRecode>();

            OperationRecode operationRecode = null;

            try
            {
                operationRecode = await operationRepository.GetOneOperationRecodeAsync(post.Id);

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

                #region 新增運維作業記錄檔案
                List<OperationRecodeFile> operationRecodeFiles;

                if (post.RecodeFiles != null && post.RecodeFiles.Length > 0)
                {
                    FolderFunction folderFunction = new FolderFunction();

                    var fileSaveAsPath = Path.Combine(operationRecodeSaveAsPath, operationRecode.Id.ToString());

                    folderFunction.CreateFolder(fileSaveAsPath, 0);

                    operationRecodeFiles = new List<OperationRecodeFile>();

                    foreach (var file in post.RecodeFiles)
                    {
                        var split = file.FileName.Split(".");

                        var fileName = Guid.NewGuid() + "." + split[split.Length - 1];

                        var fullPath = Path.Combine(fileSaveAsPath, fileName);

                        using (var stream = new FileStream(fullPath, FileMode.Create))
                        {
                            file.CopyTo(stream);
                        }

                        OperationRecodeFile operationRecodeFile = new OperationRecodeFile()
                        {
                            RecordId = operationRecode.Id,
                            FileName = fileName,
                            CreatedBy = myUser.Id
                        };

                        operationRecodeFiles.Add(operationRecodeFile);
                    }

                    List<string> fileProperties = new List<string>()
                        {
                            "RecordId",
                            "FileName",
                            "CreatedBy"
                        };

                    await operationRepository.AddOperationRecodeFilesAsync(operationRecodeFiles, fileProperties);
                }
                #endregion

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

            return apiResult;
        }

        public async Task<ApiResult<string>> DeleteOperationRecodeFile(PostOperationRecodeIdAndSelectedId post)
        {
            ApiResult<string> apiResult = new ApiResult<string>();

            OperationRecode operationRecode = null;
            OperationRecodeFile operationRecodeFile = null;

            try
            {
                operationRecode = await operationRepository.GetOneOperationRecodeAsync(post.ReocdeId);

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

                operationRecodeFile = await operationRepository.GetOneOperationRecodeFileAsync(post.SelectedId);

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

                await operationRepository.DeleteOneOperationRecodeFile(post.SelectedId);

                apiResult.Code = "0000";
                apiResult.Msg = "刪除成功";
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = errorCode.GetString(apiResult.Code);
                string json = System.Text.Json.JsonSerializer.Serialize(post);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            return apiResult;
        }

        public async Task<ApiResult<List<OperationRecodeDataTable>>> ExportOperationRecodeExcel(PostOperationRecodeFilter post)
        {
            ApiResult<List<OperationRecodeDataTable>> apiResult = new ApiResult<List<OperationRecodeDataTable>>();

            List<OperationRecodeDataTable> recodes = null;

            try
            {

                //if (!IsPlatformLayer(myUser.Role.Layer))
                //{   //如果只是身分公司管理員 或 公司使用者，就只能看自己公司的資料
                //    post.SelectedCompanyId = myUser.CompanyId;
                //}

                recodes = await operationRepository.GetAllRecodeByFilterAsync(post);

                foreach (var recode in recodes)
                {
                    recode.PowerStationName = !string.IsNullOrEmpty(recode.PowerStationName) ? recode.PowerStationName : "";
                    recode.FormId = !string.IsNullOrEmpty(recode.FormId) ? recode.FormId : "";
                    recode.FixDo = !string.IsNullOrEmpty(recode.FixDo) ? recode.FixDo : "";
                    recode.WorkPersonName = !string.IsNullOrEmpty(recode.WorkPersonName) ? recode.WorkPersonName : "";
                    //recode.FinishTime = !string.IsNullOrEmpty(recode.FinishTime) ? recode.FinishTime : "";

                    if (recode.RecodeFiles != null && recode.RecodeFiles.Count > 0)
                    {
                        foreach (var file in recode.RecodeFiles)
                        {
                            var hyperLink = "<a href='" + baseURL + file.FileName + "'>" + file.FileName + "</a>";
                            if(recode.HyperLinks == null)
                            {
                                recode.HyperLinks = new List<string>();
                            }
                            recode.HyperLinks.Add(hyperLink);
                        }
                    }
                }

                apiResult.Code = "0000";
                apiResult.Data = recodes;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                string json = System.Text.Json.JsonSerializer.Serialize(post);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

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

        public async void Schedule ()
        {
            try {
                var getTime = await operationRepository.GetOperationSchedules();
                foreach(OperationCreatePlanModal a in getTime)
                {
                    DateTime Updatedtime;
                    if (a.ScheduleType == 0)//日
                    {
                        Updatedtime = Convert.ToDateTime(a.StartTime).AddDays(a.ScheduleNum);
                    }
                    else if(a.ScheduleType == 1)//周
                    {
                        Updatedtime = Convert.ToDateTime(a.StartTime).AddDays(a.ScheduleNum * 7);
                    }
                    else if (a.ScheduleType == 2)//月
                    {
                        Updatedtime = Convert.ToDateTime(a.StartTime).AddMonths(a.ScheduleNum);
                    }
                    else if (a.ScheduleType == 3)//季
                    {
                        Updatedtime = Convert.ToDateTime(a.StartTime).AddMonths(a.ScheduleNum * 3);
                    }
                    else // 年
                    {
                        Updatedtime = Convert.ToDateTime(a.StartTime).AddYears(a.ScheduleNum);
                    }

                    if (Updatedtime < DateTime.Now)
                    {
                        var now = DateTime.Now.ToString("yyyy-MM-dd");
                        var finalid = await operationRepository.GetCurrentSerialNumber("operation_plan_create", $"PowerStationId = {a.PowerStationId} AND CreatedAt LIKE '%{now}%'");
                        var newSerialNumber = GetLastSerialNumber(finalid);
                        var OperationPlan = new OperationCreatePlan()
                        {
                            EmailType = a.EmailType,
                            ScheduleNum = a.ScheduleNum,
                            Description = a.Description,
                            WorkDay = a.WorkDay,
                            ScheduleType = a.ScheduleType,
                            SerialNumber = newSerialNumber,
                            StartTime = Updatedtime.ToString("yyyy-MM-dd hh:mm:ss"),
                            PowerStationId = a.PowerStationId,
                            Type = a.Type,
                            PlanId = DateTime.Now.ToString("yyyyMMdd") + newSerialNumber,
                            CreatedBy = myUser.Id
                        };
                        List<string> properties = new List<string>()
                        {
                            "EmailType",
                            "ScheduleNum",
                            "Description",
                            "WorkDay",
                            "ScheduleType",
                            "SerialNumber",
                            "StartTime",
                            "PowerStationId",
                            "Type",
                            "PlanId",
                            "CreatedBy"
                        };
                        await operationRepository.AddOperationPlan(OperationPlan, properties);

                        var record = new PlanToRecord()
                        {
                            WorkType = a.Type,
                            PowerStationId = a.PowerStationId,
                            StartTime = Updatedtime.ToString("yyyy-MM-dd hh:mm:ss"),
                            CreatedBy = myUser.Id,
                            EndTime = Updatedtime.AddDays(a.WorkDay).ToString("yyyy-MM-dd hh:mm:ss")
                        };
                        List<string> properties2 = new List<string>()
                        {
                            "WorkType",
                            "PowerStationId",
                            "StartTime",
                            "CreatedBy",
                            "EndTime"
                        };
                        await operationRepository.AddToRecord(record, properties2);
                        var operation = await operationRepository.GetOneOperation(a.Id);
                        await operationRepository.DeleteOneByIdWithCustomTable(a.Id, "operation_plan_create");

                    }

                }
            }
            catch (Exception exception)
            {
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
        }

    }
}
