package gmdata

import (
	"encoding/json"
	"errors"
	"fmt"
	"gadmin/utility"
	"io"
	"os"
	"sync"

	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
)

// 从json中读取配置
type GoodsItem struct {
	Id    int `json:"goods_id"`
	Cd    int `json:"cd"`
	Price int `json:"price"`
}

type ShopItem struct {
	GoodId int    `json:"good_id"`
	Price  string `json:"price"`
}

type Equipment struct {
	BodyId       int64     `json:"bodyId"` //穿戴部位
	Id           int64     `json:"id"`
	LevelId      int64     `json:"level_id"`
	Name         string    `json:"name"`
	Star         int       `json:"star"`
	DecoMaterial [][]int64 `json:"deco_material"` //分解后获得
	Equiplev     int       `json:"equiplev"`
}

type Material struct {
	ID   int    `json:"Uid"`
	Type int    `json:"Type"`
	Name string `json:"Name"`
}

// 符文
type Rune struct {
	ID   int    `json:"Uid"`
	Type int    `json:"Type"`
	Name string `json:"Name"`
}

// 天赋
type Talent struct {
	ID        int64  `json:"talent_id"`
	Name      string `json:"talent_name"`
	MaxLevel  int64  `json:"max_level"`
	BaseValue string `json:"base_value"`
}

type Role struct {
	Id               int64  `json:"Role_id"`
	Name             string `json:"Role_name"`
	Type             int64  `json:"Role_type"`
	Level            int64  `json:"Role_level"`
	Evolution        int    `json:"Role_evolution"`
	SkillUnlockLevel []int  `json:"skill_unlock_level"`
	Skill            []int  `json:"Role_skill"`
}

type Level struct {
	Level int64 `json:"level"`
	Exp   int64 `json:"exp"`
}

type Antique struct {
	ID   int    `json:"antiques_id"`
	Type int    `json:"antiques_type"`
	Name string `json:"antiques_name"`
}

type Good struct {
	Value int32  `json:"value"`
	Label string `json:"label"`
}

// 商品价格与类型
type Cost struct {
	Id    int64 `json:"id"`
	Count int64 `json:"count"`
}
type ShopGoods struct {
	Id        int64  `json:"ID"`
	Name      string `json:"Name"`
	Cost      []Cost `json:"Cost"`
	GoodsType int    `json:"GoodsType"`
}

type Server struct {
	ServerId        int    `json:"serverId"`
	Page            int    `json:"page"`
	ServerName      string `json:"serverName"`
	MaxPlayerNumber int    `json:"maxPlayerNumber"`
}

type Exskill struct {
	SkillID     int       `json:"skill_id,omitempty"`
	SkillGroup  int       `json:"skill_group,omitempty"`
	SkillType   int       `json:"skill_type,omitempty"`
	SkillName   string    `json:"skill_name,omitempty"`
	SkillLevel  int       `json:"skill_level,omitempty"`
	SkillUnlock int       `json:"skill_unlock,omitempty"`
	SkillIcon   string    `json:"skill_icon,omitempty"`
	IsAll       int       `json:"isall,omitempty"`
	SkillDes    string    `json:"skill_des,omitempty"`
	SkillValue  []float64 `json:"skill_value,omitempty"`
	CombatEffe  int       `json:"combat_effe,omitempty"`
}

// json配置列表
var (
	GoodsInfo     []GoodsItem // 商品信息
	Talents       []Talent    // 天赋信息
	EquipmentDict = make([]Equipment, 0)
	MaterialsDict = make([]Material, 0)
	RunesDict     = make([]Rune, 0)
	AntiQueDict   = make([]Antique, 0) // 古玩信息
	Goods         = make([]Good, 0)
	AllShopGoods  = make(map[string]ShopGoods)
	Servers       = make([]Server, 0)
	Roles         []Role  // 不同角色分一组
	PlayLevel     []Level //
	Exskills      []Exskill
	CurrentPath   string
	lock          sync.Mutex
)

// GetEquipmentStartID 获取指定装备的起始ID，1级ID
func GetEquipmentStartID(id int64) int64 {
	return id/1000*1000 + 1
}

// 完整天赋
func GetFullTalent() map[int]int {
	data := make(map[int]int)
	for _, talent := range Talents {
		data[int(talent.ID)] = int(talent.MaxLevel)
	}
	return data
}

// 天赋清空
func GetEmptyTalent() map[int]int {
	data := make(map[int]int)
	for _, talent := range Talents {
		data[int(talent.ID)] = 0
	}
	return data
}

func GetGoodLabel(value int32) string {
	for _, v := range Goods {
		if v.Value == value {
			return v.Label + "(" + cast.ToString(value) + ")"
		}
	}
	return `未关联商品信息` + "(" + cast.ToString(value) + ")"
}

func GetShopGoods() map[int64]ShopGoods {
	data := make(map[int64]ShopGoods)
	for _, v := range AllShopGoods {
		data[v.Id] = v
	}
	return data
}

func LoadGraveJson(confPath string) (err error) {
	lock.Lock()
	defer lock.Unlock()

	logrus.Infof("当前加载的json配置路径为：%v", confPath)

	/*err = LoadItemData(confPath, "Role.json", &Roles)
	if err != nil {
		return
	}
	err = LoadItemData(confPath, "playerLevel.json", &PlayLevel)
	if err != nil {
		return
	}*/
	err = LoadItemData(confPath, "item.json", &MaterialsDict)
	if err != nil {
		return
	}
	err = LoadItemData(confPath, "rune.json", &RunesDict)
	if err != nil {
		return
	}
	return
	LoadItemData(confPath, "antique.json", &AntiQueDict)

	err = LoadItemData(confPath, "talent.json", &Talents) //天赋
	if err != nil {
		return
	}
	for _, v := range []string{"weapons.json"} { //"wear.json",
		var equi []Equipment
		LoadItemData(confPath, v, &equi)
		EquipmentDict = append(EquipmentDict, equi...)
	}

	err = LoadItemData(confPath, "goods.json", &Goods)
	if err != nil {
		return
	}

	err = LoadItemData(confPath, "product.json", &AllShopGoods)
	if err != nil {
		return
	}

	CurrentPath = confPath

	loadNoviceTask(confPath)

	LoadLimitGift(confPath)

	LoadTreasure(confPath) //宝物

	LoadServer(confPath)

	LoadKingSeason(confPath)

	LoadChapter() //关卡
	return
}

func LoadItemData(confPath, file string, value interface{}) (err error) {
	if file == "" {
		panic("file cannot be blank")
	}
	fileObj, err := os.Open(fmt.Sprintf("%s/%s", confPath, file))
	if err != nil {
		panic(err)
	}
	fileData, err := io.ReadAll(fileObj)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(fileData, value)
	if err != nil {
		panic(err)
	}
	return
}

func SetConfPath(confPath string) (err error) {
	ok, err := utility.PathExists(confPath)
	if err != nil {
		return
	}
	if !ok {
		return errors.New("路径未找到")
	}
	err = LoadGraveJson(confPath)
	if err != nil {
		return
	}
	os.WriteFile("json_path.txt", []byte(confPath), 0600)
	CurrentPath = confPath
	return
}

func loadJsonFile(filePath string, val interface{}) {
	ptrFile, err := os.Open(filePath)
	if err != nil {
		logrus.Fatalln("读取json文件失败", err)
	}
	defer ptrFile.Close()

	decoder := json.NewDecoder(ptrFile)
	if err = decoder.Decode(&val); err != nil {
		logrus.Fatalln("loadJsonFile Decoder failed ", filePath, err.Error())
	}
}

func LoadCurrentFromDisk() {
	data, err := os.ReadFile("json_path.txt")
	if err != nil {
		return
	}
	CurrentPath = string(data)
	LoadGraveJson(CurrentPath)
}

func IsMaterial(id int) bool {
	for _, v := range MaterialsDict {
		if v.ID == id {
			return true
		}
	}

	return false
}

func IsEquipment(id int64) bool {
	for _, v := range EquipmentDict {
		if v.LevelId == id {
			return true
		}
	}

	return false
}

func GetEquipment(id int64) Equipment {
	for _, v := range EquipmentDict {
		if v.LevelId == id {
			return v
		}
	}

	var v2 Equipment
	return v2
}

func GetRoleNameByType(typ int64) string {
	for _, v := range Roles {
		if v.Type == typ {
			return v.Name
		}
	}
	return ""
}
