package bot

import (
	"bordrobot/lib/company"
	"bordrobot/lib/helper"
	"bordrobot/lib/ocr"
	"context"
	"errors"
	"fmt"
	"io/ioutil"
	"strconv"
	"strings"
	"time"

	"github.com/shopspring/decimal"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/launcher"
	"github.com/go-rod/rod/lib/proto"
)

var pageErrors []string
var scriptIndexArray []BordroPageScript

type Luca struct {
	Page    *rod.Page
	Browser *rod.Browser
}
type errorInfo struct {
	Error string
	Index int
}
type BordroPageScript struct {
	Index          string
	Value          string
	itemType       string
	DomSelectValue struct {
		Index    string
		Value    string
		itemType string
	}
}

func (l *Luca) ErrFunc(index bool) {
	if index {
		CloseBrowser(l.Browser)
	}
}
func (l *Luca) ClosingBrowserFromExternalLink() {
	CloseBrowser(l.Browser)
}
func VerifyCaptcha(page *rod.Page) error {
	//captcha := "#captcha"
	picturePreparation := []string{
		`document.getElementsByTagName("body")[0].style.backgroundImage = "none"`,
		`document.getElementsByClassName("baslik1")[0].style.display = "none"`,
		`document.getElementsByClassName("baslik2")[0].style.display = "none"`,
		`document.getElementsByClassName("baslik3")[0].getElementsByClassName("inp")[1].style.display = "none"`,
		`document.getElementsByClassName("baslik3")[0].getElementsByClassName("inp")[2].style.display = "none"`,
		`document.getElementsByClassName("baslik3")[0].getElementsByClassName("inp")[3].style.display = "none"`,
		`document.getElementsByClassName("baslik3")[0].getElementsByClassName("inp")[4].style.display = "none"`,
		`document.getElementsByClassName("baslik3")[0].getElementsByClassName("inp")[5].style.display = "none"`,
		`document.getElementsByClassName("captcha-container")[0].style.display ='none'`,
	}
	for i := 0; i < len(picturePreparation); i++ {
		wait := page.WaitRequestIdle(600*time.Millisecond, nil, nil, nil)
		wait()
		_, err := page.Evaluate(rod.Eval(`()=>{` + picturePreparation[i] + `}`))
		if err != nil {
			return err
		}
		fmt.Print(err)
	}
	datas, err := page.Screenshot(true, &proto.PageCaptureScreenshot{})
	if err != nil {
		panic(err)
	}

	err = helper.CreateFolder("./processFolder")
	err = ioutil.WriteFile("./processFolder/screenshot.png", datas, 0644)
	if err != nil {
		panic(err)
	}
	//captchaMessage, err := ReceiveDOMMessages(page, captcha, "src")
	picturePreparation = []string{
		`document.getElementsByTagName("body")[0].style.backgroundImage = ""`,
		`document.getElementsByClassName("baslik1")[0].style.display = ""`,
		`document.getElementsByClassName("baslik2")[0].style.display = ""`,
		`document.getElementsByClassName("baslik3")[0].getElementsByClassName("inp")[1].style.display = ""`,
		`document.getElementsByClassName("baslik3")[0].getElementsByClassName("inp")[2].style.display = ""`,
		`document.getElementsByClassName("baslik3")[0].getElementsByClassName("inp")[3].style.display = ""`,
		`document.getElementsByClassName("baslik3")[0].getElementsByClassName("inp")[4].style.display = ""`,
		`document.getElementsByClassName("baslik3")[0].getElementsByClassName("inp")[5].style.display = ""`,
	}
	for i := 0; i < len(picturePreparation); i++ {
		wait := page.WaitRequestIdle(600*time.Millisecond, nil, nil, nil)
		wait()
		_, err := page.Evaluate(rod.Eval(`()=>{` + picturePreparation[i] + `}`))
		if err != nil {
			return err
		}
		fmt.Print(err)
	}
	var captchaMsg string
	screenshot, err := page.Screenshot(true, &proto.PageCaptureScreenshot{})
	if err != nil {
		return errors.New("Captcha Sayfasında Hata Oluştu. İşlem Sonlanıyor.")
	}
	//captchaMsg, err = ocr.VisionApi("./processFolder/screenshot.png")
	captchaMsg, err = ocr.DecodeGeminiCaptcha(context.Background(), screenshot, "luca")
	if err != nil {
		return errors.New("Captcha Servisinde Hata Oluştu. İşlem Sonlanıyor.")
	}

	trimmedMsg := strings.ReplaceAll(captchaMsg, " ", "")
	trimmedMsg = strings.Replace(trimmedMsg, "\"", "", -1)
	page.MustElement("#captcha-input").MustInput(strings.ToLower(trimmedMsg))
	_, err = page.Evaluate(rod.Eval(`document.getElementById(document.forms[0].submit())`))
	if err != nil {
	}
	err = WaitLoad(page)
	if err != nil {
		return err
	}
	getUrl := page.MustInfo().URL
	splitUrl := strings.Split(getUrl, "/")
	uri := strings.Split(splitUrl[len(splitUrl)-1], ";")[0]
	if uri != "main.erp" {
		_, err = page.Evaluate(rod.Eval(`document.querySelector("body > div.swal2-container.swal2-fade.swal2-in > div > button.swal2-confirm.swal2-styled").click()`))
		//rod.Eval(`document.querySelector("body > div.swal2-container.swal2-fade.swal2-in > div > button.swal2-confirm.swal2-styled").click()`)

		VerifyCaptcha(page)
		fmt.Println("captcha tekrar deneme fonksiyonuna sok")
		//captcha tekrar denenecek
	}
	return nil

}
func NewLucaBot(devMode bool) *Luca {
	l := launcher.New().
		Headless(devMode).
		Devtools(true)

	//defer l.Cleanup()

	url := l.MustLaunch()
	browser := rod.New().
		ControlURL(url).
		Trace(true).
		//SlowMotion(1 * time.Second).
		MustConnect()
	page := browser.MustPage("https://agiris.luca.com.tr/LUCASSO/giris.erp")
	fmt.Println(page)

	return &Luca{Page: page, Browser: browser}
}

func (l *Luca) Login(company company.Company, month float64, year float64) error {
	page := l.Page
	err := WaitLoad(page)
	if err != nil {
		return err
	}
	err = FillInput(page, "#musteriNo", company.MemberNumber)
	if err != nil {
		return err
	}
	page.Timeout(500)
	err = FillInput(page, "#kullaniciAdi", company.Username)
	if err != nil {
		return err
	}
	page.Timeout(500)
	err = FillInput(page, "#parola", company.Password)
	if err != nil {
		return err
	}
	page.Timeout(500)

	result, err := page.Evaluate(rod.Eval(`()=>{girisbtn()}`))
	if err != nil {
		return err
	}
	page.Timeout(1000)
	loginDialog := "body > div.swal2-container.swal2-fade.swal2-in > div > div.swal2-content"

	loginDialogMessage, err := ReceiveDOMMessages(page, loginDialog, "innerText")
	if err != nil {
		errString := err.Error()
		if !strings.Contains(errString, "Sellector Bulunamadı") {
			return err
		}
	}
	if loginDialogMessage == "Müşteri No, Kullanıcı Adı veya Parola hatalıdır." {
		return errors.New("Şifre hatalı")

	}
	err = WaitLoad(page)
	if err != nil {
		return err
	}
	getUrl := page.MustInfo().URL
	splitUrl := strings.Split(getUrl, "/")
	splitUrlPage := strings.Split(splitUrl[len(splitUrl)-1], ";")[0]
	if splitUrlPage != "main.erp" {
		VerifyCaptcha(page)
	}
	fmt.Println(result)
	wait := page.WaitRequestIdle(1000*time.Millisecond, nil, nil, nil)
	wait()

	_, err = page.Evaluate(rod.Eval(`()=>{gonder('formTarget');}`))
	if err != nil {
		return err
	}

	Wait(page, 2000)

	allPages, err := page.Browser().Pages()
	if err != nil {
		return err
	}

	newPage, err := allPages.FindByURL("https://auygs.luca.com.tr/Luca/luca.do")
	err = WaitLoad(newPage)
	if err != nil {
		return err
	}
	frm4, err := newPage.Element("#frm4")
	if err != nil {
		return err
	}
	frame4, err := frm4.Frame()
	Wait(frame4, 1500)
	err = WaitLoad(newPage)
	if err != nil {
		return err
	}
	Wait(frame4, 1500)
	companiesSelectBoxWait, err := frame4.Element("#SirketCombo > option")
	if err != nil {
		return err
	}
	err = companiesSelectBoxWait.WaitLoad()
	if err != nil {
		return err
	}
	companiesSelectBox, err := frame4.Elements("#SirketCombo > option")
	if err != nil {
		return err
	}
	var vls string = ""
	for j := 0; j < len(companiesSelectBox); j++ {
		tex, err := companiesSelectBox[j].Text()
		value, err := companiesSelectBox[j].Property("value")
		if err != nil {
			return err
		}
		if err != nil {
			return err
		}
		if tex == company.Name {
			vls = value.String()
			break
		}
	}
	Wait(newPage, 500)
	element, err := frame4.Element("#SirketCombo")
	if err != nil {
		return err
	}
	selectInput := Select{Element: element, Selector: "#SirketCombo"}
	err = selectInput.SelectItem(vls)
	if err != nil {
		return err
	}
	err = WaitLoad(frame4)
	if err != nil {
		return err
	}
	Wait(frame4, 1500)
	companiesSelectYear, err := frame4.Elements("#DonemCombo > option")

	if err != nil {
		return err
	}
	for j := 0; j < len(companiesSelectYear); j++ {
		tex, err := companiesSelectYear[j].Text()
		value, err := companiesSelectYear[j].Property("value")
		if err != nil {
			return err
		}
		if err != nil {
			return err
		}
		if strings.Contains(tex, strconv.Itoa(int(year))) {
			vls = value.String()
			break
		}
	}
	Wait(newPage, 500)
	element, err = frame4.Element("#DonemCombo")
	if err != nil {
		return err
	}
	selectInput = Select{Element: element, Selector: "#DonemCombo"}
	err = selectInput.SelectItem(vls)
	if err != nil {
		return err
	}
	err = WaitLoad(frame4)
	if err != nil {
		return err
	}

	err = ClickItem(frame4, "#SirName > button.no-bold.green > i", 1)

	err = WaitLoad(frame4)
	if err != nil {
		return err
	}
	Wait(newPage, 500)

	return err
}

func (l *Luca) BordroTableMaping(frame *rod.Page, b *LucaBordro) ([]BordroPageScript, error) {
	scriptIndexArray = []BordroPageScript{}
	table, err := frame.Elements("#scroll > div > table > tbody > tr > td > table > tbody > tr > td") //table kontrol et var mı yok mu diye
	if err != nil {
		return nil, err
	}
	//table := frame.MustElements(".i2")
	var mainText string
	for t := 0; t < len(table); t++ {
		inputElement, err := table[t].Element("input")
		text, err := table[t].Text()
		fmt.Print(mainText)
		if text != "" {
			mainText = text
		}
		if inputElement != nil {
			if mainText != "" {
				fmt.Print(t)
				elem, err := table[t+1].Element("input")
				if elem == nil {
					mainText = ""
					fmt.Print("Hatalı Text")
					continue
				}
				id, err := elem.Attribute("id")

				fmt.Print(err)
				pageScript := BordroPageScript{
					Value:    text,
					Index:    *id,
					itemType: "input",
				}
				scriptIndexArray = append(scriptIndexArray, pageScript)
				mainText = ""
			}

		} else {
			if t <= len(table)-2 {
				if text != "" {
					if mainText == "N\nB" {
						aa, err := table[t].Element("select")
						id, err := aa.Attribute("id")
						dd := len(scriptIndexArray) - 2
						scriptIndexArray[dd].DomSelectValue.Index = *id
						scriptIndexArray[dd].DomSelectValue.Value = mainText
						scriptIndexArray[dd].DomSelectValue.itemType = "select"
						fmt.Print(aa, id, err)

					}
					inputBox, err := table[t+1].Element("input")
					selectBox, err := table[t+1].Element("select")
					fmt.Print(err)
					if inputBox != nil {
						types, err := inputBox.Attribute("type")
						if err != nil {
							return nil, err
						}
						if *types != "hidden" {
							id, err := inputBox.Attribute("id")
							pageScript := BordroPageScript{
								Value:    text,
								Index:    *id,
								itemType: "input",
							}
							scriptIndexArray = append(scriptIndexArray, pageScript)
							fmt.Print(inputBox, err, id, types)
						}

					} else if selectBox != nil {
						id, err := selectBox.Attribute("id")
						if err != nil {
							return nil, err
						}
						pageScript := BordroPageScript{
							Value:    text,
							Index:    *id,
							itemType: "selectBox",
						}
						scriptIndexArray = append(scriptIndexArray, pageScript)
					}
					mainText = ""

				}
			}

		}
		fmt.Print(err)
	}
	return scriptIndexArray, nil
}
func (l *Luca) PayrollPageLogin() error {
	newPage, err := l.GetPageByUrl("https://auygs.luca.com.tr/Luca/luca.do")
	if err != nil {
		return err
	}

	fs2, err := newPage.Element("#frm2")
	if err != nil {
		return err
	}
	frame, err := fs2.Frame()
	fs3, err := newPage.Element("#frm3")
	if err != nil {
		return err
	}
	frame3, err := fs3.Frame()
	err = newPage.WaitLoad()
	if err != nil {
		return err
	}
	err = frame.WaitLoad()
	if err != nil {
		return err
	}
	Wait(newPage, 500)
	err = ClickItem(frame, "#apy1000m0i1ITD", 1)
	if err != nil {
		return err
	}
	fmt.Println(err)
	err = ClickItem(frame3, "#apy1000m41i4ITX", 1)
	if err != nil {
		return err
	}
	err = newPage.WaitLoad()
	if err != nil {
		return err
	}
	Wait(newPage, 1500)
	err = WaitLoad(frame3)
	if err != nil {
		return err
	}
	return err
}

func (l *Luca) BordroYaz(month, year int, b *LucaBordro, lastItem bool) error {
	newPage, err := l.GetPageByUrl("https://auygs.luca.com.tr/Luca/luca.do")
	if err != nil {
		return err
	}
	frame3, err := l.GetFrame(newPage, "#frm3")
	if err != nil {
		return err
	}
	isyeriId := ""
	bolumId := ""
	err = WaitLoad(frame3)
	if err != nil {
		return err
	}
	Wait(frame3, 2000)
	err = WaitDomElement(frame3, "#isyeriId > option", 50)
	if err != nil {
		return errors.New("işyeri bulunurken hata ile karşılaşıldı")
	}
	bordroCompanySelectBox, err := frame3.Elements("#isyeriId > option")
	if err != nil {
		return err
	}
	for j := 0; j < len(bordroCompanySelectBox); j++ {
		text, err := bordroCompanySelectBox[j].Text()
		value, err := bordroCompanySelectBox[j].Property("value")
		if err != nil {
			return err
		}
		if strings.Trim(text, " ") == b.Sube { //.Sube.Value
			isyeriId = value.String()
			break
		}
	}
	if isyeriId == "" {
		return errors.New("Kayıtlı Şube Bulunamadı")
	}
	err = WaitLoad(frame3)
	if err != nil {
		return err
	}
	Wait(frame3, 1000)
	element, err := frame3.Element("#isyeriId")
	element.WaitLoad()
	if err != nil {
		return err
	}
	selectInput := Select{Element: element, Selector: "#isyeriId"}
	err = selectInput.SelectItem(isyeriId)
	if err != nil {
		return err
	}
	err = WaitLoad(frame3)
	if err != nil {
		return err
	}
	Wait(frame3, 2500)
	err = WaitDomElement(frame3, "#bolumId > option", 50)
	if err != nil {
		return errors.New("bölüm bulunurken hata ile karşılaşıldı")
	}
	bordroDepartmentSelectBox, err := frame3.Elements("#bolumId > option")
	if err != nil {
		return err
	}
	element, err = frame3.Element("#bolumId > option")
	if err != nil {
		return err
	}
	element.WaitLoad()
	err = WaitLoad(frame3)
	if err != nil {
		return err
	}
	for j := 0; j < len(bordroDepartmentSelectBox); j++ {
		text, err := bordroDepartmentSelectBox[j].Text()
		value, err := bordroDepartmentSelectBox[j].Property("value")
		if err != nil {
			return err
		}
		if strings.Trim(text, " ") == b.Bolum { //.Bolum.Value
			bolumId = value.String()
			break
		}
	}
	if bolumId == "" {
		return errors.New("Kayıtlı Bölüm Bulunamadı")
	}

	element, err = frame3.Element("#bolumId")
	if err != nil {
		return err
	}
	selectInput = Select{Element: element, Selector: "#bolumId"}
	err = selectInput.SelectItem(bolumId)
	if err != nil {
		return err
	}
	Wait(frame3, 1000)
	err = WaitLoad(frame3)
	if err != nil {
		return err
	}
	err = ClickItem(frame3, "#tr"+strconv.FormatFloat(float64(month), 'f', -1, 64)+" > td:nth-child(1)", 2) //aktarım ayı
	if err != nil {
		return err
	}
	err = WaitLoad(frame3)
	if err != nil {
		return err
	}
	Wait(frame3, 1500)
	var isEmpty bool = false
	//var targetID string
	err = WaitDomElement(frame3, "#scroll > table > tbody > tr > td[id^='tcKimlikNo']", 50)
	if err != nil {
		return errors.New("tablo okunurken hata ile karşılaşıldı")
	}

	elems, err := frame3.Elements("#scroll > table > tbody > tr > td[id^='tcKimlikNo']")
	if err != nil {
		return err
	}
	elemsProcess, err := frame3.Elements("#scroll > table > tbody > tr > td > a")
	if err != nil {
		return err
	}
	trs, err := frame3.Elements("#scroll > table > tbody > tr")
	if err != nil {
		return err
	}
	var foundIndex int = -1
	for j := 0; j < len(elems); j++ {
		tex, err := elems[j].Text()
		if err != nil {
			return err
		}
		process, err := elemsProcess[j].Text()
		if err != nil {
			return err
		}
		if tex == b.TcNo { //.TCKimlikNo.Value
			foundIndex = j
			if process == "Bordro Sil" {
				isEmpty = true
			}
			break
		}
	}
	if foundIndex == -1 {
		err = ClickItem(frame3, "body > form > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td:nth-child(1) > button:nth-child(3)", 1)
		if err != nil {
			return err
		}
		err = WaitLoad(frame3)
		if err != nil {
			return err
		}
		return errors.New("Böyle Bir Kullanıcı Bulunamadı")
	}
	if isEmpty == true {
		err = ClickItem(frame3, "body > form > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td:nth-child(1) > button:nth-child(3)", 1)
		if err != nil {
			return err
		}
		err = WaitLoad(frame3)
		if err != nil {
			return err
		}
		return errors.New("Yazılı Bordro Var Lütfen Siliniz")
	}
	if foundIndex != -1 && isEmpty == false {

		trs[foundIndex].Click(proto.InputMouseButtonLeft, 2)
	}
	Wait(newPage, 1500)
	err = WaitLoad(frame3)
	if err != nil {
		return err

	}
	rsp, err := l.BordroTableMaping(frame3, b)
	if err != nil {
		return errors.New("Bordro Tablosu Çekilemedi")
	}
	sgkDayFlag := false

	//rsp den dönden değerler ile matchlencek ve yazılcak
	firsts := make(map[string]decimal.Decimal)
	if value, ok := b.Ucretler["Normal Gün"]; ok {
		// Anahtarı ve değeri yeni map'e ekle
		firsts["Normal Gün"] = value
	}
	if value, ok := b.Ucretler["Hafta Tatili"]; ok {
		// Anahtarı ve değeri yeni map'e ekle
		firsts["Hafta Tatili"] = value
	}
	if value, ok := b.Ucretler["Genel Tatil"]; ok {
		// Anahtarı ve değeri yeni map'e ekle
		firsts["Genel Tatil"] = value
	}
	if value, ok := b.Ucretler["Ücretli İzin"]; ok {
		// Anahtarı ve değeri yeni map'e ekle
		firsts["Ücretli İzin"] = value
		if !value.IsZero() {
			sgkDayFlag = true
		}
	}
	if value, ok := b.Ucretler["Rapor"]; ok {
		// Anahtarı ve değeri yeni map'e ekle
		firsts["Rapor"] = value
		if !value.IsZero() {
			sgkDayFlag = true
		}
	}
	keys := []string{"Normal Gün", "Hafta Tatili", "Genel Tatil", "Ücretli İzin", "Rapor"}

	for _, v := range keys {
		fmt.Print(v)
		for i := 0; i < len(rsp); i++ {
			value, ok := firsts[v]
			if !ok {
				fmt.Printf("Key %s not found in map\n", v)
				break
			}
			if v == rsp[i].Value {
				el, err := frame3.Element("#" + rsp[i].Index)
				if err != nil {
					return err
				}
				if !value.Equal(value.Truncate(0)) {
					nevvl := strings.ReplaceAll(value.String(), ".", ",")
					strv := nevvl
					err = el.Input(strv)
					if err != nil {
						return err
					}
				} else {
					err = el.Input(value.String())
					if err != nil {
						return err
					}
				}

				el.Eval(`this.dispatchEvent(new KeyboardEvent('keydown', {'key': 'Enter'}))`)
				// valueStr := value.String()
				// // JS ile değeri ata, input tetikle, blur tetikle (Enter yerine geçer)
				// script := fmt.Sprintf(`this.value = "%s"; this.dispatchEvent(new Event("input", { bubbles: true })); this.blur();`, strings.ReplaceAll(valueStr, `"`, `\"`))

				// _, err = el.Eval(script)
				// if err != nil {
				// 	return err
				// }
				break
			}

		}

	}

	display, err := frame3.Element("#puantajGunTable")
	if err != nil {
		return errors.New("Puantaj Gün Tablosu Bulunamadı.")
	}
	dsp, err := display.Attribute("style")
	if err != nil {
		return err
	}

	// `display: none;` içerip içermediğini kontrol et
	if dsp != nil && !strings.Contains(*dsp, "display: none;") {
		if sgkDayFlag {
			ClickItem(frame3, "#ayGun2", 1)
		} else {
			ClickItem(frame3, "#ayGun1", 1)
		}
	}

	for k, v := range b.Ucretler {
		splitValue := strings.SplitN(k, " #", 2)
		k = strings.TrimSpace(splitValue[0])
		var elementInsertControl bool = true
		var displayControl bool = true
		tt := v.String()
		if tt == "0" {
			continue
		}
		if k == "Normal Gün" || k == "Hafta Tatili" || k == "Genel Tatil" || k == "Ücretli İzin" || k == "Rapor" {
			continue
		}
		Wait(frame3, 100)
		for i := 0; i < len(rsp); i++ {

			if k == rsp[i].Value {
				var hashValue string
				if len(splitValue) > 1 {
					hashValue = strings.TrimSpace(splitValue[1])
				}
				Wait(frame3, 200)
				if rsp[i].itemType == "selectBox" {
					elemBox, err := frame3.Element("#" + rsp[i].Index)
					if err != nil {
						return err
					}
					selectInput = Select{Element: elemBox, Selector: "#" + rsp[i].Index}
					err = selectInput.SelectItem(v.String())
					if err != nil {
						return err
					}
					elementInsertControl = false
					break
				}
				el, err := frame3.Element("#" + rsp[i].Index)
				if err != nil {
					return err
				}

				// //s ve g olunca i yi çalıştır n ve b olunca i+1 i
				if (hashValue == "S" || hashValue == "G") && k != "ARGE-Destek ve Tasarım Faaliyeti" {
					if rsp[i+1].Value != hashValue {
						newBordroPage, err := frame3.Element("body > form > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td:nth-child(1) > button:nth-child(4)")
						newBordroPage.WaitLoad()
						if err != nil {
							return err
						}
						newBordroPage.Click(proto.InputMouseButtonLeft, 1)
						err = WaitLoad(frame3)
						if err != nil {
							return err
						}
						err = ClickItem(frame3, "body > form > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td:nth-child(1) > button:nth-child(3)", 1)
						if err != nil {
							return err
						}
						return errors.New(k + hashValue + "Sütun Bulunamadı")
					}
					el, err = frame3.Element("#" + rsp[i].Index)
					if err != nil {
						return err
					}
				}
				if hashValue == "B" || hashValue == "N" {
					if strings.Contains(rsp[i].Index, "Carpan") {
						b := BordroPageSelectBoxType{
							B: "1", // Buraya gerçek değeri koyun
							N: "0", // Buraya gerçek değeri koyun
						}
						var dynamicValue string
						if hashValue == "B" {
							dynamicValue = b.B
						} else {
							dynamicValue = b.N
						}
						elemBox, err := frame3.Element("#" + rsp[i].DomSelectValue.Index)
						if err != nil {
							return err
						}
						selectInput = Select{Element: elemBox, Selector: "#" + rsp[i].DomSelectValue.Index}
						err = selectInput.SelectItem(dynamicValue)
						if err != nil {
							return err
						}
						el, err = frame3.Element("#" + rsp[i+1].Index)
						if err != nil {
							return err
						}
					}
				}
				if k == "ARGE-Destek ve Tasarım Faaliyeti" {
					if hashValue == "S" {
						el, err = frame3.Element("#" + rsp[i+1].Index)
						if err != nil {
							return err
						}
					}
				}
				value := v.String()
				if strings.Contains(value, ".") {
					value = strings.Replace(value, ".", ",", -1)
				}
				elemF := el
				if strings.Contains(rsp[i].Index, rsp[i].Index) {
					for {
						parentElement, err := elemF.Parent()
						if err != nil {
							fmt.Println("Error:", err)

						}
						innerHTML, err := parentElement.HTML()
						if err != nil {
							fmt.Println("Error:", err)

						}

						// innerHTML'deki etiket adını al
						tagName1 := strings.Split(innerHTML, ">")[0]
						tagName := strings.TrimPrefix(tagName1, "<")
						fmt.Println("Tag name:", tagName)
						fmt.Print(tagName)
						if strings.Contains(tagName, "table") {
							if strings.Contains(tagName1, " display: none;") {
								displayControl = false
							}
							break
						}
						elemF = parentElement
					}

				}
				if displayControl {
					err = el.Input(value)
				}
				elementInsertControl = false
				break
			}
		}
		if elementInsertControl {
			if tt != "0" {
				newBordroPage, err := frame3.Element("body > form > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td:nth-child(1) > button:nth-child(4)")
				newBordroPage.WaitLoad()
				if err != nil {
					return err
				}
				newBordroPage.Click(proto.InputMouseButtonLeft, 1)
				err = WaitLoad(frame3)
				if err != nil {
					return err
				}
				err = ClickItem(frame3, "body > form > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td:nth-child(1) > button:nth-child(3)", 1)
				if err != nil {
					return err
				}
				return errors.New(k + "    Sütunu Bulunamadı Taslak Hatası,    ")
			}
		}
	}
	err = ClickItem(frame3, "body > form > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td.right > button", 1)
	if err != nil {
		return err
	}
	saveButtonMessage, _ := ReceiveDOMMessages(frame3, ".alert-container", "innerText")
	// if err != nil {
	// 	return err
	// }
	if saveButtonMessage != "Bordro hesaplanıyor." {
		newBordroPage, err := frame3.Element("body > form > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td:nth-child(1) > button:nth-child(4)")
		newBordroPage.WaitLoad()
		if err != nil {
			return err
		}
		newBordroPage.Click(proto.InputMouseButtonLeft, 1)
		err = WaitLoad(frame3)
		if err != nil {
			return err

		}
		err = ClickItem(frame3, "body > form > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td:nth-child(1) > button:nth-child(3)", 1)

		if err != nil {
			return err

		}
		return errors.New(saveButtonMessage)
	}

	err = WaitLoad(frame3)
	if err != nil {
		return err
	}
	newBordroPage, err := frame3.Element("body > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td:nth-child(1) > button:nth-child(4)")
	newBordroPage.WaitLoad()
	if err != nil {
		return err
	}
	newBordroPage.Click(proto.InputMouseButtonLeft, 1)
	err = WaitLoad(frame3)
	if err != nil {
		return err

	}
	err = ClickItem(frame3, "body > form > table > tbody > tr.altBar.alt-button-bar > th > table > tbody > tr > td:nth-child(1) > button:nth-child(3)", 1)

	if err != nil {
		return err
	}
	return err
}
