package db

import (
	"context"
	"errors"
	"fmt"
	"github.com/issue9/conv"
	"github.com/sirupsen/logrus"
	"github.com/tidwall/gjson"
	"gorm.io/gorm"
	"strings"
	"time"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
	"youngee_b_api/pack"
)

func GetSecTaskById(ctx context.Context, secTaskId string) (*gorm_model.YounggeeSecTaskInfo, error) {
	db := GetWriteDB(ctx)
	secTaskInfo := gorm_model.YounggeeSecTaskInfo{}
	whereCondition := gorm_model.YounggeeSecTaskInfo{TaskID: secTaskId}
	result := db.Where(&whereCondition).First(&secTaskInfo)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil
		} else {
			return nil, result.Error
		}
	}
	return &secTaskInfo, nil
}

func GetSecTaskList(ctx context.Context, selectionId string, taskStatus int, searchValue string, pageSize, pageNum int64) ([]*http_model.SecTaskInfo, int64, error) {
	db := GetReadDB(ctx)
	// var taskStages []int
	var freeStages []int
	var rewardStages []int
	switch taskStatus {
	case 3:
		// 待选
		freeStages = []int{1}
		break
	case 4:
		// 申请成功
		freeStages = []int{3, 4, 5}
		break
	case 6:
		// 待发货
		freeStages = []int{3}
		break
	case 7:
		// 已发货
		freeStages = []int{4}
		break
	case 8:
		// 已收货
		freeStages = []int{5}
	case 9:
		// 待领悬赏
		rewardStages = []int{1}
		break
	case 10:
		// 已领悬赏
		rewardStages = []int{2}
		break
	case 11:
		// 返回全部 使用场景-绑定免费领样策略
		freeStages = []int{0, 1, 2, 3, 4, 5}
		rewardStages = []int{0, 1}
	}
	fmt.Println("task_stages: ", freeStages, rewardStages)
	if len(freeStages) == 0 {
		// 根据悬赏阶段筛选
		db = db.Model(gorm_model.YounggeeSecTaskInfo{}).Where("selection_id = ? and reward_stage in ?", selectionId, rewardStages)
	} else {
		// 根据免费领样阶段筛选
		db = db.Model(gorm_model.YounggeeSecTaskInfo{}).Where("selection_id = ? and free_stage in ?", selectionId, freeStages)
	}
	// 查询总数
	var total int64
	var secTaskInfoList []*gorm_model.YounggeeSecTaskInfo
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetSelectionList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	// 查询该页数据
	limit := pageSize
	offset := pageSize * (pageNum - 1) // assert pageNum start with 0
	err := db.Order("create_date desc").Limit(int(limit)).Offset(int(offset)).Find(&secTaskInfoList).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetSelectionList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	fmt.Printf("secTaskInfoList：%+v", secTaskInfoList)
	newSecTaskInfoList := pack.GormSecTaskListToHttpSecTaskList(secTaskInfoList)
	fmt.Printf("newSecTaskInfoList：%+v", newSecTaskInfoList)

	//for i, secTask := range newSecTaskInfoList {
	//	if secTask.RegionCode != 0 {
	//		newSecTaskInfoList[i].DetailAddr = GetRegion(ctx, secTask.RegionCode) + newSecTaskInfoList[i].DetailAddr
	//	}
	//}
	var resSecTaskInfoList []*http_model.SecTaskInfo
	if searchValue != "" {
		for _, v := range newSecTaskInfoList {
			if strings.Contains(v.SecTaskId, searchValue) {
				resSecTaskInfoList = append(resSecTaskInfoList, v)
			} else if strings.Contains(v.PlatformNickname, searchValue) {
				resSecTaskInfoList = append(resSecTaskInfoList, v)
			} else {
				total--
			}
		}
	} else {
		resSecTaskInfoList = newSecTaskInfoList
	}
	fmt.Println("resSecTaskInfoList: ", &resSecTaskInfoList)
	return resSecTaskInfoList, total, nil
}

func PassSecTaskCoop(ctx context.Context, selectionId string, taskIds []string) (bool, error) {
	db := GetWriteDB(ctx)
	// 1. 校验
	var count int64
	fmt.Println("task_ids: ", taskIds)
	err := db.Model(gorm_model.YounggeeSecTaskInfo{}).Where("task_id IN ? AND free_stage = 1", taskIds).Count(&count).Error

	fmt.Println("count: ", count)
	if err != nil {
		return false, err
	}
	if int64(len(taskIds)) == 0 || count != int64(len(taskIds)) {
		return false, errors.New("任务id有误")
	}

	// 2. 查询任务对应达人id（用于生成达人消息）
	var talentIds []string
	err = db.Model(gorm_model.YounggeeSecTaskInfo{}).Where("task_id IN ?", taskIds).Select("talent_id").Find(&talentIds).Error
	if err != nil {
		return false, err
	}
	// 3. 查询任务对应选品名称（用于生成达人消息）
	var selection gorm_model.YounggeeSelectionInfo
	err = db.Model(gorm_model.YounggeeSelectionInfo{}).Where("selection_id = ?", selectionId).Find(&selection).Error
	if err != nil {
		return false, err
	}
	if int64(selection.RemainNum) < count {
		if int64(len(taskIds)) == 0 || count != int64(len(taskIds)) {
			return true, errors.New("剩余选品数量不足")
		}
	}

	err = db.Transaction(func(tx *gorm.DB) error {
		// 2. 修改任务状态和任务阶段
		// 若选品不提供样品，则直接跳转执行阶段，否则进入发货阶段
		if selection.SampleMode == 3 {
			updateData := gorm_model.YounggeeSecTaskInfo{
				TaskStatus:       2,
				TaskStage:        8,
				SelectDate:       time.Now(),
				LogisticsStatus:  3,
				AssignmentStatus: 1,
			}
			err = tx.Model(gorm_model.YounggeeSecTaskInfo{}).Where("task_id IN ? AND task_stage = 3", taskIds).Updates(updateData).Error
			if err != nil {
				return err
			}
		} else {
			// 免费领样
			updateData := gorm_model.YounggeeSecTaskInfo{
				TaskStatus:      2,
				TaskStage:       6,
				SelectDate:      time.Now(),
				LogisticsStatus: 1,
				FreeStage:       3,
			}
			err = tx.Model(gorm_model.YounggeeSecTaskInfo{}).Where("task_id IN ? AND free_stage = 1", taskIds).Updates(updateData).Error
			if err != nil {
				return err
			}
		}
		// 3. 更新选品剩余数量
		err = tx.Model(gorm_model.YounggeeSelectionInfo{}).Where("selection_id = ?", selectionId).Updates(
			map[string]interface{}{"remain_num": gorm.Expr("remain_num - ?", 1)}).Error
		if err != nil {
			return err
		}

		// 4. 生成达人消息
		for _, talendId := range talentIds {
			err = CreateMessage(ctx, 1, 1, talendId, selection.SelectionName)
			if err != nil {
				return err
			}
		}
		// 返回 nil 提交事务
		return nil
	})
	if err != nil {
		return false, err
	}
	return true, nil
}

func RefuseSecTaskCoop(ctx context.Context, taskIds []string) (bool, error) {
	db := GetWriteDB(ctx)
	// 1. 校验
	var count int64
	err := db.Model(gorm_model.YounggeeSecTaskInfo{}).Where("task_id IN ? AND free_stage = 1", taskIds).Count(&count).Error
	if err != nil {
		return false, err
	}
	if count != int64(len(taskIds)) {
		return false, errors.New("任务id有误")
	}

	// 查询任务对应达人id
	var talentIds []string
	err = db.Model(gorm_model.YounggeeSecTaskInfo{}).Where("task_id IN ?", taskIds).Select("talent_id").Find(&talentIds).Error
	if err != nil {
		return false, err
	}

	err = db.Transaction(func(tx *gorm.DB) error {
		// 2. 修改任务状态和任务阶段
		updateData := gorm_model.YounggeeSecTaskInfo{
			TaskStatus:     3,
			TaskStage:      5,
			CompleteDate:   time.Now(),
			CompleteStatus: 3,
			FreeStage:      2,
		}
		err = tx.Model(gorm_model.YounggeeSecTaskInfo{}).Where("task_id IN ? AND free_stage = 1", taskIds).Updates(updateData).Error
		if err != nil {
			return err
		}

		// 返回 nil 提交事务
		return nil
	})
	if err != nil {
		return false, err
	}
	return true, nil
}

func UpdateSecTask(ctx context.Context, updateData gorm_model.YounggeeSecTaskInfo) (bool, error) {
	db := GetWriteDB(ctx)
	whereCondition := gorm_model.YounggeeSecTaskInfo{
		TaskID: updateData.TaskID,
	}
	err := db.Where(whereCondition).Updates(&updateData).Error
	if err != nil {
		return false, err
	}
	return true, nil
}

func GetSecTaskSettleList(ctx context.Context, secTaskList []*http_model.SecTaskInfo, selectionId string, taskStatus int) ([]*http_model.SecTaskInfo, error) {
	db := GetWriteDB(ctx)
	whereCondition := gorm_model.YounggeeSelectionInfo{
		SelectionID: selectionId,
	}
	selectionInfo := gorm_model.YounggeeSelectionInfo{}
	err := db.Model(gorm_model.YounggeeSelectionInfo{}).Where(whereCondition).Scan(&selectionInfo).Error
	if err != nil {
		return nil, err
	}

	// 获取返现金额、悬赏金额
	fmt.Println("selectionInfo.ProductSnap: ", selectionInfo.ProductSnap)
	price := conv.MustString(gjson.Get(selectionInfo.ProductSnap, "ProductPrice"), "")
	for i, _ := range secTaskList {
		secTaskList[i].TaskReward = selectionInfo.TaskReward
		secTaskList[i].ReturnMoney = price
	}

	// 获取作业信息
	var taskIds []string
	taskMap := make(map[string]*http_model.SecTaskInfo)
	for _, secTask := range secTaskList {
		taskIds = append(taskIds, secTask.SecTaskId)
		taskMap[secTask.SecTaskId] = secTask
	}

	var assignmentInfos []gorm_model.YounggeeAssignmentInfo
	err = db.Model(gorm_model.YounggeeAssignmentInfo{}).Where("task_id IN ?", taskIds).Find(&assignmentInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, err
	}
	assignmentMap := make(map[string]gorm_model.YounggeeAssignmentInfo)
	for _, assignmentInfo := range assignmentInfos {
		assignmentMap[assignmentInfo.TaskID] = assignmentInfo
	}
	// 融合信息
	for i, secTask := range secTaskList {
		taskID := secTask.SecTaskId
		secTaskList[i].AssignmentLink = assignmentMap[taskID].LinkUrl
		secTaskList[i].DataScreenshot = assignmentMap[taskID].PhotoUrl
		secTaskList[i].CreateDate = conv.MustString(assignmentMap[taskID].CreateAt, "")
	}

	return secTaskList, nil
}
