package srv

import (
	"bordrobot/lib/bot"
	"bordrobot/lib/company"
	"bordrobot/lib/run"
	"fmt"
	"log/slog"

	"github.com/shopspring/decimal"
	"github.com/wailsapp/wails/v3/pkg/application"
	"github.com/xuri/excelize/v2"
)

type Srv struct {
	xlsFileName string
}

func (s *Srv) Companies() ([]company.Company, error) {
	var res []company.Company
	err := run.DB.Select(&res, "SELECT * FROM company order by 1")
	return res, err
}

func (s *Srv) CreateCompany(name, memberNumber, username, password string) error {
	c := &company.Company{
		Name:         name,
		MemberNumber: memberNumber,
		Username:     username,
		Password:     password,
	}

	return c.Create()
}

func (s *Srv) UploadExcel() string {
	dialog := application.OpenFileDialog()
	dialog.AddFilter("Excel Dosyaları", "*.xls;*.xlsx")
	dialog.SetTitle("Bordro Excel Dosyası Yükleme")
	file, err := dialog.PromptForSingleSelection()
	if err != nil {
		return ""
	}
	s.xlsFileName = file
	return file
}

type userInfo struct {
	userName  string
	password  string
	accountNo string
}

func (s *Srv) Rpa(companyName string, month float64, year float64) error {
	type CompanyInfo struct {
		company *company.Company // float64.Company türünü gömme
		month   float64          // yeni bir alan ekliyoruz
		year    float64
	}
	user, err := company.GetCompany(companyName)
	if err != nil {
		return err
	}
	// companyInfo := CompanyInfo{
	// 	company: &user,
	// 	month:   month,
	// 	year:    year,
	// }

	//todo: readb company details by name
	b := bot.NewLucaBot()
	err = b.Login(user, month, year)
	if err != nil {
		//todo: inform user about process and errors
		emitLog("Şifreniz Hatalı")
		return nil

	}
	err = b.PayrollPageLogin()

	slog.Debug("inputs", "year", year, "month", month)

	f, err := excelize.OpenFile(s.xlsFileName)
	if err != nil {
		slog.Error(err.Error())
		return err
	}
	defer func() {
		// Close the spreadsheet.
		if err := f.Close(); err != nil {
			slog.Error(err.Error())
			//return err
		}
	}()

	sheets := f.GetSheetList()
	rows, err := f.GetRows(sheets[0])
	fmt.Println(rows)
	if err != nil {
		slog.Error(err.Error())
		return err
	}
	if rows[0][0] == "" {
		rows = rows[1:]
	}
	var insertMessage []string
	var lastItem bool = false
	// data := make([]*model.Bordro, 0) // []*Bordro türünde bir dilim oluştur
	for i := 1; i < len(rows); i++ {
		brd := &bot.LucaBordro{
			Sube:     rows[i][0],
			Bolum:    rows[i][1],
			TcNo:     rows[i][2],
			AdSoyad:  rows[i][3],
			Ucretler: make(map[string]decimal.Decimal),
		}

		for ndx, col := range rows[i] {
			if ndx > 3 {
				key := rows[0][ndx]
				brd.Ucretler[key], err = decimal.NewFromString(col)
				if err != nil {
					//todo: kullanıcıya hata logu ver
					//veya tekrar okuma denebilinir
					fmt.Println(err)
				}
			}
		}
		if i == len(rows)-1 {
			lastItem = true
		}
		err := b.BordroYaz(int(month), int(year), brd, lastItem)
		var str string
		if err != nil {
			insertMessage = append(insertMessage, err.Error())
			for _, v := range insertMessage {
				str += "Şube : " + brd.Sube + "Bölüm : " + brd.Bolum + v + ",       "
			}
			emitLog(str)

		} else {
			str += "işlem başarılı, "
			emitLog(str)

		}

	}

	return nil
}

func emitLog(logMessage string) {
	run.APP.Events.Emit(&application.WailsEvent{
		Name: "logProcess",
		Data: logMessage,
	})
}
