package common

import (
	"fmt"
	"go_dreamfactory/utils"
	"io/ioutil"
	"sort"
	"strings"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
	"github.com/sirupsen/logrus"
)

type ItemList struct {
	SelItemIds []string //选择的ID 多选
	SelItemId  string   //选择的ID 单选
	ItemTotal  int      //总数
	TitleLabel *widget.Label
	CachedList List
	ItemList   *widget.List
	SearchItem []Item //用于暂存搜索结果
}

func NewItemList() *ItemList {
	return &ItemList{
		TitleLabel: &widget.Label{},
		CachedList: NewList(""),
	}
}

// 重置
func (f *ItemList) Reset() {
	f.ItemTotal = 0
	f.SelItemIds = []string{}
	f.SelItemId = ""
	f.CachedList = NewList("")
	f.ItemList.Refresh()
}

func (f *ItemList) CreateList() *widget.List {
	f.ItemList = widget.NewList(
		func() int {
			return len(f.CachedList.Items)
		},
		func() fyne.CanvasObject {
			return widget.NewLabel("Template")
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
			c, _ := item.(*widget.Label)
			c.Text = f.CachedList.Items[id].Text
			c.Refresh()
		},
	)
	f.ItemList.OnSelected = func(id widget.ListItemID) {
		selId := f.CachedList.Items[id].Id
		f.SelItemId = selId
		return
	}

	// f.ItemList.OnUnselected = func(id widget.ListItemID) {
	// 	selId := f.CachedList.Items[id].Id
	// 	utils.DeleteString(f.SelItemIds, selId)
	// }
	return f.ItemList
}

// 创建默认的列表
func (f *ItemList) CreateDefaultCheckList() *widget.List {
	f.ItemList = widget.NewList(
		func() int {
			return len(f.CachedList.Items)
		},
		func() fyne.CanvasObject {
			return widget.NewCheck("Template", func(bool) {})
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
			c, _ := item.(*widget.Check)
			_id := f.CachedList.Items[id].Id
			c.Text = f.CachedList.Items[id].Text
			c.Checked = f.CachedList.Items[id].Checked

			c.OnChanged = func(b bool) {
				if b {
					f.SelItemIds = append(f.SelItemIds, _id)
				} else {
					f.SelItemIds = utils.DeleteString(f.SelItemIds, _id)
				}
				f.TitleLabel.SetText(fmt.Sprintf("(%d/%d)", len(f.SelItemIds), f.ItemTotal))
				f.CachedList.Items[id].Checked = b
				// sort.Sort(f.cachedList)
				f.ItemList.Refresh()
			}
			c.Refresh()
		},
	)
	return f.ItemList
}

// 创建下载列表
func (f *ItemList) CreateDownloadList() *widget.List {
	f.ItemList = widget.NewList(
		func() int {
			return len(f.CachedList.Items)
		},
		func() fyne.CanvasObject {
			chk := widget.NewCheck("Template", func(bool) {})
			lb := widget.NewLabel("Template")
			items := container.NewHBox(chk, &layout.Spacer{}, lb)
			return items
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
			c, _ := item.(*fyne.Container)
			chk := c.Objects[0].(*widget.Check)
			data := f.CachedList.Items[id]
			chk.Text = data.Text
			chk.Checked = data.Checked
			chk.OnChanged = func(b bool) {
				if b {
					f.SelItemIds = append(f.SelItemIds, chk.Text)
				} else {
					f.SelItemIds = utils.DeleteString(f.SelItemIds, chk.Text)
				}
				f.CachedList.Items[id].Checked = b
				// sort.Sort(f.cachedList)
				f.ItemList.Refresh()
			}

			lb := c.Objects[2].(*widget.Label)
			lb.Text = ConvertFileSize(data.Size)
			c.Refresh()
		},
	)
	return f.ItemList
}

func (f *ItemList) AddItem(item Item) {
	f.CachedList.Items = append(f.CachedList.Items, item)
	// sort.Sort(f.cachedList)
	f.ItemList.Refresh()
}

func (f *ItemList) AddItemWithText(val string) {
	val = strings.TrimSpace(val)
	if len(val) == 0 {
		return
	}
	newItem := Item{
		Id:       val,
		Text:     val,
		Quantity: 1,
		Checked:  false, //默认不选中
	}
	f.CachedList.Items = append(f.CachedList.Items, newItem)
	sort.Sort(f.CachedList)
	f.ItemList.Refresh()
}

func (f *ItemList) LoadItem(dirPath string) {
	f.Reset()
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		logrus.Error(err)
		return
	}

	for _, file := range files {
		if !file.IsDir() {
			f.AddItemWithText(file.Name())
			// f.selItemIds = append(f.selItemIds, file.Name())
			f.ItemTotal++
			// logrus.Debugf("%v", file.Name())
		}
	}

	f.SearchItem = f.CachedList.Items
}

// 改变列表项目
func (f *ItemList) ChangeItem(tmpDir, projectDir string) {
	f.ItemTotal = 0
	f.SelItemIds = []string{}
	f.CachedList = NewList("")
	tmpFiles, err := ioutil.ReadDir(tmpDir)
	if err != nil {
		logrus.Error(err)
		return
	}

	defer func() {
		if len(tmpFiles) == 0 || len(f.CachedList.Items) == 0 {
			ShowTip("没有任何变更的项目")
		}
	}()

	projectFiles, err := ioutil.ReadDir(projectDir)
	if err != nil {
		logrus.Error(err)
		return
	}

	pfMap := make(map[string]int64)
	for _, v := range projectFiles {
		if !v.IsDir() {
			pfMap[v.Name()] = v.ModTime().Unix()
		}
	}

	for _, file := range tmpFiles {
		if !file.IsDir() {
			if pfTime, ok := pfMap[file.Name()]; ok {
				if file.ModTime().Unix() <= pfTime {
					continue
				}
			}
			f.AddItemWithText(file.Name())
			// f.SelItemIds = append(f.SelItemIds, file.Name())
			f.ItemTotal++
			// logrus.Debugf("%v", file.Name())
		}
	}
}

// 刷新文件数
func (f *ItemList) ChangeFileCount() {
	f.TitleLabel.SetText(fmt.Sprintf("(%d/%d)", len(f.SelItemIds), f.ItemTotal))
}

func (f *ItemList) DeleteItem(name string) {
	for i, v := range f.CachedList.Items {
		if v.Text == name {
			f.SelItemIds = utils.DeleteString(f.SelItemIds, v.Text)
			f.CachedList.Items = append(f.CachedList.Items[:i], f.CachedList.Items[i+1:]...)
			if f.ItemTotal > 0 {
				f.ItemTotal--
			}
		}
	}
}
