package service

import (
	"fmt"
	"strconv"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/utils/file"
	"be.ems/src/modules/ne_data/model"
	"be.ems/src/modules/ne_data/repository"
)

// 实例化数据层 NBState 结构体
var NewNBState = &NBState{
	nbStateRepository: repository.NewNBState,
}

// NBState 基站状态记录表 服务层处理
type NBState struct {
	nbStateRepository *repository.NBState // 基站状态记录信息
}

// FindByPage 根据条件分页查询
func (r NBState) FindByPage(query model.NBStateQuery) ([]model.NBState, int64) {
	return r.nbStateRepository.SelectByPage(query)
}

// Insert 插入数据
func (r NBState) Insert(item model.NBState) int64 {
	return r.nbStateRepository.Insert(item)
}

// DeleteByIds 批量删除信息
func (r NBState) DeleteByIds(ids []string) (int64, error) {
	// 检查是否存在
	arr := r.nbStateRepository.SelectByIds(ids)
	if len(arr) <= 0 {
		return 0, fmt.Errorf("not data")
	}

	if len(arr) == len(ids) {
		rows := r.nbStateRepository.DeleteByIds(ids)
		return rows, nil
	}
	// 删除信息失败！
	return 0, fmt.Errorf("delete fail")
}

// ExportXlsx 导出数据到 xlsx 文件
func (r NBState) ExportXlsx(rows []model.NBState, fileName, language string) (string, error) {
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": i18n.TKey(language, "nbState.export.id"),
		"B1": i18n.TKey(language, "nbState.export.name"),
		"C1": i18n.TKey(language, "nbState.export.position"),
		"D1": i18n.TKey(language, "nbState.export.address"),
		"E1": i18n.TKey(language, "nbState.export.nbName"),
		"F1": i18n.TKey(language, "nbState.export.state"),
		"G1": i18n.TKey(language, "nbState.export.time"),
	}

	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		// 角色状态
		statusValue := i18n.TKey(language, "dictData.offline")
		if row.State == "ON" {
			statusValue = i18n.TKey(language, "dictData.online")
		}
		dataCells = append(dataCells, map[string]any{
			"A" + idx: row.ID,
			"B" + idx: row.Name,
			"C" + idx: row.Position,
			"D" + idx: row.Address,
			"E" + idx: row.NbName,
			"F" + idx: statusValue,
			"G" + idx: row.Time,
		})
	}

	// 导出数据表格
	return file.WriteSheet(headerCells, dataCells, fileName, "Sheet1")
}
