package service

import (
	"context"
	"fmt"
	"github.com/issue9/conv"
	log "github.com/sirupsen/logrus"
	"time"
	"youngee_b_api/db"
	"youngee_b_api/model/common_model"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
)

var SProject *sProject

type sProject struct {
}

// CreateSProject 新建服务商加入商单后的公开种草任务
func (*sProject) CreateSProject(ctx context.Context, request http_model.AddToListRequest) error {

	// 1. 建立SProject信息
	// 1.1. 根据传入的ProjectId去Project表查找信息补全SProject
	newSProject := gorm_model.SProjectInfo{
		EnterpriseId:   request.EnterpriseId,
		SupplierId:     request.SupplierId,
		ProjectId:      request.ProjectId,
		SubAccountId:   request.SubAccountId,
		OperatorType:   request.OperatorType,
		SProjectStatus: 2,
		StrategyStatus: 1,
	}
	projectInfo, projectErr := db.GetProjectDetail(ctx, request.ProjectId)
	if projectErr != nil {
		return projectErr
	}
	if projectInfo != nil {
		var currentTime time.Time
		currentTime = time.Now()
		newSProject.ProjectStatus = projectInfo.ProjectStatus
		newSProject.ProjectForm = projectInfo.ProjectForm
		newSProject.ContentType = projectInfo.ContentType
		newSProject.ProjectPlatform = projectInfo.ProjectPlatform
		newSProject.CreateTime = &currentTime
		newSProject.ProjectType = 1
		newSProject.ProductId = projectInfo.ProductID
		newSProject.ProjectName = projectInfo.ProjectName
	}
	sProjectId, err := db.CreateSProject(ctx, newSProject)
	if err != nil {
		log.Infof("[CreateEnterpriseSubUser] fail,err:%+v", err)
		return err
	}
	fmt.Println("创建SProject信息成功")

	// 2. 建立新的recruitStrategy
	// 2.1. 根据projectId去查找原来的recruitStrategy
	recruitStrategys, strategyErr := db.GetRecruitStrategyByProjectId(ctx, request.ProjectId)
	if strategyErr != nil {
		return strategyErr
	}
	// 2.2. 设置新的结构体以写入
	var currRecruitStrategys []gorm_model.RecruitStrategy
	for _, strategy := range recruitStrategys {
		var currStrategy gorm_model.RecruitStrategy
		currStrategy.StrategyID = strategy.StrategyID
		currStrategy.QuoteRecruitStrategyId = int(strategy.RecruitStrategyID)
		currStrategy.FeeForm = strategy.FeeForm
		currStrategy.FollowersLow = strategy.FollowersLow
		currStrategy.FollowersUp = strategy.FollowersUp
		currStrategy.RecruitNumber = strategy.RecruitNumber
		currStrategy.Offer = strategy.Offer
		currStrategy.TOffer = strategy.TOffer
		currStrategy.ProjectID = strategy.ProjectID
		currStrategy.ServiceCharge = strategy.ServiceCharge
		currStrategy.ServiceRate = strategy.ServiceRate
		currStrategy.SProjectId = sProjectId
		currStrategy.StrategyType = 2
		currRecruitStrategys = append(currRecruitStrategys, currStrategy)
	}
	// 2.3. 写入
	createStrategyErr := db.CreateSpecialStrategy(ctx, currRecruitStrategys)
	if createStrategyErr != nil {
		return createStrategyErr
	}
	fmt.Println("创建招募策略成功")
	return nil
}

// GetSProjectList 查找服务商加入商单的种草任务列表
func (*sProject) GetSProjectList(ctx context.Context, supplierId int, pageSize, pageNum int32, condition *common_model.SProjectCondition) (*http_model.SProjectData, error) {
	var SProjectList *http_model.SProjectData
	SProjectList = &http_model.SProjectData{}

	// 1. 加入商单后的种草任务基本信息
	sProjects, total, err := db.GetSProjectList(ctx, supplierId, pageSize, pageNum, condition)
	if err != nil {
		return nil, err
	}
	SProjectList.Total = total

	// 2. 商品信息填入
	for _, sProject := range sProjects {
		var currSProject *http_model.SProjectListReview
		currSProject = &http_model.SProjectListReview{}
		currSProject.SProjectId = sProject.SProjectId
		currSProject.ProjectId = sProject.ProjectId
		currSProject.ProjectPlatform = sProject.ProjectPlatform
		currSProject.ContentType = sProject.ContentType
		currSProject.ProjectForm = sProject.ProjectForm
		currSProject.ProjectStatus = sProject.ProjectStatus
		currSProject.SupplierId = sProject.SupplierId
		currSProject.SubAccountId = sProject.SubAccountId
		currSProject.OperatorType = sProject.OperatorType
		currSProject.CreateTime = conv.MustString(sProject.CreateTime)[0:19]
		currSProject.ApplyNum = sProject.ApplyNum
		currSProject.RecruitNum = sProject.RecruitNum
		currSProject.SettleNum = sProject.SettleNum
		currSProject.ServiceChargeActual = sProject.ServiceChargeActual
		currSProject.ServiceCharge = sProject.ServiceCharge
		currSProject.ServiceChargeSettle = sProject.ServiceChargeSettle

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

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

// GetSPorjectDetail 查找服务商种草任务详情
func (*sProject) GetSPorjectDetail(ctx context.Context, sProjectId int) (*http_model.ShowSProjectData, error) {
	var sProjectData *http_model.ShowSProjectData
	sProjectData = &http_model.ShowSProjectData{}

	// 1. 取出服务商种草表中的信息
	sProjectInfo, err := db.GetSProjectDetail(ctx, sProjectId)
	if err != nil {
		return nil, err
	}
	if sProjectInfo != nil {
		sProjectData.SProjectId = sProjectInfo.SProjectId
		sProjectData.ProjectName = sProjectInfo.ProjectName
		sProjectData.ProjectID = sProjectInfo.ProjectId
		sProjectData.ProjectType = sProjectInfo.ProjectType
		sProjectData.ProjectPlatform = sProjectInfo.ProjectPlatform
		sProjectData.ProjectForm = sProjectInfo.ProjectForm
		sProjectData.ContentType = sProjectInfo.ContentType
		sProjectData.EnterpriseID = sProjectInfo.EnterpriseId

		// 2. 取出商家发布的种草任务表中的信息作为补充
		projectInfo, projectErr := db.GetProjectDetail(ctx, sProjectInfo.ProjectId)
		if projectErr != nil {
			return nil, projectErr
		}
		if projectInfo != nil {
			sProjectData.TalentType = projectInfo.TalentType
			sProjectData.RecruitDdl = conv.MustString(projectInfo.RecruitDdl)[0:19]
			sProjectData.ProjectDetail = projectInfo.ProjectDetail
			// sProjectData.PayAt = conv.MustString(projectInfo.PayAt)
			sProjectData.ProjectDetail = projectInfo.ProjectDetail
			sProjectData.EstimatedCost = projectInfo.EstimatedCost
			sProjectData.PassAt = conv.MustString(projectInfo.PassAt)[0:19]

			// 3. 取出招募策略并聚合达人数量信息
			recruitStrategy, recruitErr := db.GetRecruitStrategyByProjectId(ctx, sProjectData.ProjectID)
			if recruitErr != nil {
				return nil, recruitErr
			}
			if recruitStrategy != nil {
				for _, strategy := range recruitStrategy {
					// fmt.Println("recruitStrategy: ", strategy)
					selectedNumber, countTaskErr := db.CountTaskNumByStrategyId(ctx, sProjectData.ProjectID, strategy.StrategyID)
					if countTaskErr != nil {
						return nil, countTaskErr
					}
					showStrategy := http_model.ShowSRecruitStrategy{
						StrategyID:     strategy.StrategyID,
						FeeForm:        strategy.FeeForm,
						FollowersLow:   strategy.FollowersLow,
						FollowersUp:    strategy.FollowersUp,
						RecruitNumber:  strategy.RecruitNumber,
						ServiceCharge:  projectInfo.ServiceChargeRate,
						SelectedNumber: selectedNumber,
						Offer:          strategy.Offer,
					}
					sProjectData.SRecruitStrategys = append(sProjectData.SRecruitStrategys, showStrategy)
				}
			}

			// 4. 取出种草任务创建者用户信息
			if projectInfo.OperatorType == 1 {
				// fmt.Println("商家用户")
				enterpriseInfo, enterpriseErr := db.GetEnterpriseByEnterpriseID(ctx, projectInfo.EnterpriseID)
				if enterpriseErr != nil {
					return nil, enterpriseErr
				}
				sProjectData.CreatorName = enterpriseInfo.BusinessName
				sProjectData.CreatorCompany = enterpriseInfo.BusinessName
				sProjectData.CreatorType = 1
				sProjectData.Phone = enterpriseInfo.BusinessName
			} else if projectInfo.OperatorType == 2 {
				// fmt.Println("商家子账号")
				enterpriseInfo, enterpriseErr := db.GetEnterpriseByEnterpriseID(ctx, projectInfo.EnterpriseID)
				if enterpriseErr != nil {
					return nil, enterpriseErr
				}
				sProjectData.CreatorCompany = enterpriseInfo.BusinessName
				subAccountInfo, SubAccountErr := db.FindSubAccountById(ctx, projectInfo.SubAccountId)
				if SubAccountErr != nil {
					return nil, SubAccountErr
				}
				sProjectData.Phone = subAccountInfo.PhoneNumber
				jobInfo, jobErr := db.FindJobByJobId(ctx, subAccountInfo.JobId)
				if jobErr != nil {
					return nil, jobErr
				}
				sProjectData.CreatorType = 2
				sProjectData.CreatorName = jobInfo.JobName
			}

			// 5. 商品信息
			// 5.1. 取出商品信息并聚合
			productInfo, productErr := db.GetProductByID(ctx, projectInfo.ProductID)
			if productErr != nil {
				return nil, productErr
			}
			if productInfo != nil {
				sProjectData.ProductID = productInfo.ProductID
				sProjectData.ProductName = productInfo.ProductName
				sProjectData.ProductType = productInfo.ProductType
				sProjectData.ProductPrice = productInfo.ProductPrice
				sProjectData.ProductCategory = productInfo.ProductCategory
			}
			// 5.2. 聚合商品图片信息
			productPhotoInfo, productPhotoErr := db.GetProductPhotoByProductID(ctx, projectInfo.ProductID)
			if productPhotoErr != nil {
				return nil, productPhotoErr
			}
			if productPhotoInfo != nil {
				for _, p := range productPhotoInfo {
					if p.Symbol == 1 {
						sProjectData.ProductMainPhotoUrl = p.PhotoUrl
						sProjectData.ProductMainPhotoUid = p.PhotoUid
						sProjectData.Symbol = 1
					}
				}
			}

			// 6. 执行要求Brief和素材
			// 6.1. Brief
			projectBrief, briefErr := db.FindProjectBriefByProjectId(ctx, sProjectData.ProjectID)
			if briefErr != nil {
				return nil, briefErr
			}
			if projectBrief != nil {
				sProjectData.ProjectBriefInfo = projectBrief
			}

			// 6.2. 素材
			projectMaterial, materialErr := db.FindProjectMaterialByProjectId(ctx, sProjectData.ProjectID)
			if materialErr != nil {
				return nil, materialErr
			}
			if projectMaterial != nil {
				sProjectData.ProjectMaterial = projectMaterial
			}
		}
	}
	return sProjectData, nil
}

// GetSpecialProjectList 查找服务商加入商单前的定向种草任务列表
func (*sProject) GetSpecialProjectList(ctx context.Context, supplierId int, pageSize, pageNum int32, condition *common_model.SSpecialProjectCondition) (*http_model.SpecialProjectListData, error) {
	var specialProjectListData *http_model.SpecialProjectListData
	specialProjectListData = &http_model.SpecialProjectListData{}

	// 1. 定向种草任务基本信息填入
	specialProjects, total, err := db.GetSpecialProjectList(ctx, supplierId, pageSize, pageNum, condition)
	if err != nil {
		return nil, err
	}
	if specialProjects != nil {
		specialProjectListData.Total = total
		for _, specialProject := range specialProjects {
			var currSpecialProject *http_model.SpecialProjectResponse
			currSpecialProject = &http_model.SpecialProjectResponse{}
			currSpecialProject.SProjectId = specialProject.SProjectId
			currSpecialProject.ProjectPlatform = specialProject.ProjectPlatform
			currSpecialProject.ProjectForm = specialProject.ProjectForm
			currSpecialProject.ContentType = specialProject.ContentType
			currSpecialProject.SProjectStatus = specialProject.SProjectStatus

			// 2. 定向种草任务商品信息填入
			// 2.1. 商品信息
			productInfo, productErr := db.GetProductByID(ctx, specialProject.ProductId)
			if productErr != nil {
				return nil, productErr
			}
			if productInfo != nil {
				currSpecialProject.ProductId = productInfo.ProductID
				currSpecialProject.ProductName = productInfo.ProductName
				currSpecialProject.ProductPrice = productInfo.ProductPrice
			}

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

			// 3. 招募策略信息
			recruitStrategy, recruitErr := db.GetRecruitStrategyByProjectId(ctx, specialProject.ProjectId)
			if recruitErr != nil {
				return nil, recruitErr
			}
			if recruitStrategy != nil {
				for _, strategy := range recruitStrategy {
					showStrategy := http_model.EasyRecruitStrategy{
						FeeForm:       strategy.FeeForm,
						RecruitNumber: strategy.RecruitNumber,
						StrategyId:    strategy.StrategyID,
					}
					currSpecialProject.RecruitStrategy = append(currSpecialProject.RecruitStrategy, showStrategy)
				}
			}

			// 4. 原种草任务信息
			projectInfo, projectErr := db.GetProjectDetail(ctx, specialProject.ProjectId)
			if projectErr != nil {
				return nil, projectErr
			}
			if projectInfo != nil {
				currSpecialProject.Tools = projectInfo.Tools
			}
			specialProjectListData.SpecialProjectInfo = append(specialProjectListData.SpecialProjectInfo, currSpecialProject)
		}
	} else {
		specialProjectListData.Total = 0
	}
	return specialProjectListData, nil
}

// GetSpecialSProjectList 查找服务商加入商单后的定向种草任务列表
func (*sProject) GetSpecialSProjectList(ctx context.Context, supplierId int, pageSize, pageNum int32, condition *common_model.SSpecialProjectCondition) (*http_model.SpecialSProjectListData, error) {
	var specialProjectListData *http_model.SpecialSProjectListData
	specialProjectListData = &http_model.SpecialSProjectListData{}
	specialProjects, total, err := db.GetSpecialProjectList(ctx, supplierId, pageSize, pageNum, condition)
	if err != nil {
		return nil, err
	}
	if specialProjects != nil {
		specialProjectListData.Total = total
		// 1. 定向种草任务基本信息填入
		for _, specialProject := range specialProjects {
			var currSpecialProject *http_model.SpecialProjectResponse
			currSpecialProject = &http_model.SpecialProjectResponse{}
			currSpecialProject.SProjectId = specialProject.SProjectId
			currSpecialProject.ProjectPlatform = specialProject.ProjectPlatform
			currSpecialProject.ProjectForm = specialProject.ProjectForm
			currSpecialProject.ContentType = specialProject.ContentType
			currSpecialProject.SProjectStatus = specialProject.SProjectStatus

			// 2. 定向种草任务商品信息填入
			// 2.1. 商品信息
			productInfo, productErr := db.GetProductByID(ctx, specialProject.ProductId)
			if productErr != nil {
				return nil, productErr
			}
			if productInfo != nil {
				currSpecialProject.ProductId = productInfo.ProductID
				currSpecialProject.ProductName = productInfo.ProductName
				currSpecialProject.ProductPrice = productInfo.ProductPrice
			}

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

			// 3. 招募策略信息
			recruitStrategy, recruitErr := db.GetRecruitStrategyByProjectId(ctx, specialProject.ProjectId)
			if recruitErr != nil {
				return nil, recruitErr
			}
			if recruitStrategy != nil {
				for _, strategy := range recruitStrategy {
					showStrategy := http_model.EasyRecruitStrategy{
						FeeForm:       strategy.FeeForm,
						RecruitNumber: strategy.RecruitNumber,
						StrategyId:    strategy.StrategyID,
					}
					currSpecialProject.RecruitStrategy = append(currSpecialProject.RecruitStrategy, showStrategy)
				}
			}

			// 4. 原种草任务信息
			projectInfo, projectErr := db.GetProjectDetail(ctx, specialProject.ProjectId)
			if projectErr != nil {
				return nil, projectErr
			}
			if projectInfo != nil {
				currSpecialProject.Tools = projectInfo.Tools
			}
			specialProjectListData.SpecialProjectInfo = append(specialProjectListData.SpecialProjectInfo, currSpecialProject)
		}
	} else {
		specialProjectListData.Total = 0
	}
	return specialProjectListData, nil
}

// UpdateSProject 更新SProject信息
func (*sProject) UpdateSProject(ctx context.Context, request *http_model.SpecialSProjectAddToListRequest) error {
	updateSProjectErr := db.UpdateSProjectStatus(ctx, request)
	if updateSProjectErr != nil {
		return updateSProjectErr
	}
	return nil
}

// CreateSpecialStrategy 添加服务商招募策略
func (*sProject) CreateSpecialStrategy(ctx context.Context, request *http_model.SpecialAddStrategyRequest) error {
	// 1. 添加服务商招募策略
	createErr := db.CreateSpecialStrategy(ctx, request.RecruitStrategys)
	if createErr != nil {
		return createErr
	}

	// 2. 修改sProject中的字段
	updateErr := db.UpdateSProjectStrategyStatus(ctx, request)
	if updateErr != nil {
		return updateErr
	}
	return nil
}

// FullSProjectBillList 种草任务账单列表
func (*sProject) FullSProjectBillList(ctx context.Context, request *http_model.FullSProjectBillListRequest) (*http_model.FullSProjectBillData, error) {
	// 1. 根据SupplierId和账单状态查询数据
	fullSProjectBillData, total, err := db.GetFullSProjectBillList(ctx, request.SupplierId, request.ProjectPlatform, request.ProjectStatus, request.PageSize, request.PageNum)
	if err != nil {
		return nil, err
	}
	var currSProjectBillData *http_model.FullSProjectBillData
	currSProjectBillData = &http_model.FullSProjectBillData{}
	currSProjectBillData.SProjectList = fullSProjectBillData
	currSProjectBillData.Total = total
	return currSProjectBillData, nil
}
