package repository

import (
	"fmt"
	"strings"
	"time"

	"be.ems/src/framework/database/db"
	"be.ems/src/framework/logger"
	"be.ems/src/modules/trace/model"
)

// 实例化数据层 TraceTask 结构体
var NewTraceTask = &TraceTask{}

// TraceTask 跟踪_任务 数据层处理
type TraceTask struct{}

// SelectByPage 分页查询集合
func (r TraceTask) SelectByPage(query map[string]string) ([]model.TraceTask, int64) {
	tx := db.DB("").Model(&model.TraceTask{})
	// 查询条件拼接
	if v, ok := query["traceType"]; ok && v != "" {
		tx = tx.Where("trace_type = ?", v)
	}
	if v, ok := query["imsi"]; ok && v != "" {
		tx = tx.Where("imsi like ?", fmt.Sprintf("%s%%", v))
	}
	if v, ok := query["msisdn"]; ok && v != "" {
		tx = tx.Where("msisdn like ?", fmt.Sprintf("%s%%", v))
	}
	if v, ok := query["title"]; ok && v != "" {
		tx = tx.Where("title like ?", fmt.Sprintf("%s%%", v))
	}
	if v, ok := query["neType"]; ok && v != "" {
		tx = tx.Where("ne_list like ?", fmt.Sprintf("%%%s%%", strings.ToUpper(v)))
	}
	if v, ok := query["startTime"]; ok && v != "" {
		if len(v) == 10 {
			v = fmt.Sprintf("%s000", v)
			tx = tx.Where("start_time >= ?", v)
		} else if len(v) == 13 {
			tx = tx.Where("start_time >= ?", v)
		}
	}
	if v, ok := query["endTime"]; ok && v != "" {
		if len(v) == 10 {
			v = fmt.Sprintf("%s999", v)
			tx = tx.Where("end_time <= ?", v)
		} else if len(v) == 13 {
			tx = tx.Where("end_time <= ?", v)
		}
	}

	// 查询结果
	var total int64 = 0
	rows := []model.TraceTask{}

	// 查询数量为0直接返回
	if err := tx.Count(&total).Error; err != nil || total <= 0 {
		return rows, total
	}

	// 查询数据分页
	pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
	tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
	// 排序
	sortByStr, sortOk := query["sortBy"]
	sortOrderStr, orderOk := query["sortOrder"]
	if sortOk && sortByStr != "" && orderOk && sortOrderStr != "" {
		sortByArr := strings.Split(sortByStr, ",")
		sortOrderArr := strings.Split(sortOrderStr, ",")
		for i := range sortByArr {
			sortBy := sortByArr[i]
			sortOrder := sortOrderArr[i]
			// 排序字段
			sort := "id"
			if sortBy == "operaBy" {
				sort = "opera_by"
			} else if sortBy == "endTime" {
				sort = "end_time"
			}
			// 排序方式
			order := "ASC"
			if strings.HasPrefix(sortOrder, "asc") {
				order = "ASC"
			} else if strings.HasPrefix(sortOrder, "desc") {
				order = "DESC"
			}
			tx = tx.Order(fmt.Sprintf("%s %s", sort, order))
		}
	} else {
		tx = tx.Order("id desc")
	}

	if err := tx.Find(&rows).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows, total
	}
	return rows, total
}

// SelectByIds 通过ID查询信息
func (r TraceTask) SelectByIds(ids []int64) []model.TraceTask {
	rows := []model.TraceTask{}
	if len(ids) <= 0 {
		return rows
	}
	tx := db.DB("").Model(&model.TraceTask{})
	// 构建查询条件
	tx = tx.Where("id in ?", ids)
	// 查询数据
	if err := tx.Find(&rows).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows
	}
	return rows
}

// SelectByUnstopped 查询未停止的任务补发
func (r TraceTask) SelectByUnstopped(neStr string) []model.TraceTask {
	rows := []model.TraceTask{}
	tx := db.DB("").Model(&model.TraceTask{})
	// 构建查询条件
	tx = tx.Where("end_time > ? and ne_list like ?", time.Now().UnixMilli(), fmt.Sprintf("%%%s%%", neStr))
	// 查询数据
	if err := tx.Find(&rows).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows
	}
	return rows
}

// Insert 新增信息 返回新增数据ID
func (r TraceTask) Insert(param model.TraceTask) int64 {
	if param.CreateBy != "" {
		ms := time.Now().UnixMilli()
		param.CreateTime = ms
	}
	// 执行插入
	if err := db.DB("").Create(&param).Error; err != nil {
		logger.Errorf("insert err => %v", err.Error())
		return 0
	}
	return param.ID
}

// DeleteByIds 批量删除信息 返回受影响行数
func (r TraceTask) DeleteByIds(ids []int64) int64 {
	if len(ids) <= 0 {
		return 0
	}
	tx := db.DB("").Where("id in ?", ids)
	if err := tx.Delete(&model.TraceTask{}).Error; err != nil {
		logger.Errorf("delete err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}

// LastID 最后一条ID
func (r TraceTask) LastID() int64 {
	tx := db.DB("").Model(&model.TraceTask{})
	// 查询数据
	var id int64 = 0
	if err := tx.Select("id").Order("id DESC").Limit(1).Find(&id).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return id
	}
	return id
}
