package service

import (
	"context"
	"encoding/json"
	"fmt"
	"math/rand"
	"strconv"
	"strings"
	"time"
	"youngee_b_api/db"
	"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/gin-gonic/gin"

	"github.com/issue9/conv"
	"github.com/sirupsen/logrus"
)

var Project *project

type project struct {
}

func (*project) Create(ctx context.Context, newProject http_model.CreateProjectRequest, enterpriseID string) (*http_model.CreateProjectData, error) {
	// build gorm_model.ProjectInfo
	// 查询关联商品信息
	product, err := db.GetProductByID(ctx, newProject.ProductID)
	if err != nil {
		return nil, err
	}
	productPhotos, err := db.GetProductPhotoByProductID(ctx, newProject.ProductID)
	productInfoToJson, _ := json.Marshal(product)
	productPhotosToJson, _ := json.Marshal(productPhotos)
	//fmt.Println("productPhotosToJson:", productPhotosToJson)
	AutoTaskID, err := db.GetLastAutoTaskID()
	if err != nil {
		return nil, err
	}

	AutoDefaultID, err := db.GetLastAutoDefaultID()
	if err != nil {
		return nil, err
	}
	// 按照品牌名-商品名对项目进行命名
	projectName := product.BrandName + "-" + product.ProductName
	//feeForm := fmt.Sprintf("[")
	feeFrom := []string{}
	for _, strategy := range newProject.RecruitStrategys {
		feeFrom = append(feeFrom, strconv.FormatInt(strategy.FeeForm, 10))
	}
	var ECost float64 = 0
	if newProject.ProjectType == int64(1) {
		for _, strategy := range newProject.RecruitStrategys {
			// 计算预估成本
			var tmpCost float64 = 0
			if strategy.FeeForm == 1 {
				tmpCost = strategy.ServiceCharge * float64(strategy.RecruitNumber)
			} else if strategy.FeeForm == 2 {
				tmpCost = strategy.Offer * float64(strategy.RecruitNumber)
			}
			ECost += tmpCost
		}
	}
	feeFroms := strings.Join(feeFrom, ",")
	//fmt.Printf("创建项目new %+v", newProject)
	RecruitDdl := time.Time{} //赋零值
	if newProject.RecruitDdl != "" {
		RecruitDdl, _ = time.ParseInLocation("2006-01-02 15:04:05", newProject.RecruitDdl, time.Local)
	}
	fmt.Println("Create RecruitDdl：", newProject.RecruitDdl, RecruitDdl)
	projectInfo := gorm_model.ProjectInfo{}
	rand.Seed(time.Now().UnixNano())
	td := conv.MustString(time.Now().Day())
	for {
		if len(td) == 3 {
			break
		}
		td = "0" + td
	}
	if newProject.ProjectType == int64(1) {
		// 没有填写DDL
		if newProject.RecruitDdl == "" {
			projectInfo = gorm_model.ProjectInfo{
				ProjectID:        conv.MustString(time.Now().Year())[2:] + td + conv.MustString(rand.Intn(100000-10000)+10000),
				ProjectName:      projectName,
				ProjectStatus:    1,
				ProjectType:      newProject.ProjectType,
				TalentType:       newProject.TalentType,
				ProjectPlatform:  newProject.ProjectPlatform,
				ProjectForm:      newProject.ProjectForm,
				ProjectDetail:    newProject.ProjectDetail,
				ContentType:      newProject.ContentType,
				EnterpriseID:     enterpriseID,
				ProductID:        newProject.ProductID,
				FeeForm:          feeFroms,
				AutoTaskID:       conv.MustInt64(AutoTaskID),
				AutoDefaultID:    conv.MustInt64(AutoDefaultID),
				EstimatedCost:    ECost,
				IsRead:           0,
				ProductSnap:      string(productInfoToJson),
				ProductPhotoSnap: string(productPhotosToJson),
			}
		} else {
			projectInfo = gorm_model.ProjectInfo{
				ProjectID:        conv.MustString(time.Now().Year())[2:] + td + conv.MustString(rand.Intn(100000-10000)+10000),
				ProjectName:      projectName,
				ProjectStatus:    1,
				ProjectType:      newProject.ProjectType,
				TalentType:       newProject.TalentType,
				ProjectPlatform:  newProject.ProjectPlatform,
				ProjectForm:      newProject.ProjectForm,
				RecruitDdl:       &RecruitDdl,
				ProjectDetail:    newProject.ProjectDetail,
				ContentType:      newProject.ContentType,
				EnterpriseID:     enterpriseID,
				ProductID:        newProject.ProductID,
				FeeForm:          feeFroms,
				AutoTaskID:       conv.MustInt64(AutoTaskID),
				AutoDefaultID:    conv.MustInt64(AutoDefaultID),
				EstimatedCost:    ECost,
				IsRead:           0,
				ProductSnap:      string(productInfoToJson),
				ProductPhotoSnap: string(productPhotosToJson),
			}
		}
	} else {
		projectInfo = gorm_model.ProjectInfo{
			ProjectID:       conv.MustString(time.Now().Year())[2:] + td + conv.MustString(rand.Intn(100000-10000)+10000),
			ProjectName:     projectName,
			ProjectStatus:   1,
			ProjectType:     newProject.ProjectType,
			TalentType:      "[]",
			ProjectPlatform: newProject.ProjectPlatform,
			ProjectForm:     newProject.ProjectForm,
			//RecruitDdl:       &RecruitDdl,
			ProjectDetail:    newProject.ProjectDetail,
			ContentType:      newProject.ContentType,
			EnterpriseID:     enterpriseID,
			ProductID:        newProject.ProductID,
			FeeForm:          feeFroms,
			AutoTaskID:       conv.MustInt64(AutoTaskID),
			AutoDefaultID:    conv.MustInt64(AutoDefaultID),
			EstimatedCost:    ECost,
			ProductSnap:      string(productInfoToJson),
			ProductPhotoSnap: string(productPhotosToJson),
		}
	}
	// db create ProjectInfo
	projectID, err := db.CreateProject(ctx, projectInfo)
	if err != nil {
		return nil, err
	}
	if len(newProject.ProjectPhotos) != 0 {
		// build []gorm_model.ProjectPhoto
		projectPhotos := []gorm_model.ProjectPhoto{}
		for _, photo := range newProject.ProjectPhotos {
			projectPhoto := gorm_model.ProjectPhoto{
				PhotoUrl:  photo.PhotoUrl,
				PhotoUid:  photo.PhotoUid,
				ProjectID: *projectID,
			}
			projectPhotos = append(projectPhotos, projectPhoto)
		}
		// db create ProjectPhoto
		err = db.CreateProjectPhoto(ctx, projectPhotos)
		if err != nil {
			return nil, err
		}
	}
	// build
	if newProject.ProjectType == int64(1) && newProject.RecruitStrategys != nil {
		recruitStrategys := []gorm_model.RecruitStrategy{}
		for _, strategy := range newProject.RecruitStrategys {
			// 查询对应定价策略
			pricingStrategy, err := db.GetPricingStrategy(ctx, strategy.FollowersLow, strategy.FollowersUp, strategy.FeeForm, newProject.ProjectPlatform)
			if err != nil {
				return nil, err
			}
			// 根据定价策略计算达人所见报价
			if strategy.FeeForm == 2 {
				strategy.TOffer = strategy.Offer * (1 - conv.MustFloat64(pricingStrategy.ServiceRate)/1000)
			}
			recruitStrategy := gorm_model.RecruitStrategy{
				FeeForm:       strategy.FeeForm,
				StrategyID:    strategy.StrategyID,
				FollowersLow:  strategy.FollowersLow,
				FollowersUp:   strategy.FollowersUp,
				RecruitNumber: strategy.RecruitNumber,
				ServiceCharge: strategy.ServiceCharge,
				Offer:         strategy.Offer,
				TOffer:        strategy.TOffer,
				ProjectID:     *projectID,
			}
			recruitStrategys = append(recruitStrategys, recruitStrategy)
		}
		err = db.CreateRecruitStrategy(ctx, recruitStrategys)
		if err != nil {
			return nil, err
		}
	}
	res := &http_model.CreateProjectData{
		ProjectID: *projectID,
	}
	//fmt.Printf("%+v", res)
	return res, nil
}
func (*project) Update(ctx context.Context, newProject http_model.UpdateProjectRequest, enterpriseID string) (*http_model.UpdateProjectData, error) {
	RecruitDdl := time.Time{} //赋零值
	if newProject.RecruitDdl != "" {
		RecruitDdl, _ = time.ParseInLocation("2006-01-02 15:04:05", newProject.RecruitDdl, time.Local)
	}
	fmt.Println("Update RecruitDdl：", newProject.RecruitDdl, RecruitDdl)
	oldProject, err3 := db.GetProjectDetail(ctx, newProject.ProjectID)
	if err3 != nil {
		return nil, err3
	}
	feeFrom := []string{}
	for _, strategy := range newProject.RecruitStrategys {
		//if strategy.StrategyID
		feeFrom = append(feeFrom, strconv.FormatInt(strategy.FeeForm, 10))
		//feeForm += string(strategy.StrategyID)
	}
	var ECost float64 = 0
	if newProject.ProjectType == int64(1) && newProject.RecruitStrategys != nil {
		for _, strategy := range newProject.RecruitStrategys {
			// 计算预估成本
			var tmpCost float64 = 0
			if strategy.FeeForm == 1 {
				tmpCost = strategy.ServiceCharge * float64(strategy.RecruitNumber)
			} else if strategy.FeeForm == 2 {
				tmpCost = strategy.Offer * float64(strategy.RecruitNumber)
			}
			ECost += tmpCost
		}
	}
	feeFroms := strings.Join(feeFrom, ",")
	t := time.Now()
	project := gorm_model.ProjectInfo{}
	if newProject.RecruitDdl == "" {
		project = gorm_model.ProjectInfo{
			ProjectID:     newProject.ProjectID,
			TalentType:    newProject.TalentType,
			ContentType:   conv.MustInt64(newProject.ContentType),
			ProjectDetail: newProject.ProjectDetail,
			ProjectForm:   conv.MustInt64(newProject.ProjectForm),
			EnterpriseID:  enterpriseID,
			ProjectStatus: conv.MustInt64(newProject.ProjectStatus),
			FeeForm:       feeFroms,
			EstimatedCost: ECost,
			SubmitAt:      &t,
		}
	} else {
		project = gorm_model.ProjectInfo{
			ProjectID:     newProject.ProjectID,
			RecruitDdl:    &RecruitDdl,
			TalentType:    newProject.TalentType,
			ContentType:   conv.MustInt64(newProject.ContentType),
			ProjectDetail: newProject.ProjectDetail,
			ProjectForm:   conv.MustInt64(newProject.ProjectForm),
			EnterpriseID:  enterpriseID,
			ProjectStatus: conv.MustInt64(newProject.ProjectStatus),
			FeeForm:       feeFroms,
			EstimatedCost: ECost,
			SubmitAt:      &t,
		}
	}
	projectID, err := db.UpdateProject(ctx, project)
	if err != nil {
		return nil, err
	}
	// 删除该项目之前的所有图片
	err = db.DeleteProjectPhotoByProjecttID(ctx, *projectID)
	if err != nil {
		return nil, err
	}
	//fmt.Printf("照片:\t %+v", newProject.ProjectPhotos)
	if len(newProject.ProjectPhotos) != 0 {
		// 新增图片
		projectPhotos := []gorm_model.ProjectPhoto{}
		for _, photo := range newProject.ProjectPhotos {
			projectPhoto := gorm_model.ProjectPhoto{
				ProjectID: project.ProjectID,
				PhotoUrl:  photo.PhotoUrl,
				PhotoUid:  photo.PhotoUid,
				FileName:  photo.FileName,
			}
			projectPhotos = append(projectPhotos, projectPhoto)
		}
		err = db.CreateProjectPhoto(ctx, projectPhotos)
		if err != nil {
			return nil, err
		}
	}
	// 删除该项目之前的所有策略
	err = db.DeleteRecruitStrategyByProjectID(ctx, *projectID)
	if err != nil {
		return nil, err
	}
	fmt.Printf("策略:\t %+v,%+v", newProject.RecruitStrategys, len(newProject.RecruitStrategys) == 0)
	if len(newProject.RecruitStrategys) != 0 && newProject.ProjectType == int64(1) {
		// 新增策略
		RecruitStrategys := []gorm_model.RecruitStrategy{}
		for _, Strategy := range newProject.RecruitStrategys {
			// 查询对应定价策略
			pricingStrategy, err := db.GetPricingStrategy(ctx, Strategy.FollowersLow, Strategy.FollowersUp, Strategy.FeeForm, oldProject.ProjectPlatform)
			if err != nil {
				return nil, err
			}
			// 根据定价策略计算达人所见报价
			if Strategy.FeeForm == 2 {
				Strategy.TOffer = Strategy.Offer * (1 - conv.MustFloat64(pricingStrategy.ServiceRate)/1000)
			}

			RecruitStrategy := gorm_model.RecruitStrategy{
				FeeForm:       conv.MustInt64(Strategy.FeeForm),
				StrategyID:    conv.MustInt64(Strategy.StrategyID),
				FollowersLow:  conv.MustInt64(Strategy.FollowersLow),
				FollowersUp:   conv.MustInt64(Strategy.FollowersUp),
				RecruitNumber: conv.MustInt64(Strategy.RecruitNumber),
				ServiceCharge: Strategy.ServiceCharge,
				Offer:         Strategy.Offer,
				TOffer:        Strategy.TOffer,
				ProjectID:     project.ProjectID,
			}
			//fmt.Printf("Offer:\t %+v", Strategy.Offer)
			RecruitStrategys = append(RecruitStrategys, RecruitStrategy)
		}
		err = db.CreateRecruitStrategy(ctx, RecruitStrategys)
		if err != nil {
			return nil, err
		}
	}
	res := &http_model.UpdateProjectData{
		ProjectID: *projectID,
	}
	return res, nil
}

func (*project) Delete(ctx context.Context, projectID string) (*http_model.DeleteProjectData, error) {
	// 删除该项目之前的所有图片
	err := db.DeleteProjectPhotoByProjecttID(ctx, projectID)
	if err != nil {
		return nil, err
	}
	// 删除该项目之前的所有策略
	err = db.DeleteRecruitStrategyByProjectID(ctx, projectID)
	if err != nil {
		return nil, err
	}
	//删除项目
	NewProjectID, err1 := db.DeleteProject(ctx, projectID)
	if err1 != nil {
		return nil, err1
	}
	res := &http_model.DeleteProjectData{
		ProjectID: *NewProjectID,
	}
	return res, nil
}

func (*project) GetFullProjectList(ctx context.Context, pageSize, pageNum int32, supplierId int, condition *common_model.ProjectCondition) (*http_model.FullProjectListData, error) {

	// 1. 查询种草任务基本信息
	fullProjects, total, err := db.GetFullProjectList(ctx, pageSize, pageNum, condition)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetFullProjectList error,err:%+v", err)
		return nil, err
	}
	fullProjectListData := new(http_model.FullProjectListData)
	fullProjectListData.FullProjectPreview = pack.MGormFullProjectToHttpFullProjectPreview(fullProjects)
	fullProjectListData.Total = conv.MustString(total)

	// 2. 查询种草任务补充信息：商品信息，招募策略
	for _, project := range fullProjectListData.FullProjectPreview {

		// 2.1. 商品信息
		productInfo, productErr := db.GetProductByID(ctx, project.ProductId)
		if productErr != nil {
			return nil, productErr
		}
		if productInfo != nil {
			project.ProductId = productInfo.ProductID
			project.ProductPrice = productInfo.ProductPrice
			project.ProductName = productInfo.ProductName
		}

		// 2.2. 商品图片信息
		productPhotoInfo, productPhotoErr := db.GetProductPhotoByProductID(ctx, project.ProductId)
		if productPhotoErr != nil {
			return nil, productPhotoErr
		}
		if productPhotoInfo != nil {
			for _, photo := range productPhotoInfo {
				fmt.Println(photo)
				if photo.Symbol == 1 {
					project.ProductPhotoSymbol = 1
					project.ProductPhotoUrl = photo.PhotoUrl
					project.ProductPhotoUid = photo.PhotoUid
				}
			}
		}

		// 2.3. 招募策略信息
		recruitStrategyInfo, recruitErr := db.GetRecruitStrategyByProjectId(ctx, project.ProjectId)
		if recruitErr != nil {
			return nil, recruitErr
		}
		if recruitStrategyInfo != nil {
			for _, strategy := range recruitStrategyInfo {
				var recruitStrategy *http_model.EasyRecruitStrategy
				recruitStrategy = &http_model.EasyRecruitStrategy{}
				recruitStrategy.StrategyId = strategy.StrategyID
				recruitStrategy.FeeForm = strategy.FeeForm
				recruitStrategy.RecruitNumber = strategy.RecruitNumber
				project.RecruitStrategy = append(project.RecruitStrategy, recruitStrategy)
			}
		}

		// 2.4. 判断是否加入商单
		sProjectCount, sProjectErr := db.FindSProjectByProjectIdAndSupplierId(ctx, project.ProjectId, supplierId)
		if sProjectErr != nil {
			return nil, sProjectErr
		}
		if sProjectCount > 0 {
			project.AddToListStatus = 1
		} else {
			project.AddToListStatus = 2
		}
	}
	return fullProjectListData, nil
}

func (*project) GetProjectDraftList(ctx context.Context, enterpriseID string, pageSize, pageNum int32, condition *common_model.ProjectCondition) (*http_model.ProjectDraftListData, error) {

	ProjectDrafts, total, err := db.GetProjectDraftList(ctx, enterpriseID, pageSize, pageNum, condition)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetProjectDraftList error,err:%+v", err)
		return nil, err
	}
	ProjectDraftListData := new(http_model.ProjectDraftListData)
	ProjectDraftListData.ProjectDraftPreview = pack.MGormProjectDraftToHttpProjectDraftPreview(ProjectDrafts)
	ProjectDraftListData.Total = conv.MustString(total)
	return ProjectDraftListData, nil
}

func (*project) GetProjectTaskList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TaskConditions) (*http_model.ProjectTaskListData, error) {

	// 1. 根据SProject和condition查询所有Task
	projectTasks, total, err := db.GetProjectTaskList(ctx, projectID, pageSize, pageNum, conditions)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetProjectTaskList error,err:%+v", err)
		return nil, err
	}
	projectTaskListData := new(http_model.ProjectTaskListData)
	projectTaskListData.ProjectTaskPreview = pack.MGormProjectTaskToHttpProjectTaskPreview(projectTasks)

	// 2. 查找SProject中其他信息
	sProjectInfo, sProjectErr := db.GetSProjectDetail(ctx, conditions.SProjectId)
	if sProjectErr != nil {
		return nil, sProjectErr
	}
	if sProjectInfo != nil {
		projectTaskListData.SettleNum = sProjectInfo.SettleNum
		projectTaskListData.RecruitNum = sProjectInfo.RecruitNum
		projectTaskListData.QuitNum = sProjectInfo.QuitNum
		projectTaskListData.ServiceChargeSettle = sProjectInfo.ServiceChargeSettle
		projectTaskListData.ServiceChargeActual = sProjectInfo.ServiceChargeActual
	}
	projectTaskListData.Total = conv.MustString(total)
	return projectTaskListData, nil
}

func (*project) GetPorjectDetail(ctx context.Context, projectID string) (*http_model.ShowProjectData, error) {
	project, err := db.GetProjectDetail(ctx, projectID)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetPorjectDetail error,err:%+v", err)
		return nil, err
	}
	enterprise, err := db.GetEnterpriseByEnterpriseID(ctx, project.EnterpriseID)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetEnterpriseByEnterpriseID error,err:%+v", err)
		return nil, err
	}
	user, err := db.GetUserByID(ctx, enterprise.UserID)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetUserByID error,err:%+v", err)
		return nil, err
	}
	ProjectDetail := http_model.ShowProjectData{
		ProjectID:        conv.MustString(project.ProjectID),
		ProjectName:      conv.MustString(project.ProjectName),
		ProjectStatus:    conv.MustString(project.ProjectStatus),
		ProjectType:      conv.MustString(project.ProjectType),
		ProjectPlatform:  conv.MustString(project.ProjectPlatform),
		ProjectForm:      conv.MustString(project.ProjectForm),
		TalentType:       conv.MustString(project.TalentType),
		RecruitDdl:       util.GetTimePoionter(project.RecruitDdl),
		ContentType:      conv.MustString(project.ContentType),
		ProjectDetail:    conv.MustString(project.ProjectDetail),
		ProductID:        conv.MustString(project.ProductID),
		EnterpriseID:     conv.MustString(project.EnterpriseID),
		Balance:          conv.MustString(enterprise.Balance),
		AvailableBalance: conv.MustString(enterprise.AvailableBalance),
		EstimatedCost:    conv.MustString(project.EstimatedCost),
		FailReason:       conv.MustString(project.FailReason),
		CreateAt:         util.GetTimePoionter(project.CreatedAt),
		UpdateAt:         util.GetTimePoionter(project.UpdatedAt),
		Phone:            user.Phone,
		FinishAt:         util.GetTimePoionter(project.FinishAt),
		PassAt:           util.GetTimePoionter(project.PassAt),
		SubmitAt:         util.GetTimePoionter(project.SubmitAt),
		PayAt:            util.GetTimePoionter(project.PayAt),
		ProductInfo:      conv.MustString(project.ProductSnap),
		ProductPhotoInfo: conv.MustString(project.ProductPhotoSnap),
		AutoFailAt:       util.GetTimePoionter(project.AutoFailAt),
	}
	Strategys, err := db.GetRecruitStrategys(ctx, projectID)
	if err != nil {
		logrus.WithContext(ctx).Error()
		return nil, err
	}
	for _, strategy := range Strategys {
		RecruitStrategy := http_model.ShowRecruitStrategy{
			RecruitStrategyID: conv.MustString(strategy.RecruitStrategyID),
			FeeForm:           conv.MustString(strategy.FeeForm),
			StrategyID:        conv.MustString(strategy.StrategyID),
			FollowersLow:      conv.MustString(strategy.FollowersLow),
			FollowersUp:       conv.MustString(strategy.FollowersUp),
			RecruitNumber:     conv.MustString(strategy.RecruitNumber),
			Offer:             conv.MustString(strategy.Offer),
			ServiceCharge:     conv.MustString(strategy.ServiceCharge),
			SelectedNumber:    strategy.SelectedNumber,
			WaitingNumber:     strategy.WaitingNumber,
			DeliveredNumber:   strategy.DeliveredNumber,
			SignedNumber:      strategy.SignedNumber,
		}
		ProjectDetail.RecruitStrategys = append(ProjectDetail.RecruitStrategys, RecruitStrategy)
	}
	Photos, err := db.GetProjectPhoto(ctx, projectID)
	if err != nil {
		logrus.WithContext(ctx).Error()
		return nil, err
	}
	for _, Photo := range Photos {
		ProjectPhoto := http_model.ShowProjectPhoto{
			PhotoUrl: Photo.PhotoUrl,
			PhotoUid: Photo.PhotoUid,
			FileName: Photo.FileName,
		}
		ProjectDetail.ProjectPhotos = append(ProjectDetail.ProjectPhotos, ProjectPhoto)
	}
	return &ProjectDetail, nil
}

func (*project) GetTaskLogisticsList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) (*http_model.TaskLogisticsListData, error) {
	TaskLogisticss, total, err := db.GetTaskLogisticsList(ctx, projectID, pageSize, pageNum, conditions)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetTaskLogisticsList error,err:%+v", err)
		return nil, err
	}
	TaskLogisticsListData := new(http_model.TaskLogisticsListData)
	TaskLogisticsListData.TaskLogisticsPreview = pack.MGormTaskLogisticsInfoListToHttpTaskLogisticsPreviewList(TaskLogisticss)
	TaskLogisticsListData.Total = conv.MustString(total)
	return TaskLogisticsListData, nil
}

// ChangeTaskStatus 提报达人或拒绝提报达人
func (*project) ChangeTaskStatus(ctx *gin.Context, data http_model.ProjectChangeTaskStatusRequest) interface{} {
	RecruitStrategyIDs, err := db.ChangeTaskStatus(ctx, data.TaskIds, data.SupplierStatus)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call ChangeTaskStatus error,err:%+v", err)
		return err
	}
	fmt.Println(RecruitStrategyIDs)
	// 已选数量
	//if data.SupplierStatus == 2 {
	//	for _, RecruitStrategyID := range RecruitStrategyIDs {
	//		err = db.CalculateSelectedNumberByRecruitStrategyID(ctx, RecruitStrategyID, 0)
	//		if err != nil {
	//			logrus.WithContext(ctx).Errorf("[project service] call ChangeTaskStatus error,err:%+v", err)
	//			return err
	//		}
	//	}
	//} else if data.SupplierStatus == 3 {
	//	for _, RecruitStrategyID := range RecruitStrategyIDs {
	//		err = db.CalculateSelectedNumberByRecruitStrategyID(ctx, RecruitStrategyID, 0)
	//		if err != nil {
	//			logrus.WithContext(ctx).Errorf("[project service] call ChangeTaskStatus error,err:%+v", err)
	//			return err
	//		}
	//	}
	//}
	return nil
}

// ChangeSpecialTaskStatus 定向种草任务 提报达人，拒绝提报
func (*project) ChangeSpecialTaskStatus(ctx *gin.Context, data http_model.ProjectChangeTaskStatusRequest) interface{} {
	err := db.ChangeSpecialTaskStatus(ctx, data.TaskIds, data.SupplierStatus)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call ChangeSpecialTaskStatus error,err:%+v", err)
		return err
	}
	return nil
}

func (p *project) GetTaskScriptList(ctx *gin.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) (*http_model.TaskScriptListData, error) {
	TaskScripts, total, err := db.GetTaskScriptList(ctx, projectID, pageSize, pageNum, conditions)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetTaskScriptList error,err:%+v", err)
		return nil, err
	}
	TaskScriptListData := new(http_model.TaskScriptListData)
	TaskScriptListData.TaskScriptPreview = pack.MGormTaskScriptInfoListToHttpTaskScriptPreviewList(TaskScripts)
	TaskScriptListData.Total = conv.MustString(total)
	return TaskScriptListData, nil
}

func (p *project) GetTaskSketchList(ctx *gin.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) (*http_model.TaskSketchListData, error) {
	TaskSketchs, total, err := db.GetTaskSketchList(ctx, projectID, pageSize, pageNum, conditions)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetTaskSketchList error,err:%+v", err)
		return nil, err
	}
	TaskSketchListData := new(http_model.TaskSketchListData)
	TaskSketchListData.TaskSketchPreview = pack.MGormTaskSketchInfoListToHttpTaskSketchPreviewList(TaskSketchs)
	TaskSketchListData.Total = conv.MustString(total)
	return TaskSketchListData, nil
}

func (p *project) GetTaskLinkList(ctx *gin.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) (*http_model.TaskLinkListData, error) {
	TaskLinks, total, err := db.GetTaskLinkList(ctx, projectID, pageSize, pageNum, conditions)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetTaskLinkList error,err:%+v", err)
		return nil, err
	}
	TaskLinkListData := new(http_model.TaskLinkListData)
	TaskLinkListData.TaskLinkPreview = pack.MGormTaskLinkInfoListToHttpTaskLinkPreviewList(TaskLinks)
	TaskLinkListData.Total = conv.MustString(total)
	return TaskLinkListData, nil
}

func (p *project) GetTaskDataList(ctx *gin.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) (*http_model.TaskDataListData, error) {
	TaskDatas, total, err := db.GetTaskDataList(ctx, projectID, pageSize, pageNum, conditions)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetTaskDataList error,err:%+v", err)
		return nil, err
	}
	TaskDataListData := new(http_model.TaskDataListData)
	TaskDataListData.TaskDataPreview = pack.MGormTaskDataInfoListToHttpTaskDataPreviewList(TaskDatas)
	TaskDataListData.Total = conv.MustString(total)
	return TaskDataListData, nil
}

func (p *project) GetTaskFinishList(ctx *gin.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) (*http_model.TaskFinishListData, error) {
	TaskFinishs, total, err := db.GetTaskFinishList(ctx, pageSize, pageNum, conditions)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetTaskFinishList error,err:%+v", err)
		return nil, err
	}
	TaskFinishListData := new(http_model.TaskFinishListData)
	TaskFinishListData.TaskFinishPreview = pack.MGormTaskFinishInfoListToHttpTaskFinishPreviewList(TaskFinishs)
	TaskFinishListData.Total = conv.MustString(total)
	return TaskFinishListData, nil
}

func (p *project) GetServiceCharge(ctx *gin.Context, data http_model.GetServiceChargeRequest) (*http_model.ServiceChargeData, error) {
	pricingStrategy, err := db.GetPricingStrategy(ctx, data.FollowersLow, data.FollowersUp, data.FeeForm, data.Platform)
	if err != nil {
		return nil, err
	}
	serviceFee := http_model.ServiceChargeData{
		ServiceCharge: pricingStrategy.ServiceCharge,
	}
	return &serviceFee, nil
}

func (*project) GetSpecialProjectTaskList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TalentConditions) (*http_model.SpecialTaskLogisticsListData, error) {
	SpecialTaskLogisticsListDatas, total, err := db.GetSpecialTaskLogisticsList(ctx, projectID, pageSize, pageNum, conditions)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[project service] call GetSpecialProjectTaskList error,err:%+v", err)
		return nil, err
	}
	TaskLogisticsListData := new(http_model.SpecialTaskLogisticsListData)
	TaskLogisticsListData.SpecialTaskLogisticsPreview = pack.MGormSpecialTaskLogisticsInfoListToHttpTaskLogisticsPreviewList(SpecialTaskLogisticsListDatas)
	TaskLogisticsListData.Total = conv.MustString(total, "")
	return TaskLogisticsListData, nil
}

// ShowTaskProgress ToDo
// ShowTaskProgress 展示种草子任务进度
func (p *project) ShowTaskProgress(ctx *gin.Context, data http_model.ShowTaskProgressRequest) (*http_model.ShowTaskProgressData, error) {
	// 1. 初始化返回数据结构体
	var taskProgressData *http_model.ShowTaskProgressData
	taskProgressData = &http_model.ShowTaskProgressData{}

	// 2. 根据task_id筛选出对应的子任务基础信息
	taskInfo, taskErr := db.GetTaskByTaskId(ctx, data.TaskId)
	if taskErr != nil {
		return nil, taskErr
	}
	if taskInfo != nil {
		taskProgressData.TaskId = data.TaskId
		taskProgressData.CreateData = taskInfo.CreateDate
		taskProgressData.SelectDate = taskInfo.SelectDate
		taskProgressData.DeliveryDate = taskInfo.DeliveryDate
		taskProgressData.SignedTime = taskInfo.SignedTime
		taskProgressData.ServiceCharge = taskInfo.ServiceCharge
		taskProgressData.DraftFee = taskInfo.DraftFee
	}

	// 3. 筛选出上传初稿时间和初稿状态
	taskSketchs, taskSketchErr := db.FindSketchInfoByTaskId(ctx, data.TaskId)
	if taskSketchErr != nil {
		return nil, taskSketchErr
	}
	if taskSketchs != nil {
		taskProgressData.SketchInfo = taskSketchs
	}

	// 4. 筛选作品链接上传时间和状态
	taskLinks, taskLinksErr := db.GetLinkByTaskId(ctx, data.TaskId)
	if taskLinksErr != nil {
		return nil, taskLinksErr
	}
	if taskLinks != nil {
		taskProgressData.LinkInfo = taskLinks
	}

	// 5. 若有违约，筛选出违约情况
	if taskInfo != nil {
		taskProgressData.TerminateTime = taskInfo.TerminateTime
		taskProgressData.TerminateReason = taskInfo.TerminateReason
		taskProgressData.CancelTime = taskInfo.CancelTime
		taskProgressData.CancelReason = taskInfo.CancelReason
	}

	return taskProgressData, nil
}

func (p *project) GetProjectStrategys(ctx *gin.Context, projectId string) ([]gorm_model.RecruitStrategy, error) {
	recruitStrategys, getProjectStrategysErr := db.GetRecruitStrategyByProjectId(ctx, projectId)
	if getProjectStrategysErr != nil {
		return nil, getProjectStrategysErr
	}
	return recruitStrategys, nil
}
