package db

import (
	"context"
	"encoding/json"
	"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"
	"github.com/tidwall/gjson"
	"gorm.io/gorm"
)

func GetTaskList(ctx context.Context, projectID string) ([]gorm_model.YoungeeTaskInfo, error) {
	db := GetReadDB(ctx)
	tasks := []gorm_model.YoungeeTaskInfo{}

	err := db.Where("project_id=? and task_status = 2", projectID).Find(&tasks).Error
	if err != nil {
		return nil, err
	}
	return tasks, nil
}

func UpdateLogisticsStatus(ctx context.Context, taskID string, status int64) error {

	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskID).Update("logistics_status", status).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[task db] call UpdateLogisticsStatus error,err:%+v", err)
		return err
	}
	return nil
}

func UpdateLogisticsDate(ctx context.Context, taskID string) error {

	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskID).Update("delivery_date", time.Now()).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[task db] call UpdateLogisticsDate error,err:%+v", err)
		return err
	}
	return nil
}

func GetProjectIdByTaskId(ctx context.Context, taskID string) (*string, error) {
	db := GetReadDB(ctx)
	task := &gorm_model.YoungeeTaskInfo{}
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskID).Scan(task).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[task db] call UpdateLogisticsStatus error,err:%+v", err)
		return nil, err
	}
	return &task.ProjectID, nil
}

func ChangeTaskStatus(ctx context.Context, taskIds []string, supplierStatus int) ([]int64, error) {
	db := GetReadDB(ctx)
	// taskSta, err := strconv.Atoi(taskStatus)
	taskSta := supplierStatus

	if err := db.Debug().Model(&gorm_model.YoungeeTaskInfo{}).Where("task_id IN ?", taskIds).
		Updates(gorm_model.YoungeeTaskInfo{SupplierStatus: taskSta}).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[ChangeTaskStatus]2 error query mysql total, err:%+v", err)
		return nil, err
	}

	var taskInfos []gorm_model.YoungeeTaskInfo
	err := db.Debug().Model(&gorm_model.YoungeeTaskInfo{}).Where("task_id IN ?", taskIds).Find(&taskInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[ChangeTaskStatus]3 error query mysql total, err:%+v", err)
		return nil, err
	}

	var recruitStrategysIDs []int64
	recruitStrategys := gorm_model.RecruitStrategy{}
	for _, taskInfo := range taskInfos {
		err2 := db.Debug().Model(gorm_model.RecruitStrategy{}).Where("s_project_id=? AND strategy_id=?", taskInfo.SProjectId, taskInfo.StrategyID).Scan(&recruitStrategys).Error
		if err2 != nil {
			logrus.WithContext(ctx).Errorf("[ChangeTaskStatus]4 error query mysql total, err:%+v", err2)
			return nil, err2
		}
		recruitStrategysIDs = append(recruitStrategysIDs, recruitStrategys.RecruitStrategyID)
	}
	return recruitStrategysIDs, nil
}

func ChangeSpecialTaskStatus(ctx context.Context, taskIds []string, supplierStatus int) error {
	db := GetReadDB(ctx)
	if err := db.Debug().Model(&gorm_model.YoungeeTaskInfo{}).Where("task_id IN ?", taskIds).
		Updates(gorm_model.YoungeeTaskInfo{SupplierStatus: supplierStatus}).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[ChangeTaskStatus]2 error query mysql total, err:%+v", err)
		return err
	}
	return nil
}

func UpdateTaskSelectAtByProjectId(ctx context.Context, projectID string, taskStatus int64) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id=? and task_status = ?", projectID, taskStatus).Update("select_date", time.Now()).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[UpdateTaskStage]2 error query mysql total, err:%+v", err)
		return err
	}
	return nil
}

func UpdateTaskStageByProjectId(ctx context.Context, projectID string, taskStatus int64, taskStage int64) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id=? and task_status = ?", projectID, taskStatus).Update("task_stage", taskStage).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[UpdateTaskStage]2 error query mysql total, err:%+v", err)
		return err
	}
	return nil
}
func UpdateTaskStageByTaskId(ctx context.Context, taskID string, taskStatus int64, taskStage int64) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id=? and task_status = ?", taskID, taskStatus).Update("task_stage", taskStage).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[UpdateTaskStageByTaskId]2 error query mysql total, err:%+v", err)
		return err
	}
	return nil
}

func GetUnfinishedTaskNumber(ctx context.Context, projectID string) (*int64, error) {
	var unFinishedTaskNumber int64
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? and task_status = 2 and task_stage < 15", projectID).Count(&unFinishedTaskNumber).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Data db] Find YounggeeTaskInfo error,err:%+v", err)
		return nil, err
	}
	return &unFinishedTaskNumber, nil
}

// SetTaskFinish 任务结案
func SetTaskFinish(ctx context.Context, TaskIDs []string) error {
	db := GetReadDB(ctx)
	// 1. 修改任务表，更新任务阶段为已结案，结案方式为正常结束，数据状态为已通过，
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeTaskInfo{DataStatus: 5, TaskStage: 15, CompleteStatus: 2, WithdrawStatus: 2, CompleteDate: time.Now()}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Task db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}

	for _, v := range TaskIDs {
		// 查询task_info
		db = GetReadDB(ctx)
		taskInfo := gorm_model.YoungeeTaskInfo{}
		err1 := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", v).Scan(&taskInfo).Error
		if err1 != nil {
			logrus.WithContext(ctx).Errorf("[Task db] Find YoungeeTaskInfo error,err:%+v", err)
			return err1
		}
		//查询project_info
		projectInfo := gorm_model.ProjectInfo{}
		err1 = db.Model(gorm_model.ProjectInfo{}).Where("project_id = ?", taskInfo.ProjectID).Scan(&projectInfo).Error
		if err1 != nil {
			logrus.WithContext(ctx).Errorf("[Task db] Find ProjectInfo error,err:%+v", err)
			return err1
		}
		// 查询data_info
		db = GetReadDB(ctx)
		dataInfo := gorm_model.YounggeeDataInfo{}
		err1 = db.Model(gorm_model.YounggeeDataInfo{}).Where("task_id = ? and is_ok = 1", v).Scan(&dataInfo).Error
		if err1 != nil {
			logrus.WithContext(ctx).Errorf("[Task db] Find YounggeeDataInfo error,err:%+v", err)
			return err1
		}

		// 2. 创建任务收益
		var productStruct gorm_model.YounggeeProduct
		if err = json.Unmarshal([]byte(projectInfo.ProductSnap), &productStruct); err != nil {
			fmt.Println("Error:", err)
			return err
		}
		var productPhotoStruct []gorm_model.YounggeeProductPhoto
		if err = json.Unmarshal([]byte(projectInfo.ProductPhotoSnap), &productPhotoStruct); err != nil {
			fmt.Println("Error:", err)
			return err
		}
		var mainPhoto = ""
		for _, w := range productPhotoStruct {
			if w.Symbol == 1 {
				mainPhoto = w.PhotoUrl
			}
		}

		t := time.Now()
		income := gorm_model.YounggeeTalentIncome{
			TalentID:       taskInfo.TalentID,
			ProjectID:      taskInfo.ProjectID,
			TaskID:         taskInfo.TaskID,
			Type:           1,
			BrandName:      productStruct.BrandName,
			TaskName:       projectInfo.ProjectName,
			PhotoUrl:       mainPhoto,
			Income:         strconv.FormatFloat(taskInfo.SettleAmount, 'f', 10, 32),
			IncomeType:     1,
			WithdrawStatus: 1,
			IncomeAt:       &t,
			WithdrawAt:     nil,
		}
		err = CreateIncome(ctx, income, nil)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
			return err
		}

		// 3. 修改招募策略表，更新粉丝量、播放量、点赞数、收藏数、评论数、总支付、结案数量
		// 更新招募策略
		db = GetReadDB(ctx)
		db = db.Model(gorm_model.RecruitStrategy{}).Where("project_id = ? and strategy_id = ?", taskInfo.ProjectID, taskInfo.StrategyID)
		fansCount, _ := strconv.Atoi(conv.MustString(gjson.Get(taskInfo.TalentPlatformInfoSnap, "fans_count")))
		err = db.Updates(map[string]interface{}{
			"fan_number":     gorm.Expr("fan_number + ?", fansCount),
			"play_number":    gorm.Expr("play_number + ?", dataInfo.PlayNumber),
			"like_number":    gorm.Expr("like_number + ?", dataInfo.LikeNumber),
			"collect_number": gorm.Expr("collect_number + ?", dataInfo.CollectNumber),
			"comment_number": gorm.Expr("comment_number + ?", dataInfo.CommentNumber),
			"finish_number":  gorm.Expr("finish_number + 1"),
			"total_offer":    gorm.Expr("total_offer + ?", taskInfo.RealPayment)}).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[Task db] Update YounggeeDataInfo error,err:%+v", err)
			return err
		}
	}
	return nil
}

// SetTaskFinish 专项任务结案
func SetSpecialTaskFinish(ctx context.Context, TaskIDs []string) error {
	db := GetReadDB(ctx)
	// 1. 修改任务表，更新任务阶段为已结案，结案方式为正常结束，数据状态为已通过，
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id in ?", TaskIDs).Updates(gorm_model.YoungeeTaskInfo{DataStatus: 5, TaskStage: 15, CompleteStatus: 2, WithdrawStatus: 2, CompleteDate: time.Now()}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Task db] Update YoungeeTaskInfo error,err:%+v", err)
		return err
	}
	return nil
}

func GetSpecialTaskInviteList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) ([]*http_model.SpecialTaskInviteInfo, int64, error) {
	db := GetReadDB(ctx)
	// 查询task表信息
	db = db.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("task_stage != 3")
	// 根据Project条件过滤
	conditionType := reflect.TypeOf(conditions).Elem()
	conditionValue := reflect.ValueOf(conditions).Elem()
	var platformNickname string = ""
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)
		if tag == "task_status" {
			fmt.Printf("link %+v", value.Interface() == int64(0))
			if value.Interface() == int64(0) {
				db = db.Where("task_status <> 2")
			} else {
				db = db.Where("task_status = 2")
			}
			continue
		} else if !util.IsBlank(value) {
			if tag == "platform_nickname" {
				platformNickname = 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)

	talentInfoTophoneMap := make(map[string]string)
	for _, taskInfo := range taskInfos {
		if _, ok := talentInfoTophoneMap[taskInfo.TalentID]; !ok {
			phone := GetPhoneFromTalentId(ctx, taskInfo.TalentID)
			talentInfoTophoneMap[taskInfo.TalentID] = phone
		}
	}

	//// 查询该页数据
	//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 taskDatas []*http_model.SpecialTaskInviteInfo
	var newTaskDatas []*http_model.SpecialTaskInviteInfo

	taskDatas = pack.YoungeeTaskInfoToSpecialTaskInviteInfo(taskInfos)

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

func GetPhoneFromTalentId(ctx context.Context, talentId string) string {
	db := GetReadDB(ctx)
	var Phone string
	db.Model(&gorm_model.YoungeeTalentInfo{}).Select("talent_phone_number").Where("id = ?", talentId).Find(&Phone)
	return Phone
}

func SetTalentIncome(ctx context.Context, TaskIDs []string) error {
	db := GetReadDB(ctx)
	var TaskInfoList []gorm_model.YoungeeTaskInfo
	fmt.Println("收入", TaskIDs)
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id in ?", TaskIDs).Scan(&TaskInfoList).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Task db] Update SetTalentIncome error,err:%+v", err)
		return err
	}
	for _, taskInfo := range TaskInfoList {
		err := db.Model(gorm_model.YoungeeTalentInfo{}).Where("id = ?", taskInfo.TalentID).Updates(map[string]interface{}{
			"income":      gorm.Expr("income + ?", taskInfo.SettleAmount),
			"canwithdraw": gorm.Expr("canwithdraw + ?", taskInfo.SettleAmount)}).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[Task db] Update SetTalentIncome error,err:%+v", err)
			return err
		}
	}
	return nil
}

// 获取任务ids
func GetTaskIds(ctx context.Context, projectId string) ([]string, error) {
	db := GetReadDB(ctx)
	var taskIds []string
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Select("task_id").Where("project_id = ? and task_status = 2", projectId).Find(&taskIds).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[CreateMessageByTask] error read mysql, err:%+v", err)
		return nil, err
	}

	return taskIds, nil
}

func UpdateTask(ctx context.Context, updateData gorm_model.YoungeeTaskInfo, tx *gorm.DB) (bool, error) {
	db := GetWriteDB(ctx)
	whereCondition := gorm_model.YoungeeTaskInfo{
		TaskID: updateData.TaskID,
	}
	if tx != nil {
		err := tx.Where(whereCondition).Updates(&updateData).Error
		if err != nil {
			return false, err
		}
	} else {
		err := db.Where(whereCondition).Updates(&updateData).Error
		if err != nil {
			return false, err
		}
	}
	return true, nil
}

// CountTaskNumByStrategyId 根据招募策略查找对应的种草子任务数量
func CountTaskNumByStrategyId(ctx context.Context, projectId string, strategyId int64) (int64, error) {
	db := GetReadDB(ctx)
	var taskNum int64
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? and strategy_id = ?", projectId, strategyId).Count(&taskNum).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[CreateMessageByTask] error read mysql, err:%+v", err)
		return 0, err
	}
	return taskNum, nil
}

// GetTaskByTaskId 根据task_id查询子任务详细信息
func GetTaskByTaskId(ctx context.Context, taskId string) (*gorm_model.YoungeeTaskInfo, error) {
	db := GetReadDB(ctx)
	var taskInfo *gorm_model.YoungeeTaskInfo
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskId).Find(&taskInfo).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[CreateMessageByTask] error read mysql, err:%+v", err)
		return nil, err
	}
	return taskInfo, nil
}
