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

// GetTaskSketchList 查询上传初稿的task list
func GetTaskSketchList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.TaskSketchInfo, 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 == "sketch_status" {
			fmt.Printf("sketch %+v", value.Interface() == int64(0))
			if value.Interface() == int64(0) {
				db = db.Where("task_stage = 10")
			} else {
				db = db.Where("task_stage > 10 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.YounggeeSketchInfo{})

	var SketchInfos []gorm_model.YounggeeSketchInfo
	db1 = db1.Model(gorm_model.YounggeeSketchInfo{}).Where("task_id IN ? AND is_submit=? ", taskIds, 1)
	if conditions.SketchStatus == int64(0) {
		db1 = db1.Where("is_review = 0").Find(&SketchInfos)
	} else {
		db1 = db1.Where("is_ok = 1").Find(&SketchInfos)
	}
	fmt.Printf("初稿查询：%+v", SketchInfos)
	SketchMap := make(map[string]gorm_model.YounggeeSketchInfo)
	for _, SketchInfo := range SketchInfos {
		SketchMap[SketchInfo.TaskID] = SketchInfo
	}
	// 查询总数
	var totalSketch int64
	if err := db1.Count(&totalSketch).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTalentList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	var misNum int64
	if totalSketch > totalTask {
		misNum = totalSketch - totalTask
	} else {
		misNum = totalTask - totalSketch
	}
	logrus.Println("totalSketch,totalTalent,misNum:", totalSketch, totalTask, misNum)

	// 查询该页数据
	limit := pageSize + misNum
	offset := pageSize * pageNum // assert pageNum start with 0
	//fmt.Printf("limit %+v  offset %+v \n", limit, offset)
	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 TaskSketches []*http_model.TaskSketch
	var taskSketches []*http_model.TaskSketchInfo
	var newTaskSketches []*http_model.TaskSketchInfo
	for _, taskId := range taskIds {
		TaskSketch := new(http_model.TaskSketch)
		TaskSketch.Talent = taskMap[taskId]
		TaskSketch.Sketch = SketchMap[taskId]
		TaskSketches = append(TaskSketches, TaskSketch)
	}

	taskSketches = pack.TaskSketchToTaskInfo(TaskSketches)

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

// SketchOption 提交意见
func SketchOption(ctx context.Context, TaskID string, ReviseOpinion string) error {
	db := GetReadDB(ctx)
	fmt.Printf("初稿意见 %d %+v", TaskID, ReviseOpinion)
	err := db.Model(gorm_model.YounggeeSketchInfo{}).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("[Sketch db] call RevisieOption error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", TaskID).Updates(gorm_model.YoungeeTaskInfo{SketchStatus: 3}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Sketch db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", TaskID).Updates(gorm_model.YoungeeTaskInfo{TaskStage: 9}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Sketch db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	return nil
}

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

// FindPhoto
func FindSketchInfo(ctx context.Context, TaskID string) (*gorm_model.YounggeeSketchInfo, error) {
	db := GetReadDB(ctx)
	var SketchInfo gorm_model.YounggeeSketchInfo
	err := db.Model(gorm_model.YounggeeSketchInfo{}).Where("task_id = ? and is_ok = 1", TaskID).Find(&SketchInfo).Error
	if err != nil {
		return nil, err
	}
	return &SketchInfo, nil
}

// FindPhoto
func FindPhoto(ctx context.Context, SketchID int64) ([]gorm_model.YounggeeSketchPhoto, error) {
	db := GetReadDB(ctx)
	var SketchPhotos []gorm_model.YounggeeSketchPhoto
	err := db.Model(gorm_model.YounggeeSketchPhoto{}).Where("sketch_id=?", SketchID).Find(&SketchPhotos).Error
	if err != nil {
		return nil, err
	}
	return SketchPhotos, nil

}

// GetSpecialTaskSketchList 专项任务-查询上传初稿的task list
func GetSpecialTaskSketchList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.SpecialTaskSketchInfo, 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 == "sketch_status" {
			fmt.Printf("sketch %+v", value.Interface() == int64(0))
			if value.Interface() == int64(0) {
				db = db.Where("task_stage = 10")
			} else {
				db = db.Where("task_stage > 10 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.YounggeeSketchInfo{})

	var SketchInfos []gorm_model.YounggeeSketchInfo
	db1 = db1.Model(gorm_model.YounggeeSketchInfo{}).Where("task_id IN ? AND is_submit=? ", taskIds, 1)
	if conditions.SketchStatus == int64(0) {
		db1 = db1.Where("is_review = 0").Find(&SketchInfos)
	} else {
		db1 = db1.Where("is_ok = 1").Find(&SketchInfos)
	}
	//fmt.Printf("初稿查询：%+v", SketchInfos)
	SketchMap := make(map[string]gorm_model.YounggeeSketchInfo)
	for _, SketchInfo := range SketchInfos {
		SketchMap[SketchInfo.TaskID] = SketchInfo
	}
	// 查询总数
	var totalSketch int64
	if err := db1.Count(&totalSketch).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 TaskSketches []*http_model.SpecialTaskSketch
	var taskSketches []*http_model.SpecialTaskSketchInfo
	var newTaskSketches []*http_model.SpecialTaskSketchInfo
	for _, taskId := range taskIds {
		TaskSketch := new(http_model.SpecialTaskSketch)
		TaskSketch.Talent = taskMap[taskId]
		TaskSketch.Sketch = SketchMap[taskId]
		TaskSketches = append(TaskSketches, TaskSketch)
	}

	taskSketches = pack.SpecialTaskSketchToTaskInfo(TaskSketches)

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

// FindSketchInfoByTaskId 根据种草子任务ID查找初稿信息
func FindSketchInfoByTaskId(ctx context.Context, TaskID string) ([]*gorm_model.YounggeeSketchInfo, error) {
	db := GetReadDB(ctx)
	var sketchInfo []*gorm_model.YounggeeSketchInfo
	err := db.Model(gorm_model.YounggeeSketchInfo{}).Where("task_id = ?", TaskID).Find(&sketchInfo).Error
	if err != nil {
		return nil, err
	}
	return sketchInfo, nil
}
