package db

import (
	"context"
	"github.com/issue9/conv"
	"time"
	"youngee_b_api/model/gorm_model"

	log "github.com/sirupsen/logrus"
)

func AutoUpdateStatus() error {
	db := GetReadDB(context.Background())
	// 查找所有到达招募截止时间的项目id
	var projectIds []string
	db = db.Debug().Model(gorm_model.ProjectInfo{}).Select("project_id").Where("project_status = 6").Find(&projectIds)
	//fmt.Println("projectIds",projectIds)
	if len(projectIds) != 0 {
		for _, projectId := range projectIds {
			db1 := GetReadDB(context.Background())
			db1 = db1.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? and task_status = 1", projectId).Update("task_status", 3)
		}
	}
	db1 := GetReadDB(context.Background())
	// 更新招募中项目状态为待支付
	err := db1.Debug().Model(gorm_model.ProjectInfo{}).
		Where("project_status = ? AND recruit_ddl < ?", 4, time.Now()).Update("project_status", 6).Error
	if err != nil {
		log.Println("DB AutoUpdateStatus error :", err)
		return err
	}
	return nil
}

func GetLastAutoTaskID() (int, error) {
	db := GetReadDB(context.Background())
	// 查找最后一个
	LastTask := gorm_model.InfoAutoTask{}
	result := db.Last(&LastTask)
	err := result.Error
	if err != nil {
		log.Println("DB GetLastAutoTaskID:", err)
		return 0, err
	}
	//fmt.Printf("auto task %+v %+v", result, LastTask)
	return LastTask.AutoTaskID, nil
}

func AutoUpdateApplyTimes() error {
	db := GetReadDB(context.Background())
	// 查询task表信息
	db = db.Debug().Model(gorm_model.YoungeeTalentInfo{})
	err := db.Where("1 = 1").Update("apply_num", 5).Error
	if err != nil {
		log.Println("DB AutoUpdateStatus error :", err)
		return err
	}
	return nil
}

func AutoCompleteSelection() error {
	db := GetReadDB(context.Background())
	// 查询selection表，查询所有到截至时间的选品项目
	var completedSelectionList []gorm_model.YounggeeSelectionInfo
	err := db.Model(gorm_model.YounggeeSelectionInfo{}).Where("task_ddl < ?", time.Now()).Scan(&completedSelectionList).Error
	if err != nil {
		log.Println("DB AutoCompleteSelection error :", err)
		return err
	}
	// 遍历结束选品列表
	for _, v := range completedSelectionList {
		if v.SelectionStatus == 6 { // 若处于执行中阶段
			// 查询该选品下所有待结算任务
			var settleSecTaskList []gorm_model.YounggeeSecTaskInfo
			err = db.Model(gorm_model.YounggeeSecTaskInfo{}).Where("selection_id = ? and task_stage = 9", v.SelectionID).Scan(&settleSecTaskList).Error
			if err != nil {
				log.Println("DB AutoCompleteSelection error :", err)
				return err
			}
			// 结算选品
			for _, w := range settleSecTaskList {
				// 更新任务信息
				updateSecTaskData := gorm_model.YounggeeSecTaskInfo{
					TaskID:           w.TaskID,
					TaskStage:        10,
					AssignmentStatus: 5,
					IsPayReward:      0,
					IsPayPayment:     0,
					CompleteDate:     time.Now(),
				}
				_, err = UpdateSecTask(context.Background(), updateSecTaskData)
				if err != nil {
					log.Println("DB AutoCompleteSelection error :", err)
					return err
				}

				// 添加任务日志和达人消息
				err = CreateTaskLog(context.Background(), w.TaskID, "结算时间")
				if err != nil {
					log.Println("DB AutoCompleteSelection error :", err)
				}

				err = CreateMessageBySecTaskId(context.Background(), 5, 1, w.TaskID)
				if err != nil {
					log.Println("DB AutoCompleteSelection error :", err)
					return err
				}
			}

			// 计算结算金额，并返还剩余冻结资金
			var leftMoney float64 = conv.MustFloat64(v.EstimatedCost, 0) - conv.MustFloat64(v.SettlementAmount, 0)
			_, err = UpdateEnterpriseBalance(context.Background(), v.EnterpriseID, 0, leftMoney, -leftMoney)
			if err != nil {
				log.Println("DB AutoCompleteSelection error :", err)
				return err
			}

			// 更新选品阶段为已结案
			updateSelectionInfo := gorm_model.YounggeeSelectionInfo{
				SelectionID:     v.SelectionID,
				SelectionStatus: 8,
				FinishAt:        time.Now(),
			}
			err = UpdateSelection(context.Background(), updateSelectionInfo)
			if err != nil {
				log.Println("DB AutoCompleteSelection error :", err)
				return err
			}
		} else { // 否则
			// 更新选品阶段为失效，失效原因为逾期未支付
			updateSelectionInfo := gorm_model.YounggeeSelectionInfo{
				SelectionID:     v.SelectionID,
				SelectionStatus: 7,
				FailReason:      1,
				FinishAt:        time.Now(),
			}
			err = UpdateSelection(context.Background(), updateSelectionInfo)
			if err != nil {
				log.Println("DB AutoCompleteSelection error :", err)
				return err
			}
		}
	}

	return nil
}
