package service

import (
	"errors"
	"fmt"

	"github.com/bytedance/sonic"
	"github.com/go-admin-team/go-admin-core/logger"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"github.com/jinzhu/copier"
	"gorm.io/gorm"

	"go-admin/app/admin/models"
	"go-admin/app/admin/service/dto"
	"go-admin/common/const/rediskey"
	cDto "go-admin/common/dto"
	"go-admin/common/helper"
)

type SysDictData struct {
	service.Service
}

// GetPage 获取列表
func (e *SysDictData) GetPage(c *dto.SysDictDataGetPageReq, list *[]models.SysDictData, count *int64) error {
	var err error
	var data models.SysDictData

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	return nil
}

// Get 获取对象
func (e *SysDictData) Get(d *dto.SysDictDataGetReq, model *dto.SysDictDataResp) error {
	var err error
	var data models.SysDictData

	db := e.Orm.Model(&data).
		First(&data, d.GetId())
	err = db.Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("db error: %s", err)
		return err
	}
	if err = db.Error; err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}

	copier.Copy(model, data)

	if data.Language != "" {
		sonic.Unmarshal([]byte(data.Language), &model.LanguageData)
	}

	if model.LanguageData == nil {
		model.LanguageData = []dto.SysDictDataLanguageData{}
	}

	return nil
}

// Insert 创建对象
func (e *SysDictData) Insert(c *dto.SysDictDataInsertReq) error {
	var err error
	var data = new(models.SysDictData)
	c.Generate(data)
	err = e.Orm.Create(data).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	key := fmt.Sprintf(rediskey.SysDictDataKey, data.DictType, data.DictValue)
	val, _ := sonic.MarshalString(&data)

	if val != "" {
		if err := helper.DefaultRedis.SetString(key, val); err != nil {
			logger.Error("保存缓存失败")
		}
	}

	return nil
}

// Update 修改对象
func (e *SysDictData) Update(c *dto.SysDictDataUpdateReq) error {
	var err error
	var model = models.SysDictData{}
	e.Orm.First(&model, c.GetId())
	c.Generate(&model)
	db := e.Orm.Save(model)
	if err = db.Error; err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}

	key := fmt.Sprintf(rediskey.SysDictDataKey, model.DictType, model.DictValue)
	val, _ := sonic.MarshalString(&model)

	if val != "" {
		if err := helper.DefaultRedis.SetString(key, val); err != nil {
			logger.Error("保存缓存失败")
		}
	}
	return nil
}

// Remove 删除
func (e *SysDictData) Remove(c *dto.SysDictDataDeleteReq) error {
	var err error
	var data models.SysDictData
	dicts := make([]models.SysDictData, 0)
	keys := []string{}

	e.Orm.Model(&data).Where("id IN ?", c.GetId()).Select("dict_type,dict_value").Find(&dicts)

	db := e.Orm.Delete(&data, c.GetId())
	if err = db.Error; err != nil {
		e.Log.Errorf("Delete error: %s", err)
		return err
	}
	if db.RowsAffected == 0 {
		err = errors.New("无权删除该数据")
		return err
	}

	for _, item := range dicts {
		key := fmt.Sprintf(rediskey.SysDictDataKey, item.DictType, item.DictValue)
		keys = append(keys, key)
	}

	if len(keys) > 0 {
		if _, err := helper.DefaultRedis.BatchDeleteKeys(keys); err != nil {
			logger.Error("删除缓存失败")
		}
	}

	return nil
}

// GetAll 获取所有
func (e *SysDictData) GetAll(c *dto.SysDictDataGetPageReq, list *[]models.SysDictData) error {
	var err error
	var data models.SysDictData

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
		).
		Find(list).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	return nil
}

func (e *SysDictData) GetByKey(dictTypeCode, dictDataCode string) (models.SysDictData, error) {
	key := fmt.Sprintf(rediskey.SysDictDataKey, dictTypeCode, dictDataCode)
	data, _ := helper.GetObjString[models.SysDictData](helper.DefaultRedis, key)

	if data.DictCode == 0 {
		if err := e.Orm.Model(&data).Where("dict_type =? AND dict_value= ?", dictTypeCode, dictDataCode).First(&data).Error; err != nil {
			return data, err
		}
		val, _ := sonic.MarshalString(data)

		if val != "" {
			helper.DefaultRedis.SetString(key, val)
		}
	}

	return data, nil
}

// 根据字典类型 获取字典数据
func (e *SysDictData) GetByType(dictTypeCode string) (map[string]dto.SysDictDataResp, error) {
	var data []models.SysDictData
	result := map[string]dto.SysDictDataResp{}
	if err := e.Orm.Model(&models.SysDictData{}).Where("dict_type = ?", dictTypeCode).Find(&data).Error; err != nil {
		return result, err
	}

	for _, v := range data {
		item := dto.SysDictDataResp{}
		copier.Copy(&item, v)

		if v.Language != "" {
			languageData := []dto.SysDictDataLanguageData{}
			sonic.Unmarshal([]byte(v.Language), &languageData)
			item.LanguageData = languageData
		}

		result[v.DictValue] = item
	}

	return result, nil
}

func (e *SysDictData) GetLanguageByDatas(datas *map[string]dto.SysDictDataResp, dictValue, language string) (string, error) {
	result := ""

	if item, ok := (*datas)[dictValue]; ok {
		result = item.DictLabel

		for _, v := range item.LanguageData {
			if v.Key == language {
				result = v.Value
				break
			}
		}
	}

	return result, nil
}
