package jobs

/*
import (
	"encoding/json"
	"errors"
	"fmt"
	"gadmin/config"
	model2 "gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"gadmin/package/gmdata"
	"github.com/sirupsen/logrus"
	"gorm.io/gen"
	"leafstalk/grave/constants"
	"leafstalk/grave/model"
	"log"
	"os"
	"time"
)

var EquipmentStill = new(jEquipmentStill)

type jEquipmentStill struct{}

type Extract struct {
	NeedExtract    bool                // 是否需要返还
	Coin           int64               // 返还的金币
	StartEquipment model.DropEquipment // 1级的装备
	Material       model.DropMaterial  // 返还后的材料
}

var extractMap = make(map[int64]Extract)

func (j *jEquipmentStill) Run() {
	logrus.Info("jEquipmentStill Run.....")

	j.loadExtractMap()
	j.saveMaterial()
}

func (j *jEquipmentStill) loadExtractMap() {
	if err := gmdata.Load(os.Getenv("JSON_PATH") + "/" + os.Getenv("JSON_VERSION")); err != nil {
		logrus.Info("gmdata.Load err:", err)
		return
	}

	for _, equipment := range gmdata.EquipmentDict {

		// 一级装备  DecoMaterial多维数组 0是id 1是数量
		if equipment.Equiplev == 1 { //  && equipment.Star == 1
			extractMap[equipment.LevelId] = Extract{
				NeedExtract:    false,
				Coin:           equipment.DecoMaterial[0][1],
				StartEquipment: model.DropEquipment{EID: equipment.LevelId},
				Material:       model.DropMaterial{ID: equipment.DecoMaterial[1][0], Count: int(equipment.DecoMaterial[1][1])},
			}
			continue
		}

		startIndex := gmdata.GetEquipmentStartID(equipment.LevelId)
		start := extractMap[startIndex]

		extractMap[equipment.LevelId] = Extract{
			NeedExtract:    true,
			Coin:           equipment.DecoMaterial[0][1] - start.Coin,
			StartEquipment: start.StartEquipment,
			Material:       model.DropMaterial{ID: equipment.DecoMaterial[1][0], Count: int(equipment.DecoMaterial[1][1]) - start.Material.Count},
		}
		//logrus.Warningf("start:%+v, EID:%+v, extractMap[equipment.LevelId]:%+v \r\n", start, equipment.LevelId, extractMap[equipment.LevelId])
	}
	//logrus.Warningf("extractMap:%+v", extractMap)

}

func (j *jEquipmentStill) instBody() model.StillBodyParts {
	var body model.StillBodyParts
	for k, _ := range body {
		body[k].Part = int64(k + 1)
		body[k].Level = 1
	}
	return body
}

type DropEquipment struct {
	model.DropEquipment
	IsInlay bool
}

func (j *jEquipmentStill) saveMaterial() {
	// .Where(u.ID.Eq(1)) .Where(u.Playerid.Gt(17367)) .Where(u.Playerid.Eq(74998)) .Where(u.Playerid.Eq(653921))

	var (
		results  []*model2.PlayerMaterial
		a        = query.Use(config.GDB1).PlayerAttr
		u        = query.Use(config.GDB1).PlayerMaterial
		instBody = j.instBody()
	)
	err := u.Select(u.ID, u.Playerid, u.Coin, u.Equipments, u.Body).
		LeftJoin(a, a.Playerid.EqCol(u.Playerid)).
		Where(a.Level.Gte(2)).
		//Where(u.Playerid.Eq(577636)).
		Where(u.Body.Null()).
		FindInBatches(&results, 1000, func(tx gen.Dao, batch int) error {
			for _, result := range results {
				logrus.Infof("playerid :%+v", result.Playerid)
				var (
					oldEquipments  map[string]DropEquipment
					newBody        model.StillBodyParts
					oldBody        = instBody
					newEquipments  = make(map[string]model.DropEquipment)
					stillMaterials = make(map[int64]model.DropMaterial)
					addCoin        int64
					change         bool
				)

				if err := json.Unmarshal([]byte(result.Equipments), &oldEquipments); err != nil {
					logrus.Warningf("Unmarshal Equipments err:%+v", err)
					return err
				}

				if result.Body != "" {
					if err := json.Unmarshal([]byte(result.Body), &oldBody); err != nil {
						logrus.Warningf("Unmarshal oldBody err:%+v, result.Body:%+v", err, result.Body)
						return err
					}
				}

				handleEquipments, handleBody, bodyChange := j.bodyHandle(oldBody, oldEquipments)

				// 部位变动
				if !bodyChange {
					logrus.Warningf("无需更新跳过 oldEquipments:%+v", oldEquipments)
					continue
				}

				newBody = handleBody

				for _, oldEquipment := range handleEquipments {
					extract, ok := extractMap[oldEquipment.EID]
					if !ok {
						return errors.New(fmt.Sprintf("oldEquipment 获取映射失败:%+v", oldEquipment))
					}

					sChange, coin, newEquipment, newStillMaterials := j.stillHandle(extract, oldEquipment, stillMaterials)
					newEquipments[newEquipment.GID] = model.DropEquipment{
						GID: newEquipment.GID,
						EID: newEquipment.EID,
						//Wear: newEquipment.Wear,
					}
					if sChange {
						change = true
						addCoin += coin
						stillMaterials = newStillMaterials
					}

					//logrus.Warningf("oldEquipment:%+v, newStillMaterials:%+v", oldEquipment, newStillMaterials)

				}

				equip, err := json.Marshal(newEquipments)
				if err != nil {
					logrus.Warningf("json.Marshal newEquipments err :%+v", err)
					return err
				}

				body, err := json.Marshal(newBody)
				if err != nil {
					logrus.Warningf("json.Marshal body err:%+v", err)
					return err
				}

				//logrus.Warningf("equip:%+v \r\nbody:%+v", string(equip), string(body))

				if change {
					//logrus.Warningf("result.Playerid :%+v, \r\n newEquipments:%+v , \r\n newBody:%+v, \r\n stillMaterials:%+v, addCoin:%+v ", result.Playerid, newEquipments, newBody, stillMaterials, addCoin)

					data := model2.PlayerMaterial{
						Equipments: string(equip),
						Body:       string(body),
					}
					if _, err = query.Use(config.GDB1).PlayerMaterial.
						Where(u.Playerid.Eq(result.Playerid)).
						Updates(&data); err != nil {
						logrus.Warnf("PlayerMaterial Updates err . %v", err)
						return err
					}

					if addCoin > 0 || len(stillMaterials) > 0 {
						if err = j.addLetter(result.Playerid, addCoin, stillMaterials); err != nil {
							return err
						}
					}
				} else {
					// 没有装备被更新，则只更新部位
					data := model2.PlayerMaterial{
						Body: string(body),
					}
					if _, err = query.Use(config.GDB1).PlayerMaterial.
						Where(u.Playerid.Eq(result.Playerid)).
						Updates(&data); err != nil {
						logrus.Warnf("PlayerMaterial Updates2 err . %v", err)
						return err
					}
				}
			}
			return nil
		})

	if err != nil {
		panic(err)
	} else {
		log.Println("update finished")
	}
}

// addLetter 将返还材料添加到邮件
func (j *jEquipmentStill) addLetter(playerID int64, coin int64, materials map[int64]model.DropMaterial) error {
	var (
		data   model.ExtraData
		l      = query.Use(config.GDB1).PlayerLetter
		t      = time.Now()
		letter = model2.PlayerLetter{
			PlayerID:    playerID,
			Type:        13,
			CreateTime:  t,
			DisplayTime: t,
			ExpireTime:  t.Add(time.Second * 86400 * 30),
		}
	)

	for _, v := range materials {
		data.Materials = append(data.Materials, &model.DropMaterial{ID: v.ID, Count: v.Count})
	}

	if coin > 0 {
		data.Materials = append(data.Materials, &model.DropMaterial{ID: constants.MaterilaId_Coin, Count: int(coin)})
	}

	extra, err := json.Marshal(data)
	if err != nil {
		logrus.Warningf("addLetter json.Marshal extra err :%+v", err)
		return err
	}
	letter.Extra = string(extra)

	if err = l.Create(&letter); err != nil {
		logrus.Warningf("addLetter Create err :%+v", err)
		return err
	}

	return nil
}

// bodyHandle 处理部位继承强化等级
func (j *jEquipmentStill) bodyHandle(body model.StillBodyParts, equipments map[string]DropEquipment) (map[string]DropEquipment, model.StillBodyParts, bool) {
	var (
		newEquipments = make(map[string]DropEquipment)
		needChange    bool
	)
	for _, equipment := range equipments {
		equip := gmdata.GetEquipment(equipment.EID)
		selfChange := false
		for k, v := range body {
			if int64(v.Part) == equip.BodyId && equip.LevelId >= int64(v.Level) {
				// 存在镶嵌装备 则卸下
				if v.Equip != "" {
					original := equipments[v.Equip]
					original.IsInlay = false
					newEquipments[v.Equip] = original
				}

				body[k].Level = equip.LevelId
				body[k].Equip = equipment.GID

				equipment.IsInlay = true
				newEquipments[equipment.GID] = equipment
				//if equip.Level > 1 {
				//	needChange = true
				//}
				needChange = true
				selfChange = true
				continue
			}

		}

		if !selfChange {
			newEquipments[equipment.GID] = equipment
		}
	}

	return newEquipments, body, needChange
}

// stillHandle 处理返还材料
func (j *jEquipmentStill) stillHandle(extract Extract, oldEquipment DropEquipment, stillMaterials map[int64]model.DropMaterial) (bool, int64, DropEquipment, map[int64]model.DropMaterial) {
	var (
		change       bool
		addCoin      int64
		newEquipment DropEquipment
	)

	if extract.NeedExtract {
		// 需要返还
		newEquipment.GID = oldEquipment.GID
		newEquipment.Wear = false
		newEquipment.EID = extract.StartEquipment.EID

		if !oldEquipment.IsInlay {
			// 返还金币
			addCoin += extract.Coin

			// 返还材料
			_, ok := stillMaterials[extract.Material.ID]
			if ok {
				stillMaterials[extract.Material.ID] = model.DropMaterial{
					ID:    extract.Material.ID,
					Count: extract.Material.Count + stillMaterials[extract.Material.ID].Count,
				}
			} else {
				stillMaterials[extract.Material.ID] = model.DropMaterial{
					ID:    extract.Material.ID,
					Count: extract.Material.Count,
				}
			}

		}

		if oldEquipment.IsInlay {
			newEquipment.Wear = true
		}

		change = true
	} else {
		// 不需要返还 直接重新加入到装备列表
		newEquipment = oldEquipment
		// 没有镶嵌且是穿戴状态 则卸下
		if !oldEquipment.IsInlay && oldEquipment.Wear == true {
			newEquipment.Wear = false
			change = true
		}

		if oldEquipment.IsInlay {
			newEquipment.Wear = true
		}
	}

	return change, addCoin, newEquipment, stillMaterials
}
*/
