package db

import (
	"context"
	"fmt"
	"reflect"
	"strings"
	"time"
	"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"
)

// GetTaskLinkList 查询上传链接的task list
func GetTaskLinkList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.TaskLinkInfo, 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 == "link_status" {
			fmt.Printf("link %+v", value.Interface() == int64(0))
			if value.Interface() == int64(0) {
				db = db.Where("task_stage = 12")
			} else {
				db = db.Where("task_stage > 12 and task_stage <> 16")
			}
			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.YounggeeLinkInfo{})

	var LinkInfos []gorm_model.YounggeeLinkInfo
	db1 = db1.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id IN ? AND is_submit=? ", taskIds, 1)
	if conditions.LinkStatus == int64(0) {
		db1 = db1.Where("is_review = 0").Find(&LinkInfos)
	} else {
		db1 = db1.Where("is_ok = 1").Find(&LinkInfos)
	}
	LinkMap := make(map[string]gorm_model.YounggeeLinkInfo)
	for _, LinkInfo := range LinkInfos {
		LinkMap[LinkInfo.TaskID] = LinkInfo
	}
	// 查询总数
	var totalLink int64
	if err := db1.Count(&totalLink).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	var misNum int64
	if totalLink > totalTask {
		misNum = totalLink - totalTask
	} else {
		misNum = totalTask - totalLink
	}
	logrus.Println("totalLink,totalTalent,misNum:", totalLink, 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 TaskLinks []*http_model.TaskLink
	var taskLinks []*http_model.TaskLinkInfo
	var newTaskLinks []*http_model.TaskLinkInfo
	for _, taskId := range taskIds {
		TaskLink := new(http_model.TaskLink)
		TaskLink.Talent = taskMap[taskId]
		TaskLink.Link = LinkMap[taskId]
		TaskLinks = append(TaskLinks, TaskLink)
	}

	taskLinks = pack.TaskLinkToTaskInfo(TaskLinks)

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

// LinkOpinion 提交意见
func LinkOpinion(ctx context.Context, TaskID string, ReviseOpinion string) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id = ? and is_review = 0", TaskID).Updates(map[string]interface{}{"revise_opinion": ReviseOpinion, "reject_at": time.Now(), "is_review": 1}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YounggeeLinkInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", TaskID).Updates(gorm_model.YoungeeTaskInfo{LinkStatus: 3}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", TaskID).Updates(gorm_model.YoungeeTaskInfo{TaskStage: 11}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	return nil
}

// AcceptLink 同意链接
func AcceptLink(ctx context.Context, TaskIDs []string) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id in ?  and is_review = 0", TaskIDs).Updates(map[string]interface{}{"is_ok": 1, "is_review": 1, "agree_at": time.Now()}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YounggeeLinkInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeTaskInfo{LinkStatus: 5}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeTaskInfo{TaskStage: 13}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	return nil
}

// GetSpecialTaskLinkList 专项任务-查询上传链接的task list
func GetSpecialTaskLinkList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.SpecialTaskLinkInfo, 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 == "link_status" {
			fmt.Printf("link %+v", value.Interface() == int64(0))
			if value.Interface() == int64(0) {
				db = db.Where("task_stage = 12")
			} else {
				db = db.Where("task_stage > 12 and task_stage <> 16")
			}
			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("[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.YounggeeLinkInfo{})

	var LinkInfos []gorm_model.YounggeeLinkInfo
	db1 = db1.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id IN ? AND is_submit=? ", taskIds, 1)
	if conditions.LinkStatus == int64(0) {
		db1 = db1.Where("is_review = 0").Find(&LinkInfos)
	} else {
		db1 = db1.Where("is_ok = 1").Find(&LinkInfos)
	}
	LinkMap := make(map[string]gorm_model.YounggeeLinkInfo)
	for _, LinkInfo := range LinkInfos {
		LinkMap[LinkInfo.TaskID] = LinkInfo
	}
	// 查询总数
	var totalLink int64
	if err := db1.Count(&totalLink).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	var misNum int64
	if totalLink > totalTask {
		misNum = totalLink - totalTask
	} else {
		misNum = totalTask - totalLink
	}
	logrus.Println("totalLink,totalTalent,misNum:", totalLink, 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 TaskLinks []*http_model.SpecialTaskLink
	var taskLinks []*http_model.SpecialTaskLinkInfo
	var newTaskLinks []*http_model.SpecialTaskLinkInfo
	for _, taskId := range taskIds {
		TaskLink := new(http_model.SpecialTaskLink)
		TaskLink.Talent = taskMap[taskId]
		TaskLink.Link = LinkMap[taskId]
		TaskLinks = append(TaskLinks, TaskLink)
	}

	taskLinks = pack.SpecialTaskLinkToTaskInfo(TaskLinks)

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

// GetLinkByTaskId 通过taskId查询链接信息
func GetLinkByTaskId(ctx context.Context, taskIds string) ([]*gorm_model.YounggeeLinkInfo, error) {
	db := GetReadDB(ctx)
	var taskLink []*gorm_model.YounggeeLinkInfo
	err := db.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id = ?", taskIds).Find(&taskLink).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YounggeeLinkInfo error,err:%+v", err)
		return nil, err
	}
	return taskLink, nil
}
