using BlazorDownloadFile;
using KarleyLibrary.Erweiterungen;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WK5.Core;
using WK5.Core.Basis;
using WK5.Core.Drucken.Briefe;
using WK5.Core.Models;
using WK5.Core.PageModels.Stammdaten.Kunden;

namespace WK5_Blazor.Components
{
    public partial class KundenKontaktForm
    {
#nullable disable
        [CascadingParameter] public AppMitarbeiter Mitarbeiter { get; set; }
#nullable enable


        [Parameter] public Kundenkontakt Input { get; set; } = new();
        private Kundenkontakt StartCopy { get; set; } = new();
        [Parameter] public EventCallback<Kundenkontakt> OnAfterCancel { get; set; }
        [Parameter] public EventCallback<Kundenkontakt> OnAfterDownload { get; set; }
        [Parameter] public EventCallback<Kundenkontakt> OnAfterEdit { get; set; }
        [Parameter] public EventCallback<Kundenkontakt> OnAfterCreate { get; set; }
        [Parameter] public EventCallback<Kundenkontakt> OnAfterTimeExtension { get; set; }
        [Parameter] public EventCallback<Kundenkontakt> OnAfterDelete { get; set; }
        [Parameter] public string SaveButtonMarkup { get; set; } = "<i class=\"fas fa-save\"></i>";
        [Parameter] public string ReturnButtonMarkup { get; set; } = "<i class=\"fas fa-reply\"></i>";
        public bool ShowBriefHeader { get; set; }
        public List<Ansprechpartner> Hauptansprechpartner { get; set; } = new List<Ansprechpartner>();
        public List<Ansprechpartner> NormaleAnsprechpartner { get; set; } = new List<Ansprechpartner>();
        private bool _wiedervorlageAnlegen = true;
        public bool WiedervorlageAnlegen
        {
            get => _wiedervorlageAnlegen;
            set
            {
                _wiedervorlageAnlegen = value;

                if (Input is not null)
                {
                    Input.KUKO_L_WIEDERV_ERL = !_wiedervorlageAnlegen;
                }
            }
        }

        private bool _showDeleteModal { get; set; }
        public bool DownloadSperre { get; set; }
        [Parameter] public bool ShowCancelButton { get; set; } = true;
        [Parameter] public bool ShowDownloadButton { get; set; } = true;
        [Parameter] public bool ShowDeleteButton { get; set; } = true;
        [Parameter] public bool ShowTimeExtensionButtons { get; set; } = false;

        public List<Lieferanschrift> Lieferanschriften { get; set; } = new List<Lieferanschrift>();
        public List<Rechnungsanschrift> Rechnungsanschriften { get; set; } = new List<Rechnungsanschrift>();
        public EditMode Modus { get; set; } = EditMode.Anlage;
        public int AdressenId { get; set; } = 0;
        protected override async Task OnParametersSetAsync()
        {
            if (Input is not null)
            {
                Modus = Input.KUKO_N_ID > 0 ? EditMode.Bearbeiten : EditMode.Anlage;
                if (!String.IsNullOrWhiteSpace(Input.KUKO_A_KUNDNR))
                {
                    var tmpPartner = await Ansprechpartner.GetAnsprechpartnerAsync(Input.KUKO_A_KUNDNR).ToListAsync();

                    Hauptansprechpartner = tmpPartner.Where(x => x.PART_WK5_L_HAUPT).OrderBy(x => x.PART_A_VORNAME + " " + x.PART_A_NAME).ToList();
                    NormaleAnsprechpartner = tmpPartner.Where(x => !x.PART_WK5_L_HAUPT).OrderBy(x => x.PART_A_VORNAME + " " + x.PART_A_NAME).ToList();

                    Lieferanschriften = await Lieferanschrift.GetLieferanschriftenAsync(Input.KUKO_A_KUNDNR).ToListAsync();
                    Rechnungsanschriften = await Rechnungsanschrift.GetRechnungsanschriftenAsync(Input.KUKO_A_KUNDNR).ToListAsync();
                }




                StartCopy = Input.DeepCopy();
            }
        }

        private async Task ExtendTime(int minutes)
        {
            if (Input is not null)
            {
                Input.KUKO_T_WIEDERV_TIME = DateTime.Now.AddMinutes(minutes);
                Input.KUKO_D_WIEDERV_DATE = DateTime.Now.AddMinutes(minutes);
                await SaveAsync();
                await OnAfterTimeExtension.InvokeAsync(Input);
            }

        }

        private async Task ExtendTimeRandom(int from, int to)
        {
            Random rnd = new Random();
            await ExtendTime(rnd.Next(from, to + 1));
        }

        private async Task SaveAsync()
        {
            if (Input is not null)
            {
                using FbController2 fbController = new FbController2(Mitarbeiter.PersonalNummer);
                switch (Modus)
                {
                    case EditMode.Anlage:
                        {
                            await kundenkontaktService.CreateAsync(Input, fbController);
                            await OnAfterCreate.InvokeAsync(Input);
                        }
                        break;
                    case EditMode.Bearbeiten:
                        {
                            await kundenkontaktService.UpdateAsync(Input, fbController);
                            await OnAfterEdit.InvokeAsync(Input);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private async Task DownloadAsync()
        {
            if (Input is null)
            {
                return;
            }

            DownloadSperre = true;

            BriefView view = new BriefView(Input.KUKO_WK5_A_BETREFF ?? "", Input.KUKO_WK5_B_LANGNOTIZ ?? String.Empty);


            Kunde? kunde = await Kunde.GetKundeAsync(Input.KUKO_A_KUNDNR);
            Ansprechpartner? partner = await Ansprechpartner.GetAnsprechpartnerByNameAsync(kunde.KUND_A_NR, Input.KUKO_A_PARTNER ?? String.Empty);

            if (partner is not null)
            {
                await view.SetEmpfängerAsync(partner);
            }
            else
            {
                if (kunde is not null)
                {
                    await view.SetEmpfängerAsync(kunde);
                }
            }

            Personal? versender = await Personal.GetPersonalAsync(Mitarbeiter.PersonalNummer);
            if (versender is not null)
            {
                view.SetAbsender(versender);
            }


            if (AdressenId != 0)
            {
                // Adressenid < 0 = Rechnungsanschrift
                // Adressenid > 0 = Lieferanschrift
                // Adressenid = 0 = Nichts
                if (AdressenId < 0)
                {
                    int id = AdressenId * -1;
                    Rechnungsanschrift? anschrift = Rechnungsanschriften.Where(x => x.KURE_N_NR == id).FirstOrDefault();
                    if (anschrift is not null)
                        await view.SetAdresse(anschrift);
                }
                else
                {
                    int id = AdressenId;
                    Lieferanschrift? anschrift = Lieferanschriften.Where(x => x.KULA_N_NR == id).FirstOrDefault();
                    if (anschrift is not null)
                        await view.SetAdresse(anschrift);

                }
            }


            BriefRegelsatz briefRegeln = new BriefRegelsatz()
            {
                ShowFooter = ShowBriefHeader,
                ShowHeader = ShowBriefHeader
            };

            PrintBrief printBrief = await PrintBrief.CreateAsync(view, briefRegeln);

            byte[] file = printBrief.PrintToMemory();

            await downloadService.DownloadFile($"Brief-{Input.KUKO_A_KUNDNR}.pdf", file, "application/pdf");
            await downloadService.ClearBuffers();

            DownloadSperre = false;

            await OnAfterDownload.InvokeAsync(Input);
        }

        private async Task DeleteKontaktAsync()
        {
            if (Input is null)
            {
                return;
            }

            if (Modus is EditMode.Bearbeiten)
            {
                FbController2 fbController = new FbController2(Mitarbeiter.PersonalNummer);
                await kundenkontaktService.DeleteAsync(Input, fbController);
            }

            await OnAfterDelete.InvokeAsync(Input);
        }
    }
}
