package db

import (
	"context"
	"fmt"
	"github.com/sirupsen/logrus"
	"reflect"
	"youngee_b_api/model/common_model"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/util"
)

// GetFullLocalLifeList 查看所有本地生活列表
func GetFullLocalLifeList(ctx context.Context, pageSize, pageNum int32, condition *common_model.SLocalLifeCondition) ([]*gorm_model.YounggeeLocalLifeInfo, int64, error) {
	db := GetReadDB(ctx)

	// 根据带货任务状态过滤
	db = db.Debug().Model(gorm_model.YounggeeLocalLifeInfo{}).Where("task_status = 4")

	// 根据Project条件过滤
	conditionType := reflect.TypeOf(condition).Elem()
	conditionValue := reflect.ValueOf(condition).Elem()
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)
		if (tag == "local_id" || tag == "local_name") && !util.IsBlank(value) {
			db = db.Where(fmt.Sprintf("local_id like '%%%v%%' or local_name like '%%%v%%'", value.Interface(), value.Interface()))
		} else if tag == "updated_at" && value.Interface() != "0" {
			db = db.Where(fmt.Sprintf("updated_at like '%s%%'", value.Interface()))
		} else if !util.IsBlank(value) && tag != "updated_at" {
			db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
		}
	}

	// 查询总数
	var total int64
	var fullLocals []*gorm_model.YounggeeLocalLifeInfo
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	// 查询该页数据
	limit := pageSize
	offset := pageSize * pageNum // assert pageNum start with 0
	err := db.Order("updated_at desc").Limit(int(limit)).Offset(int(offset)).Find(&fullLocals).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	return fullLocals, total, nil
}
