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

// GetTaskScriptList 查询上传脚本的task list
func GetTaskScriptList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.TaskScriptInfo, 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 == "script_status" {
			fmt.Printf("script %+v", value.Interface() == int64(2))
			if value.Interface() == int64(2) {
				db = db.Where("task_stage = 8")
			} else {
				db = db.Where("task_stage > 8 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.YounggeeScriptInfo{})

	var ScriptInfos []gorm_model.YounggeeScriptInfo
	db1 = db1.Model(gorm_model.YounggeeScriptInfo{}).Where("task_id IN ? AND is_submit=? ", taskIds, 1)
	if conditions.ScriptStatus == int64(2) {
		db1 = db1.Where("is_review = 0").Find(&ScriptInfos)
	} else {
		db1 = db1.Where("is_ok = 1").Find(&ScriptInfos)
	}
	ScriptMap := make(map[string]gorm_model.YounggeeScriptInfo)
	for _, ScriptInfo := range ScriptInfos {
		ScriptMap[ScriptInfo.TaskID] = ScriptInfo
	}
	// 查询总数
	var totalScript int64
	if err := db1.Count(&totalScript).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	var misNum int64
	if totalScript > totalTask {
		misNum = totalScript - totalTask
	} else {
		misNum = totalTask - totalScript
	}
	logrus.Println("totalScript,totalTalent,misNum:", totalScript, 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 TaskScripts []*http_model.TaskScript
	var taskScripts []*http_model.TaskScriptInfo
	var newTaskScripts []*http_model.TaskScriptInfo
	for _, taskId := range taskIds {
		TaskScript := new(http_model.TaskScript)
		TaskScript.Talent = taskMap[taskId]
		TaskScript.Script = ScriptMap[taskId]
		TaskScripts = append(TaskScripts, TaskScript)
	}

	taskScripts = pack.TaskScriptToTaskInfo(TaskScripts)

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

// ScriptOpinion 提交意见
func ScriptOpinion(ctx context.Context, TaskID string, ReviseOpinion string) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YounggeeScriptInfo{}).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("[Script db] Update YounggeeScriptInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", TaskID).Updates(gorm_model.YoungeeTaskInfo{ScriptStatus: 3}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Script db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", TaskID).Updates(gorm_model.YoungeeTaskInfo{TaskStage: 7}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Script db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	return nil
}

// AcceptScript 同意脚本
func AcceptScript(ctx context.Context, TaskIDs []string) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YounggeeScriptInfo{}).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("[Script db] Update YounggeeScriptInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeTaskInfo{ScriptStatus: 5}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Script 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: 9}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Script db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	return nil
}

// GetSpecialTaskScriptList 专项任务-查询上传脚本的task list
func GetSpecialTaskScriptList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.SpecialTaskScriptInfo, 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 == "script_status" {
			fmt.Printf("script %+v", value.Interface() == int64(2))
			if value.Interface() == int64(2) {
				db = db.Where("task_stage = 8")
			} else {
				db = db.Where("task_stage > 8 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.YounggeeScriptInfo{})

	var ScriptInfos []gorm_model.YounggeeScriptInfo
	db1 = db1.Model(gorm_model.YounggeeScriptInfo{}).Where("task_id IN ? AND is_submit=? ", taskIds, 1)
	if conditions.ScriptStatus == int64(2) {
		db1 = db1.Where("is_review = 0").Find(&ScriptInfos)
	} else {
		db1 = db1.Where("is_ok = 1").Find(&ScriptInfos)
	}
	ScriptMap := make(map[string]gorm_model.YounggeeScriptInfo)
	for _, ScriptInfo := range ScriptInfos {
		ScriptMap[ScriptInfo.TaskID] = ScriptInfo
	}
	// 查询总数
	var totalScript int64
	if err := db1.Count(&totalScript).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	var misNum int64
	if totalScript > totalTask {
		misNum = totalScript - totalTask
	} else {
		misNum = totalTask - totalScript
	}
	logrus.Println("totalScript,totalTalent,misNum:", totalScript, 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 TaskScripts []*http_model.SpecialTaskScript
	var taskScripts []*http_model.SpecialTaskScriptInfo
	var newTaskScripts []*http_model.SpecialTaskScriptInfo
	for _, taskId := range taskIds {
		TaskScript := new(http_model.SpecialTaskScript)
		TaskScript.Talent = taskMap[taskId]
		TaskScript.Script = ScriptMap[taskId]
		TaskScripts = append(TaskScripts, TaskScript)
	}

	taskScripts = pack.SpecialTaskScriptToTaskInfo(TaskScripts)

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