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

// GetTaskDataList 查询上传数据的task list
func GetTaskDataList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.TaskDataInfo, 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 == "data_status" {
			fmt.Printf("Data %+v", value.Interface() == int64(0))
			if value.Interface() == int64(0) {
				db = db.Where("task_stage = 14")
			} else {
				db = db.Where("task_stage > 14 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("[GetTaskDataList] 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 LinkInfos []gorm_model.YounggeeLinkInfo
	db1 = db1.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id IN ? AND is_submit= 1 AND is_ok = 1", taskIds)
	err := db1.Find(&LinkInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	LinkMap := make(map[string]gorm_model.YounggeeLinkInfo)
	for _, LinkInfo := range LinkInfos {
		LinkMap[LinkInfo.TaskID] = LinkInfo
	}

	db2 := GetReadDB(ctx)
	// db2 = db1.Debug().Model(gorm_model.YounggeeDataInfo{})

	var DataInfos []gorm_model.YounggeeDataInfo
	db2 = db2.Model(gorm_model.YounggeeDataInfo{}).Where("task_id IN ? AND is_submit = 1", taskIds)
	fmt.Printf("conditions %+v", conditions)
	if conditions.DataStatus == int64(0) {
		db2 = db2.Where("is_review = 0")
	} else {
		db2 = db2.Where("is_ok = 1")
	}
	err = db2.Find(&DataInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	DataMap := make(map[string]gorm_model.YounggeeDataInfo)
	for _, DataInfo := range DataInfos {
		DataMap[DataInfo.TaskID] = DataInfo
	}
	// 查询总数
	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("[GetTaskDataList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	var TaskDatas []*http_model.TaskData
	var taskDatas []*http_model.TaskDataInfo
	var newTaskDatas []*http_model.TaskDataInfo
	for _, taskId := range taskIds {
		TaskData := new(http_model.TaskData)
		TaskData.Talent = taskMap[taskId]
		TaskData.Data = DataMap[taskId]
		TaskData.Link = LinkMap[taskId]
		TaskDatas = append(TaskDatas, TaskData)
	}

	taskDatas = pack.TaskDataToTaskInfo(TaskDatas)

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

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

// AcceptData 同意数据-结案
func AcceptData(ctx context.Context, TaskIDs []string) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YounggeeDataInfo{}).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("[Data db] Update YounggeeDataInfo error,err:%+v", err)
		return err
	}
	return nil
}

// GetSpecialTaskDataList 专项任务-查询上传数据的task list
func GetSpecialTaskDataList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.SpecialTaskDataInfo, 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 == "data_status" {
			fmt.Printf("Data %+v", value.Interface() == int64(0))
			if value.Interface() == int64(0) {
				db = db.Where("task_stage = 14")
			} else {
				db = db.Where("task_stage > 14 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("[GetTaskDataList] 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 LinkInfos []gorm_model.YounggeeLinkInfo
	db1 = db1.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id IN ? AND is_submit= 1 AND is_ok = 1", taskIds)
	err := db1.Find(&LinkInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	LinkMap := make(map[string]gorm_model.YounggeeLinkInfo)
	for _, LinkInfo := range LinkInfos {
		LinkMap[LinkInfo.TaskID] = LinkInfo
	}

	db2 := GetReadDB(ctx)
	// db2 = db1.Debug().Model(gorm_model.YounggeeDataInfo{})

	var DataInfos []gorm_model.YounggeeDataInfo
	db2 = db2.Model(gorm_model.YounggeeDataInfo{}).Where("task_id IN ? AND is_submit = 1", taskIds)
	fmt.Printf("conditions %+v", conditions)
	if conditions.DataStatus == int64(0) {
		db2 = db2.Where("is_review = 0")
	} else {
		db2 = db2.Where("is_ok = 1")
	}
	err = db2.Find(&DataInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	DataMap := make(map[string]gorm_model.YounggeeDataInfo)
	for _, DataInfo := range DataInfos {
		DataMap[DataInfo.TaskID] = DataInfo
	}
	// 查询总数
	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("[GetTaskDataList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	var TaskDatas []*http_model.SpecialTaskData
	var taskDatas []*http_model.SpecialTaskDataInfo
	var newTaskDatas []*http_model.SpecialTaskDataInfo
	for _, taskId := range taskIds {
		TaskData := new(http_model.SpecialTaskData)
		TaskData.Talent = taskMap[taskId]
		TaskData.Data = DataMap[taskId]
		TaskData.Link = LinkMap[taskId]
		TaskDatas = append(TaskDatas, TaskData)
	}

	taskDatas = pack.SpecialTaskDataToTaskInfo(TaskDatas)

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