package db

import (
	"context"
	"fmt"
	"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"

	"github.com/issue9/conv"
	"github.com/sirupsen/logrus"
	"github.com/tidwall/gjson"
)

func GetTaskFinishList(ctx context.Context, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.TaskFinishInfo, int64, error) {
	db := GetReadDB(ctx)
	// 查询Task表信息
	db = db.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("task_status = 2 and task_stage = 15")
	// 根据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 !util.IsBlank(value) {
			if tag == "platform_nickname" {
				platform_nickname = fmt.Sprintf("%v", value.Interface())
				continue
			} else if tag == "project_id" || tag == "strategy_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("[GetProjectTaskList] 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 DataInfos []gorm_model.YounggeeDataInfo
	db1 = db1.Model(gorm_model.YounggeeDataInfo{}).Where("task_id IN ? AND is_ok = 1", taskIds)
	err := db1.Find(&DataInfos).Error
	DataMap := make(map[string]gorm_model.YounggeeDataInfo)
	for _, DataInfo := range DataInfos {
		DataMap[DataInfo.TaskID] = DataInfo
	}

	var LinkInfos []gorm_model.YounggeeLinkInfo
	db2 := GetReadDB(ctx)
	db2 = db2.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id IN ? AND is_ok = 1", taskIds).Find(&LinkInfos)
	LinkMap := make(map[string]gorm_model.YounggeeLinkInfo)
	for _, LinkInfo := range LinkInfos {
		LinkMap[LinkInfo.TaskID] = LinkInfo
	}

	// 查询总数
	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
	}
	var misNum int64
	if totalData > totalTask {
		misNum = totalData - totalTask
	} else {
		misNum = totalTask - totalData
	}
	logrus.Println("totalData,totalTalent,misNum:", totalData, totalTask, misNum)

	// 查询该页数据
	limit := pageSize + misNum
	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("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	var TaskFinishs []*http_model.TaskFinish
	var taskDatas []*http_model.TaskFinishInfo
	var newTaskFinishs []*http_model.TaskFinishInfo
	for _, taskId := range taskIds {
		TaskFinish := new(http_model.TaskFinish)
		TaskFinish.Talent = taskMap[taskId]
		TaskFinish.Data = DataMap[taskId]
		TaskFinish.Link = LinkMap[taskId]
		TaskFinishs = append(TaskFinishs, TaskFinish)
	}

	taskDatas = pack.TaskFinishToTaskInfo(TaskFinishs)

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

func GetFinishData(ctx context.Context, projectID string) ([]*gorm_model.RecruitStrategy, error) {
	finishRecruitStrategy := []*gorm_model.RecruitStrategy{}
	db := GetReadDB(ctx)
	// 查询Task表信息
	err := db.Debug().Model(gorm_model.RecruitStrategy{}).Where("project_id = ?", projectID).Scan(&finishRecruitStrategy).Order("strategy_id").Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, err
	}
	return finishRecruitStrategy, nil
}

func GetSpecialTaskFinishList(ctx context.Context, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.SpecialTaskFinishDataInfo, int64, error) {
	db := GetReadDB(ctx)
	// 查询Task表信息
	db = db.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("task_status = 2 and task_stage = 15")
	// 根据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 !util.IsBlank(value) {
			if tag == "platform_nickname" {
				platform_nickname = fmt.Sprintf("%v", value.Interface())
				continue
			} else if tag == "project_id" || tag == "strategy_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("[GetProjectTaskList] 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 DataInfos []gorm_model.YounggeeDataInfo
	db1 = db1.Model(gorm_model.YounggeeDataInfo{}).Where("task_id IN ? AND is_ok = 1", taskIds)
	err := db1.Find(&DataInfos).Error
	DataMap := make(map[string]gorm_model.YounggeeDataInfo)
	for _, DataInfo := range DataInfos {
		DataMap[DataInfo.TaskID] = DataInfo
	}

	var LinkInfos []gorm_model.YounggeeLinkInfo
	db2 := GetReadDB(ctx)
	db2 = db2.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id IN ? AND is_ok = 1", taskIds).Find(&LinkInfos)
	LinkMap := make(map[string]gorm_model.YounggeeLinkInfo)
	for _, LinkInfo := range LinkInfos {
		LinkMap[LinkInfo.TaskID] = LinkInfo
	}

	// 查询总数
	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
	}
	var misNum int64
	if totalData > totalTask {
		misNum = totalData - totalTask
	} else {
		misNum = totalTask - totalData
	}
	logrus.Println("totalData,totalTalent,misNum:", totalData, totalTask, misNum)

	// 查询该页数据
	limit := pageSize + misNum
	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("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	var TaskFinishs []*http_model.SpecialTaskFinishData
	var taskDatas []*http_model.SpecialTaskFinishDataInfo
	var newTaskFinishs []*http_model.SpecialTaskFinishDataInfo
	for _, taskId := range taskIds {
		TaskFinish := new(http_model.SpecialTaskFinishData)
		TaskFinish.Talent = taskMap[taskId]
		TaskFinish.Data = DataMap[taskId]
		TaskFinish.Link = LinkMap[taskId]
		TaskFinishs = append(TaskFinishs, TaskFinish)
	}

	taskDatas = pack.SpecialTaskFinishDataToTaskInfo(TaskFinishs)

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

func GetSpecialFinishDataNumber(ctx context.Context, projectId string) (*http_model.GetSpecialFinishDataData, error) {
	db := GetReadDB(ctx)
	// 查询Task表信息
	db = db.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("task_status = 2 and task_stage = 15 and project_id = ?",projectId)
	var taskInfos []gorm_model.YoungeeTaskInfo
	// 查询总数
	var totalTask int64
	if err := db.Count(&totalTask).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetSpecialFinishDataNumber] error query mysql total, err:%+v", err)
		return nil, 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 DataInfos []gorm_model.YounggeeDataInfo
	db1 = db1.Model(gorm_model.YounggeeDataInfo{}).Where("task_id IN ? AND is_ok = 1", taskIds)
	err := db1.Find(&DataInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetSpecialFinishDataNumber] error query mysql total, err:%+v", err)
		return nil, err
	}
	DataMap := make(map[string]gorm_model.YounggeeDataInfo)
	for _, DataInfo := range DataInfos {
		DataMap[DataInfo.TaskID] = DataInfo
	}

	taskFinishData := http_model.GetSpecialFinishDataData{
		FinishNumber:  totalTask,
		FanNumber:     0,
		PlayNumber:    0,
		LikeNumber:    0,
		CommentNumber: 0,
		CollectNumber: 0,
	}
	for _, taskId := range taskIds {
		fans := conv.MustString(gjson.Get(taskMap[taskId].TalentPlatformInfoSnap, "fans_count"))
		taskFinishData.FanNumber += conv.MustInt(fans)
		taskFinishData.PlayNumber += DataMap[taskId].PlayNumber
		taskFinishData.LikeNumber += DataMap[taskId].LikeNumber
		taskFinishData.CollectNumber += DataMap[taskId].CollectNumber
		taskFinishData.CommentNumber += DataMap[taskId].CommentNumber
	}
	return &taskFinishData, nil
}
