using FluentScheduler;
using Newtonsoft.Json;
using Siger.ApiDashboard.Tasks.Model;
using Siger.ApiDashboard.Tasks.Reports;
using Siger.Middlelayer.AccRepository;
using Siger.Middlelayer.Common.FieldEnum;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.KpiRespository;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.QmsRepository;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.TpmRepository;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Siger.ApiDashboard.Tasks
{
    /// <summary>
    /// 月报自动推送任务
    /// </summary>
    public class AutoMonthReportJob : IJob
    {
        public AutoMonthReportJob()
        {
          
        }

        public void Execute()
        {
            try
            {
                ReportDbHelper.Instance.LoadDbContext();
                var configs = ReportDbHelper.Instance.GetAllConfigs();
                foreach (var cfg in configs)
                {
                    ExecuteConvert(cfg);
                }
            }
            catch (Exception e)
            {
                Logger.WriteLineError($"AutoMonthReport Execute,{e}");
            }
        }

        private void ExecuteConvert(siger_project_monthreport_config config)
        {
            var emailConfig = ReportDbHelper.Instance.GetEmailConfigs(config.project_id);
            if (emailConfig == null)
            {
                Logger.WriteLineError($"邮件服务器未配置,{config.project_id}");
                return;
            }

            var users = ReportDbHelper.Instance.UserEmails(config.user_mids);
            if (!users.Any())
            {
                Logger.WriteLineError($"用户邮箱地址为空,{config.user_mids}");
                return;
            }
            try
            {
                var MainTemplate = new List<object>();
                var templates = ReportDbHelper.Instance.GetRptTemplates(config.id);
                if (!templates.Any())
                    return;

                foreach (var temp in templates)
                {
                    Logger.WriteLineInfo($"config:{config.name} templateid{temp.id} template:{temp.title}");
                    var templateID = (ReportTemplate)temp.template_id;
                    switch (templateID)
                    {
                        case ReportTemplate.MachineOEE:
                            {
                                var oee = new MouduleMachineOee().GetOee(config, temp);
                                MainTemplate.Add(oee);
                                break;
                            }
                        case ReportTemplate.MachineSplit:
                            {
                                var split = new MouduleMachineSplitanalysis().GetSplitResult(config, temp);
                                MainTemplate.Add(split);
                                break;
                            }
                        case ReportTemplate.MachineCrop:
                            {
                                var crop = new ModuleCrop().GetCropResult(config, temp);
                                MainTemplate.Add(crop);
                                break;
                            }
                        case ReportTemplate.Productivity:
                            {
                                var pro = new ModuleProductivity().GetProductivityResult(config, temp);
                                MainTemplate.Add(pro);
                                break;
                            }
                        case ReportTemplate.MachineOfProductivity:
                            {
                                var machinePro = new ModuleProdcutOfMachine().GetProductivityOfMachine(config, temp);
                                MainTemplate.Add(machinePro);
                                break;
                            }
                        case ReportTemplate.MachineStateOfStop:
                            {
                                var stateStop = new MouduleStopStateOfMachine().GetStopStateOfMachine(config, temp);
                                MainTemplate.Add(stateStop);
                                break;
                            }
                        case ReportTemplate.FJWCustomization:
                            {
                                Logger.WriteLineInfo($"create FjwTemplate:{temp.title}");
                                var fjwCust = new MouduleFjwReport().GetReportResult(config, temp);
                                var strCust = JsonConvert.SerializeObject(fjwCust);
                                var resultCust = new CustomizationReport().GeneratePdf(config, strCust);
                                SendResult(config, emailConfig, users, resultCust);
                                break;

                            }
                    }
                }
                if (!MainTemplate.Any())
                    return;

                var strObj = JsonConvert.SerializeObject(MainTemplate);
                var result = new ReporterMain().GeneratePdf(config, strObj);
                SendResult(config, emailConfig, users, result);
            }
            catch (Exception e)
            {
                Logger.WriteLineError("convert pdf failed, error:" + e);
            }
        }

        void SendResult(siger_project_monthreport_config config, SigerProjectEmailConfig emailConfig, IEnumerable<siger_project_user> users, ConvertPdfResult result)
        {
            Logger.WriteLineInfo($"ConvertResult:{result.Result}");
            if (result.Result == ReportSendResult.Successful)
            {
                var url = config.send_type == 0 ? result.HtmlPath : result.PdfPath;
                try
                {
                    var body = config.remark.Replace("\n", "<br>");
                    MailHelper.SendMailForUsers(emailConfig.server, true, emailConfig.send, emailConfig.code,
                       emailConfig.send, emailConfig.send, users.Select(t => t.work_email).ToList(),
                       config.name, body, new List<string> { url });
                }
                catch (Exception e)
                {
                    Logger.WriteLineError($"发送邮件失败,{e}");
                }
                ReportDbHelper.Instance.AddSendRecord(config.id, string.Join(",", users.Select(t => t.name).ToList()), url);
            }
        }
    }
}
