package db

import (
	"context"
	"fmt"
	"github.com/issue9/conv"
	"github.com/sirupsen/logrus"
	"reflect"
	"strings"
	"youngee_b_api/model/common_model"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
	"youngee_b_api/pack"
	"youngee_b_api/util"
)

// GetSpecialTaskSettleList 专项任务-查询上传链接的task list
func GetSpecialTaskSettleList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.SpecialTaskSettleInfo, int64, error) {
	db := GetReadDB(ctx)
	// 查询Task表信息
	db = db.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("task_status = 2")
	// 根据Project条件过滤
	conditionType := reflect.TypeOf(conditions).Elem()
	conditionValue := reflect.ValueOf(conditions).Elem()
	var platform_nickname string = ""
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)

		if tag == "settle_status" {
			fmt.Printf("Data %+v", value.Interface() == int64(0))
			if value.Interface() == int64(0) {
				db = db.Where("task_stage = 15 and settle_status = 1")
			} else {
				db = db.Where("task_stage = 15 and settle_status = 2")
			}
			continue
		} else if !util.IsBlank(value) {
			if tag == "platform_nickname" {
				platform_nickname = fmt.Sprintf("%v", value.Interface())
				continue
			} else if tag == "project_id" {
				db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
			}
		}
	}
	var taskInfos []gorm_model.YoungeeTaskInfo
	db = db.Model(gorm_model.YoungeeTaskInfo{})
	// 查询总数
	var totalTask int64
	if err := db.Count(&totalTask).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetTaskSettleList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	db.Order("task_id").Find(&taskInfos)

	// 查询任务id
	var taskIds []string
	taskMap := make(map[string]gorm_model.YoungeeTaskInfo)
	for _, taskInfo := range taskInfos {
		taskIds = append(taskIds, taskInfo.TaskID)
		taskMap[taskInfo.TaskID] = taskInfo
	}

	// 查询链接
	db1 := GetReadDB(ctx)
	// db1 = db1.Debug().Model(gorm_model.YounggeeDataInfo{})
	var LinkInfos []gorm_model.YounggeeLinkInfo
	db1 = db1.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id IN ? AND is_submit= 1 AND is_ok = 1", taskIds)
	err := db1.Find(&LinkInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	LinkMap := make(map[string]gorm_model.YounggeeLinkInfo)
	for _, LinkInfo := range LinkInfos {
		LinkMap[LinkInfo.TaskID] = LinkInfo
	}

	// 查询数据
	db2 := GetReadDB(ctx)
	var DataInfos []gorm_model.YounggeeDataInfo
	db2 = db2.Model(gorm_model.YounggeeDataInfo{}).Where("task_id IN ? AND is_submit= 1 AND is_ok = 1", taskIds)
	err = db2.Find(&DataInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	DataMap := make(map[string]gorm_model.YounggeeDataInfo)
	for _, DataInfo := range DataInfos {
		DataMap[DataInfo.TaskID] = DataInfo
	}
	// 查询总数
	var totalData int64
	if err := db2.Count(&totalData).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

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

	var TaskSettles []*http_model.SpecialTaskSettle
	var taskSettles []*http_model.SpecialTaskSettleInfo
	var newTaskSettles []*http_model.SpecialTaskSettleInfo
	for _, taskId := range taskIds {
		TaskSettle := new(http_model.SpecialTaskSettle)
		TaskSettle.Talent = taskMap[taskId]
		TaskSettle.Data = DataMap[taskId]
		TaskSettle.Link = LinkMap[taskId]
		TaskSettles = append(TaskSettles, TaskSettle)
	}

	taskSettles = pack.SpecialTaskSettleToTaskInfo(TaskSettles)

	for _, v := range taskSettles {
		if platform_nickname == "" {
			newTaskSettles = append(newTaskSettles, v)
		} else if strings.Contains(v.PlatformNickname, platform_nickname) {
			newTaskSettles = append(newTaskSettles, v)
		} else if strings.Contains(conv.MustString(v.TaskID, ""), platform_nickname) {
			newTaskSettles = append(newTaskSettles, v)
		} else {
			totalTask--
		}
	}
	return newTaskSettles, totalTask, nil
}
