package db

import (
	"context"
	"fmt"
	"reflect"
	"strconv"
	"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, operatorid string, operatetype int, projectid string, Enterpriseid string) error {
	var opid string
	var optype int
	switch operatetype {
	case 3:
		{
			opid = Enterpriseid
			optype = 1
		}
	case 4:
		{
			opid = operatorid
			optype = 2
		}
	}
	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, "b_operator": opid, "b_operator_type": optype}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YounggeeLinkInfo error,err:%+v", err)
		return err
	}
	var project gorm_model.ProjectInfo
	err = db.Model(gorm_model.ProjectInfo{}).Where("project_id = ?", projectid).Find(&project).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Sketch db] Find ProjectInfo error,err:%+v", err)
		return err
	}

	var link_default gorm_model.InfoAutoTask
	err = db.Model(gorm_model.InfoAutoTask{}).Where("auto_task_id = ?", project.AutoTaskID).Find(&link_default).Error
	if err != nil {
		return err
	}
	duration := time.Duration(link_default.LinkBreach) * time.Hour
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", TaskID).Updates(gorm_model.YoungeeTaskInfo{LinkStatus: 3, CurBreakAt: time.Now().Add(duration)}).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
}

// LinkOpinion 提交意见
func LocalLinkOpinion(ctx context.Context, TaskID string, ReviseOpinion string, operatorid string, operatetype int, projectid string, Enterpriseid string) error {
	var opid string
	var optype int
	switch operatetype {
	case 3:
		{
			opid = Enterpriseid
			optype = 1
		}
	case 4:
		{
			opid = operatorid
			optype = 2
		}
	}
	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, "b_operator": opid, "b_operator_type": optype}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YounggeeLinkInfo error,err:%+v", err)
		return err
	}
	var project gorm_model.YounggeeLocalLifeInfo
	err = db.Model(gorm_model.YounggeeLocalLifeInfo{}).Where("local_id = ?", projectid).Find(&project).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Sketch db] Find ProjectInfo error,err:%+v", err)
		return err
	}

	var link_default gorm_model.InfoAutoTask
	err = db.Model(gorm_model.InfoAutoTask{}).Where("auto_task_id = ?", project.AutoTaskId).Find(&link_default).Error
	if err != nil {
		return err
	}
	duration := time.Duration(link_default.LinkBreach) * time.Hour
	err = db.Model(gorm_model.YoungeeLocalTaskInfo{}).Where("task_id = ?", TaskID).Updates(gorm_model.YoungeeLocalTaskInfo{LinkStatus: 3, CurBreakAt: time.Now().Add(duration)}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeLocalTaskInfo{}).Where("task_id = ?", TaskID).Updates(gorm_model.YoungeeLocalTaskInfo{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, operatorid string, operatetype int, projectid string, isspecial int, Enterpriseid string) error {
	var opid string
	var optype int
	switch operatetype {
	case 3:
		{
			opid = Enterpriseid
			optype = 1
		}
	case 4:
		{
			opid = operatorid
			optype = 2
		}
	}
	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(), "b_operator": opid, "b_operator_type": optype}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YounggeeLinkInfo error,err:%+v", err)
		return err
	}
	var project gorm_model.ProjectInfo
	err = db.Model(gorm_model.ProjectInfo{}).Where("project_id = ?", projectid).Find(&project).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Sketch db] Find ProjectInfo error,err:%+v", err)
		return err
	}
	taskstages := 13
	nextstage := [6]int{0, 0, 0, 0, 0, 0} // 数组长度为6，表示6种工具 4,9,11,13
	if isspecial == 1 {

		toolList := strings.Split(project.Tools, ",")
		for _, tool := range toolList {
			// 将 tool 转换为整数
			if t, err := strconv.Atoi(tool); err == nil && t >= 0 && t <= len(nextstage) {
				nextstage[t-1] = 1
			}
		}
		for i := 4; i < len(nextstage); i++ { // 从位置1开始
			if nextstage[i] == 1 {
				switch i {
				case 4:
					taskstages = 13
				case 5:
					taskstages = 15
				}
				break
			}
		}
	}
	var data_default gorm_model.InfoAutoTask
	err = db.Model(gorm_model.InfoAutoTask{}).Where("auto_task_id = ?", project.AutoTaskID).Find(&data_default).Error
	if err != nil {
		return err
	}
	duration := time.Duration(data_default.CaseCloseDefault) * time.Hour

	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeTaskInfo{LinkStatus: 5, CurBreakAt: time.Now().Add(duration)}).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: taskstages}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	return nil
}

// AcceptLink 同意链接
func LocalAcceptLink(ctx context.Context, TaskIDs []string, operatorid string, operatetype int, projectid string, isspecial int, Enterpriseid string) error {
	var opid string
	var optype int
	switch operatetype {
	case 3:
		{
			opid = Enterpriseid
			optype = 1
		}
	case 4:
		{
			opid = operatorid
			optype = 2
		}
	}
	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(), "b_operator": opid, "b_operator_type": optype}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YounggeeLinkInfo error,err:%+v", err)
		return err
	}
	var project gorm_model.YounggeeLocalLifeInfo
	err = db.Model(gorm_model.YounggeeLocalLifeInfo{}).Where("local_id = ?", projectid).Find(&project).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Sketch db] Find YounggeeLocalLifeInfo error,err:%+v", err)
		return err
	}
	taskstages := 13
	nextstage := [6]int{0, 0, 0, 0, 0, 0} // 数组长度为6，表示6种工具 4,9,11,13
	if isspecial == 1 {

		toolList := strings.Split(project.Tools, ",")
		for _, tool := range toolList {
			// 将 tool 转换为整数
			if t, err := strconv.Atoi(tool); err == nil && t >= 0 && t <= len(nextstage) {
				nextstage[t-1] = 1
			}
		}
		for i := 4; i < len(nextstage); i++ { // 从位置1开始
			if nextstage[i] == 1 {
				switch i {
				case 4:
					taskstages = 13
				case 5:
					taskstages = 15
				}
				break
			}
		}
	}

	var data_default gorm_model.InfoAutoTask
	err = db.Model(gorm_model.InfoAutoTask{}).Where("auto_task_id = ?", project.AutoTaskId).Find(&data_default).Error
	if err != nil {
		return err
	}
	duration := time.Duration(data_default.CaseCloseDefault) * time.Hour

	err = db.Model(gorm_model.YoungeeLocalTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeLocalTaskInfo{LinkStatus: 5, CurBreakAt: time.Now().Add(duration)}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeLocalTaskInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeLocalTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeLocalTaskInfo{TaskStage: taskstages}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeLocalTaskInfo error,err:%+v", err)
		return err
	}
	return nil
}

// RejectLink 不同意链接
func RejectLink(ctx context.Context, TaskIDs []string, operatorid string, operatetype int, projectid string, Enterpriseid string) error {
	var opid string
	var optype int
	switch operatetype {
	case 3:
		{
			opid = Enterpriseid
			optype = 1
		}
	case 4:
		{
			opid = operatorid
			optype = 2
		}
	}
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id in ?  and is_review = 0", TaskIDs).Updates(map[string]interface{}{"is_ok": 0, "is_review": 1, "reject_at": time.Now(), "b_operator": opid, "b_operator_type": optype}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YounggeeLinkInfo error,err:%+v", err)
		return err
	}
	var project gorm_model.ProjectInfo
	err = db.Model(gorm_model.ProjectInfo{}).Where("project_id = ?", projectid).Find(&project).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Sketch db] Find ProjectInfo error,err:%+v", err)
		return err
	}

	var link_default gorm_model.InfoAutoTask
	err = db.Model(gorm_model.InfoAutoTask{}).Where("auto_task_id = ?", project.AutoTaskID).Find(&link_default).Error
	if err != nil {
		return err
	}
	duration := time.Duration(link_default.LinkBreach) * time.Hour
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeTaskInfo{LinkStatus: 3, CurBreakAt: time.Now().Add(duration)}).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: 11}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	return nil
}

// RejectLink 不同意链接
func LocalRejectLink(ctx context.Context, TaskIDs []string, operatorid string, operatetype int, projectid string, Enterpriseid string) error {
	var opid string
	var optype int
	switch operatetype {
	case 3:
		{
			opid = Enterpriseid
			optype = 1
		}
	case 4:
		{
			opid = operatorid
			optype = 2
		}
	}
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id in ?  and is_review = 0", TaskIDs).Updates(map[string]interface{}{"is_ok": 0, "is_review": 1, "reject_at": time.Now(), "b_operator": opid, "b_operator_type": optype}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YounggeeLinkInfo error,err:%+v", err)
		return err
	}
	var project gorm_model.YounggeeLocalLifeInfo
	err = db.Model(gorm_model.YounggeeLocalLifeInfo{}).Where("local_id = ?", projectid).Find(&project).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Sketch db] Find ProjectInfo error,err:%+v", err)
		return err
	}

	var link_default gorm_model.InfoAutoTask
	err = db.Model(gorm_model.InfoAutoTask{}).Where("auto_task_id = ?", project.AutoTaskId).Find(&link_default).Error
	if err != nil {
		return err
	}
	duration := time.Duration(link_default.LinkBreach) * time.Hour
	err = db.Model(gorm_model.YoungeeLocalTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeLocalTaskInfo{LinkStatus: 3, CurBreakAt: time.Now().Add(duration)}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeLocalTaskInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeLocalTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeLocalTaskInfo{TaskStage: 11}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link db] Update YoungeeLocalTaskInfo 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
}
