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"
)

func GetTaskDefaultReviewList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.TaskDefaultReviewInfo, 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 == "default_status" {
			fmt.Printf("default %+v", value.Interface() == int64(0))
			if value.Interface() == int64(0) {
				db = db.Where("cur_default_type = 1")
			} else if value.Interface() == int64(1) {
				db = db.Where("cur_default_type = 3")
			} else if value.Interface() == int64(2) {
				db = db.Where("cur_default_type = 5")
			}
			continue
		} else 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)
	var DefaultReviewInfos []gorm_model.YoungeeContractInfo
	db1 = db1.Model(gorm_model.YoungeeContractInfo{}).Where("task_id IN ? AND (default_status = 1 OR default_status = 4)", taskIds)
	err := db1.Find(&DefaultReviewInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	DefaultReviewMap := make(map[string]gorm_model.YoungeeContractInfo)
	for _, DefaultReviewInfo := range DefaultReviewInfos {
		DefaultReviewMap[DefaultReviewInfo.TaskID] = DefaultReviewInfo
	}
	// 查询总数
	var totalDefaultReview int64
	if err := db1.Count(&totalDefaultReview).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("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	var TaskDefaultReviews []*http_model.TaskDefaultReview
	var taskDefaultReviews []*http_model.TaskDefaultReviewInfo
	var newTaskDefaultReviews []*http_model.TaskDefaultReviewInfo
	for _, taskId := range taskIds {
		TaskDefaultReview := new(http_model.TaskDefaultReview)
		TaskDefaultReview.Talent = taskMap[taskId]
		TaskDefaultReview.Default = DefaultReviewMap[taskId]
		TaskDefaultReviews = append(TaskDefaultReviews, TaskDefaultReview)
	}

	taskDefaultReviews = pack.TaskDefaultReviewToTaskInfo(TaskDefaultReviews)

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

func GetTaskDefaultDataList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.TaskDefaultDataInfo, 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 == "default_status" {
			if value.Interface() == int64(3) {
				db = db.Where("cur_default_type = 7")
			} else if value.Interface() == int64(2) {
				db = db.Where("cur_default_type = 5")
			} else if value.Interface() == int64(1) {
				db = db.Where("cur_default_type = 3")
			} else if value.Interface() == int64(0) {
				db = db.Where("cur_default_type = 1")
			}
			continue
		} else 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.YoungeeContractInfo{})

	var DefaultDataInfos []gorm_model.YoungeeContractInfo
	db1 = db1.Model(gorm_model.YoungeeContractInfo{}).Where("task_id IN ? AND (default_status = 1 OR default_status = 4)", taskIds)
	err := db1.Find(&DefaultDataInfos).Error
	DefaultDataMap := make(map[string]gorm_model.YoungeeContractInfo)
	for _, DefaultDataInfo := range DefaultDataInfos {
		DefaultDataMap[DefaultDataInfo.TaskID] = DefaultDataInfo
	}

	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 totalDefaultData int64
	if err := db2.Count(&totalDefaultData).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	var misNum int64
	if totalDefaultData > totalTask {
		misNum = totalDefaultData - totalTask
	} else {
		misNum = totalTask - totalDefaultData
	}
	logrus.Println("totalDefaultData,totalTalent,misNum:", totalDefaultData, 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 TaskDefaultDatas []*http_model.TaskDefaultData
	var taskDefaultDatas []*http_model.TaskDefaultDataInfo
	var newTaskDefaultDatas []*http_model.TaskDefaultDataInfo
	for _, taskId := range taskIds {
		TaskDefaultData := new(http_model.TaskDefaultData)
		TaskDefaultData.Talent = taskMap[taskId]
		TaskDefaultData.Default = DefaultDataMap[taskId]
		TaskDefaultData.Link = LinkMap[taskId]
		TaskDefaultDatas = append(TaskDefaultDatas, TaskDefaultData)
	}

	taskDefaultDatas = pack.TaskDefaultDataToTaskInfo(TaskDefaultDatas)

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

func GetTaskTerminatingList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.TaskTerminatingInfo, int64, error) {
	db := GetReadDB(ctx)

	var taskIds1 []string
	var totalTerminating int64
	var TerminatingInfos []gorm_model.YoungeeContractInfo
	db = db.Model(gorm_model.YoungeeContractInfo{})
	err := db.Where("default_status = 3 AND project_id=?", projectID).Find(&TerminatingInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	TerminatingMap := make(map[string]gorm_model.YoungeeContractInfo)
	for _, TerminatingInfo := range TerminatingInfos {
		taskIds1 = append(taskIds1, TerminatingInfo.TaskID)
		TerminatingMap[TerminatingInfo.TaskID] = TerminatingInfo
	}

	if err := db.Count(&totalTerminating).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	db1 := GetReadDB(ctx)
	// 查询Task表信息
	db1 = db1.Model(gorm_model.YoungeeTaskInfo{}).Where("task_status = 2 and task_id in ?", taskIds1)
	// 根据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 == "default_status" {
			if value.Interface() == int64(4) {
				db1 = db1.Where("cur_default_type = 9")
			}
			continue
		} else if !util.IsBlank(value) {
			if tag == "platform_nickname" {
				platform_nickname = fmt.Sprintf("%v", value.Interface())
				continue
			} else if tag == "project_id" || tag == "strategy_id" {
				db1 = db1.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
			}
		}
	}
	var taskInfos []gorm_model.YoungeeTaskInfo
	// db1 = db1.Model(gorm_model.YoungeeTaskInfo{})
	// 查询总数
	var totalTask int64
	if err := db1.Count(&totalTask).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	db1.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
	}
	var misNum int64
	if totalTerminating > totalTask {
		misNum = totalTerminating - totalTask
	} else {
		misNum = totalTask - totalTerminating
	}
	logrus.Println("totalTerminating,totalTalent,misNum:", totalTerminating, totalTask, misNum)

	// 查询该页数据
	limit := pageSize + misNum
	offset := pageSize * pageNum // assert pageNum start with 0
	err = db1.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 TaskTerminatings []*http_model.TaskTerminating
	var taskTerminatings []*http_model.TaskTerminatingInfo
	var newTaskTerminatings []*http_model.TaskTerminatingInfo
	for _, taskId := range taskIds {
		TaskTerminating := new(http_model.TaskTerminating)
		TaskTerminating.Talent = taskMap[taskId]
		TaskTerminating.Default = TerminatingMap[taskId]
		TaskTerminatings = append(TaskTerminatings, TaskTerminating)
	}

	taskTerminatings = pack.TaskTerminatingToTaskInfo(TaskTerminatings)

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

func GetTaskTerminatedList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.TaskTerminatedInfo, 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 == "default_status" {
			fmt.Printf("default %+v", value.Interface() == int64(0))
			if value.Interface() == int64(5) {
				db = db.Where("complete_status = 4")
			}
			continue
		} else 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("[GetTaskTerminatedList] 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.YoungeeContractInfo{})

	var TerminatedInfos []gorm_model.YoungeeContractInfo
	db1 = db1.Model(gorm_model.YoungeeContractInfo{}).Where("task_id IN ? AND (default_status = 1 OR default_status = 5)", taskIds)
	err := db1.Find(&TerminatedInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetTaskTerminatedList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	TerminatedMap := make(map[string]gorm_model.YoungeeContractInfo)
	for _, TerminatedInfo := range TerminatedInfos {
		TerminatedMap[TerminatedInfo.TaskID] = TerminatedInfo
	}
	// 查询总数
	var totalTerminated int64
	if err := db1.Count(&totalTerminated).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetTaskTerminatedList] 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("[GetTaskTerminatedList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	var TaskTerminateds []*http_model.TaskTerminated
	var taskTerminateds []*http_model.TaskTerminatedInfo
	var newTaskTerminateds []*http_model.TaskTerminatedInfo
	for _, taskId := range taskIds {
		TaskTerminated := new(http_model.TaskTerminated)
		TaskTerminated.Talent = taskMap[taskId]
		TaskTerminated.Default = TerminatedMap[taskId]
		TaskTerminateds = append(TaskTerminateds, TaskTerminated)
	}

	taskTerminateds = pack.TaskTerminatedToTaskInfo(TaskTerminateds)

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