package service

import (
	"encoding/json"
	"errors"
	"github.com/sirupsen/logrus"
	"reflect"
	"strings"
	"time"
	"youngee_b_api/app/dao"
	"youngee_b_api/app/entity"
	"youngee_b_api/app/service/review_service"
	"youngee_b_api/app/util"
	"youngee_b_api/app/vo"
)

type SelectionInfoService struct{}

//func (s *SelectionInfoService) GetSelectionInfo(ctx *gin.Context, selectionId string) (*http_model.SelectionDetail, error) {
//	selectionDetail := http_model.SelectionDetail{}
//	selectionInfo, err := db.GetSelectionById(ctx, selectionId)
//
//	if err != nil {
//		logrus.WithContext(ctx).Errorf("[selectionDB service] call GetSelectionInfo error,err:%+v", err)
//		return nil, err
//	}
//	selectionBriefInfo, err := db.GetSelectionBriefInfo(ctx, selectionId)
//	if err != nil {
//		logrus.WithContext(ctx).Errorf("[selectionDB service] call GetSelectionBriefInfo error,err:%+v", err)
//		return nil, err
//	}
//	selectionExampleInfo, err := db.GetSelectionExampleInfo(ctx, selectionId)
//	if err != nil {
//		logrus.WithContext(ctx).Errorf("[selectionDB service] call GetSelectionExampleInfo error,err:%+v", err)
//		return nil, err
//	}
//	productInfo, err := db.GetProductInfoBySelectionId(ctx, selectionId)
//	if err != nil {
//		logrus.WithContext(ctx).Errorf("[selectionDB service] call GetProductInfo error,err:%+v", err)
//		return nil, err
//	}
//	productPhotoInfo, err := db.GetProductPhotoInfoBySelectionId(ctx, selectionId)
//	if err != nil {
//		logrus.WithContext(ctx).Errorf("[selectionDB service] call GetProductPhotoInfo error,err:%+v", err)
//		return nil, err
//	}
//	selectionDetail.SelectionBrief = selectionBriefInfo
//	selectionDetail.SelectionInfo = selectionInfo
//	selectionDetail.SelectionExample = selectionExampleInfo
//	selectionDetail.ProductInfo = productInfo
//	selectionDetail.ProductPhotoInfo = productPhotoInfo
//	return &selectionDetail, nil
//}

// 创建带货任务
func (s SelectionInfoService) CreateSelectionInfo(selectionCreateParam *vo.SelectionInfoCreateParam) (*string, error) {
	// 1. 生成选品id
	selectionId := strings.ReplaceAll(util.GenerateUUID(11), "-", "")
	// 2. 数据准备
	// 查找关联商品信息
	product, err := dao.ProductDAO{}.GetProductByID(selectionCreateParam.ProductId)
	if err != nil {
		return nil, err
	}
	if product == nil {
		return nil, errors.New("未找到关联商品")
	}
	productMainPhoto, _ := dao.ProductPhotoDAO{}.GetMainProductPhotoInfoByProductID(selectionCreateParam.ProductId)
	productInfoToJson, _ := json.Marshal(product)
	productPhotosToJson, _ := json.Marshal(productMainPhoto)
	// 任务截止时间
	taskDdl, err1 := time.ParseInLocation("2006-01-02 15:04:05", selectionCreateParam.TaskDdl, time.Local)
	if err1 != nil {
		return nil, errors.New("failed to parse taskDdl")
	}
	// 创建选品
	// 获取定时任务配置
	infoAutoTask := entity.InfoAutoTask{}
	infoAutoTask = dao.InfoAutoTaskDao{}.GetAutoTaskLast(selectionCreateParam.EnterpriseId)
	t := time.Now()
	if taskDdl.Before(t) {
		return nil, errors.New("请修改截止时间")
	}
	var sampleMode, taskMode int64
	var poolRewardSum float64
	if len(selectionCreateParam.FreeStrategys) > 0 {
		sampleMode = 1
	} else {
		sampleMode = 3
	}
	if len(selectionCreateParam.RewardStrategys) > 0 {
		taskMode = 1
		for _, rewardStrategy := range selectionCreateParam.RewardStrategys {
			poolRewardSum += rewardStrategy.Reward
		}
	} else {
		taskMode = 2
	}

	newSelection := entity.SelectionInfo{
		SelectionStatus:  1,
		SelectionID:      selectionId,
		ProductID:        selectionCreateParam.ProductId,
		ProductCategory:  product.ProductCategory,
		EnterpriseID:     selectionCreateParam.EnterpriseId,
		SubAccountId:     selectionCreateParam.SubAccountId,
		Platform:         selectionCreateParam.Platform,
		ProductSnap:      string(productInfoToJson),
		ProductPhotoSnap: string(productPhotosToJson),
		SelectionName:    selectionCreateParam.SelectionName,
		TaskDdl:          taskDdl,
		SampleNum:        selectionCreateParam.SampleNum,
		RemainNum:        selectionCreateParam.SampleNum,
		SampleMode:       sampleMode,
		TaskMode:         taskMode,
		CreatedAt:        t,
		AutoTaskID:       infoAutoTask.AutoTaskID,
		EstimatedCost:    poolRewardSum,
	}
	err = dao.SelectionInfoDAO{}.CreateSelectionInfo(newSelection)
	if err != nil {
		return nil, err
	}

	// 4. 更新选品brief和示例（带货任务补充信息）
	if selectionCreateParam.SecBrief != nil {
		// 插入新的brief
		for _, v := range selectionCreateParam.SecBrief {
			brief := entity.SecBrief{
				SelectionID: selectionId,
				FileUid:     v.FileUid,
				FileName:    v.Name,
				FileUrl:     v.FileUrl,
				CreatedAt:   time.Now(),
				Type:        v.Type,
			}
			err = dao.SecBriefDao{}.CreateSecBrief(brief)
			if err != nil {
				return nil, err
			}
		}
	}
	if selectionCreateParam.SecMaterial != nil {
		// 插入新的示例
		for _, v := range selectionCreateParam.SecMaterial {
			secMaterial := entity.SecMaterial{
				SelectionID: selectionId,
				FileUid:     v.FileUid,
				FileName:    v.Name,
				FileUrl:     v.FileUrl,
				CreatedAt:   time.Now(),
				Type:        v.Type,
			}
			err = dao.SecMaterialDao{}.CreateSecMaterial(secMaterial)
			if err != nil {
				return nil, err
			}
		}
	}
	// 更新带货任务的免费领样策略
	if selectionCreateParam.FreeStrategys != nil {
		// 2. 接收并创建新的免费领样策略
		if sampleMode == 1 {
			var frees []entity.FreeStrategy
			for _, v := range selectionCreateParam.FreeStrategys {
				free := entity.FreeStrategy{
					SelectionId:    selectionId,
					StrategyId:     v.StrategyId,
					FollowersLow:   v.FollowersLow,
					FollowersUp:    v.FollowersUp,
					SaleNum:        v.SaleNum,
					StrategyStatus: 1,
					EnrollNum:      0,
					ChooseNum:      0,
				}
				frees = append(frees, free)
			}
			err = dao.FreeStrategyDao{}.CreateFreeStrategy(frees)
			if err != nil {
				return nil, err
			}
		}
	}
	// 更新带货任务的悬赏策略
	if selectionCreateParam.RewardStrategys != nil {
		if taskMode == 1 {
			var rewards []entity.RewardStrategy
			for _, v := range selectionCreateParam.RewardStrategys {
				reward := entity.RewardStrategy{
					SelectionId:    selectionId,
					Reward:         v.Reward,
					SaleActual:     v.SaleActual,
					PerReward:      v.PerReward,
					StrategyStatus: 1,
				}
				rewards = append(rewards, reward)
			}
			err = dao.RewardStrategyDao{}.CreateRewardStrategy(rewards)
			if err != nil {
				return nil, err
			}
		}
	}

	return &selectionId, nil
}

// 更新带货任务（样品奖励、补充信息）
func (s SelectionInfoService) UpdateSelectionInfo(selectionUpdateParam *vo.SelectionInfoUpdateParam) (*string, error) {
	// 1. 检查该id
	selectionID := selectionUpdateParam.SelectionID
	selectionInfo, err := dao.SelectionInfoDAO{}.GetSelectionInfoById(selectionID)
	if err != nil {
		return nil, err
	}
	if selectionInfo == nil {
		return nil, errors.New("选品不存在")
	}
	// 2. 数据准备
	// a) 查找关联商品信息
	var productInfoToString string
	var productPhotosToString string
	if selectionUpdateParam.ProductId != 0 {
		product, err := dao.ProductDAO{}.GetProductByID(selectionUpdateParam.ProductId)
		if err != nil {
			return nil, err
		}
		if product == nil {
			return nil, errors.New("未找到关联商品")
		}
		productMainPhoto, _ := dao.ProductPhotoDAO{}.GetMainProductPhotoInfoByProductID(selectionUpdateParam.ProductId)
		productInfoToJson, _ := json.Marshal(product)
		productInfoToString = string(productInfoToJson)
		productPhotosToJson, _ := json.Marshal(productMainPhoto)
		productPhotosToString = string(productPhotosToJson)
	}

	// d) 任务截止时间
	taskDdl := time.Time{} //赋零值
	taskDdl, _ = time.ParseInLocation("2006-01-02 15:04:05", selectionUpdateParam.TaskDdl, time.Local)
	if taskDdl.Before(selectionInfo.CreatedAt) {
		return nil, errors.New("请修改截止时间")
	}
	//// f) 更新选品状态
	//if selectionUpdateParam.SelectionStatus != 2 && selectionUpdateParam.SelectionStatus != 7 {
	//	selectionUpdateParam.SelectionStatus = 1
	//}
	t := time.Now()
	var sampleMode, taskMode int64
	var poolRewardSum float64
	if len(selectionUpdateParam.FreeStrategys) > 0 {
		sampleMode = 1
	} else {
		sampleMode = 3
	}
	if len(selectionUpdateParam.RewardStrategys) > 0 {
		taskMode = 1
		for _, rewardStrategy := range selectionUpdateParam.RewardStrategys {
			poolRewardSum += rewardStrategy.Reward
		}
	} else {
		taskMode = 2
	}
	updateSelection := entity.SelectionInfo{
		SelectionID: selectionUpdateParam.SelectionID,
		//SelectionStatus:  selectionUpdateParam.SelectionStatus,
		SelectionName: selectionUpdateParam.SelectionName,
		EnterpriseID:  selectionUpdateParam.EnterpriseId,
		SubAccountId:  selectionUpdateParam.SubAccountId,
		ProductID:     selectionUpdateParam.ProductId,
		//ProductUrl:       selectionUpdateParam.ProductUrl,
		TaskMode:   taskMode,
		SampleMode: sampleMode,
		SampleNum:  selectionUpdateParam.SampleNum,
		RemainNum:  selectionUpdateParam.SampleNum,
		//CommissionRate:   selectionUpdateParam.CommissionRate,
		//TaskReward:       selectionUpdateParam.TaskReward,
		//SettlementAmount: selectionUpdateParam.SettlementAmount,
		EstimatedCost: poolRewardSum,
		//SampleCondition:  selectionUpdateParam.SampleCondition,
		//RewardCondition:  selectionUpdateParam.RewardCondition,
		TaskDdl: taskDdl,
		//Detail:           selectionUpdateParam.Detail,
		ProductSnap:      productInfoToString,
		ProductPhotoSnap: productPhotosToString,
		CreatedAt:        selectionInfo.CreatedAt,
		UpdatedAt:        t,
	}
	//if selectionUpdateParam.SelectionStatus == 2 {
	//	updateSelection.SubmitAt = t
	//}
	//if selectionUpdateParam.Status == 1 {
	//	updateSelection.Status = 1
	//}
	// 合并传入参数和数据表中原记录，若传入参数字段值为空，则将字段赋值为原记录中值
	result := util.MergeStructValue(&updateSelection, selectionInfo)
	// 利用反射机制将interface类型转换为结构体类型
	v := reflect.ValueOf(&result).Elem()
	if v.Kind() == reflect.Struct {
		updateSelection = v.Interface().(entity.SelectionInfo)
		//fmt.Println(p)
	}
	// c) 计算预估成本（如果有）
	/*
		var estimatedCost float64
		if conv.MustInt(updateSelection.TaskMode, 0) == 1 {
			estimatedCost = conv.MustFloat64(updateSelection.TaskReward, 0) * conv.MustFloat64(updateSelection.SampleNum, 0)
		}
		estimatedCostToString, _ := conv.String(estimatedCost)
		updateSelection.EstimatedCost = estimatedCostToString
	*/
	// 3. 更新选品
	err = dao.SelectionInfoDAO{}.UpdateSelectionInfo(updateSelection)
	if err != nil {
		return nil, err
	}

	// 4. 更新选品brief和示例（带货任务补充信息）
	if selectionUpdateParam.SecBrief != nil {
		// 删除已有brief
		err = dao.SecBriefDao{}.DeleteSecBriefBySelectionId(selectionInfo.SelectionID)
		if err != nil {
			return nil, err
		}
		// 插入新的brief
		for _, v := range selectionUpdateParam.SecBrief {
			brief := entity.SecBrief{
				SelectionID: selectionInfo.SelectionID,
				FileUid:     v.FileUid,
				FileName:    v.Name,
				FileUrl:     v.FileUrl,
				CreatedAt:   time.Now(),
				Type:        v.Type,
			}
			err = dao.SecBriefDao{}.CreateSecBrief(brief)
			if err != nil {
				return nil, err
			}
		}
	}

	if selectionUpdateParam.SecMaterial != nil {
		// 删除已有示例
		err = dao.SecMaterialDao{}.DeleteSecMaterialBySelectionId(selectionInfo.SelectionID)
		if err != nil {
			return nil, err
		}
		// 插入新的示例
		for _, v := range selectionUpdateParam.SecMaterial {
			secMaterial := entity.SecMaterial{
				SelectionID: selectionInfo.SelectionID,
				FileUid:     v.FileUid,
				FileName:    v.Name,
				FileUrl:     v.FileUrl,
				CreatedAt:   time.Now(),
				Type:        v.Type,
			}
			err = dao.SecMaterialDao{}.CreateSecMaterial(secMaterial)
			if err != nil {
				return nil, err
			}
		}
	}

	println("更新带货任务的免费领样策略")
	// 更新带货任务的免费领样策略
	if selectionUpdateParam.FreeStrategys != nil {
		// 1. 删除已有的免费领样策略
		err = dao.FreeStrategyDao{}.DeleteFreeStrategyBySelectionId(selectionUpdateParam.SelectionID)
		if err != nil {
			return nil, err
		}
		// 2. 接收并创建新的免费领样策略
		if sampleMode == 1 {
			var frees []entity.FreeStrategy
			for _, v := range selectionUpdateParam.FreeStrategys {
				free := entity.FreeStrategy{
					SelectionId:    selectionInfo.SelectionID,
					StrategyId:     v.StrategyId,
					FollowersLow:   v.FollowersLow,
					FollowersUp:    v.FollowersUp,
					SaleNum:        v.SaleNum,
					StrategyStatus: 1,
					EnrollNum:      0,
					ChooseNum:      0,
				}
				frees = append(frees, free)
			}
			err = dao.FreeStrategyDao{}.CreateFreeStrategy(frees)
			if err != nil {
				return nil, err
			}
		}
	}

	println("更新带货任务的悬赏策略")
	// 更新带货任务的悬赏策略
	if selectionUpdateParam.RewardStrategys != nil {
		// 1. 删除已有的悬赏策略
		err = dao.RewardStrategyDao{}.DeleteRewardStrategyBySelectionId(selectionUpdateParam.SelectionID)
		if err != nil {
			return nil, err
		}
		if taskMode == 1 {
			var rewards []entity.RewardStrategy
			for _, v := range selectionUpdateParam.RewardStrategys {
				reward := entity.RewardStrategy{
					SelectionId:    selectionInfo.SelectionID,
					Reward:         v.Reward,
					SaleActual:     v.SaleActual,
					PerReward:      v.PerReward,
					StrategyStatus: 1,
				}
				rewards = append(rewards, reward)
			}
			err = dao.RewardStrategyDao{}.CreateRewardStrategy(rewards)
			if err != nil {
				return nil, err
			}
		}
	}

	return &updateSelection.SelectionID, nil
}

// 电商带货任务预览
func (s SelectionInfoService) GetSelectionDetail(selectionId string) (*vo.ReSelectionDetail, error) {
	reSelectionDetail := vo.ReSelectionDetail{}
	selection, err := dao.SelectionInfoDAO{}.GetSelectionInfoById(selectionId)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetSelection error,err:%+v", err)
		return nil, err
	}
	reSelectionDetail.SelectionName = selection.SelectionName
	// 系统信息
	reSelectionDetail.SelectionId = selection.SelectionID
	reSelectionDetail.SelectionStatus = selection.SelectionStatus
	reSelectionDetail.SelectionPlatform = selection.Platform
	reSelectionDetail.CreatedAt = selection.CreatedAt.Format("2006-01-02 15:04:05")
	reSelectionDetail.SubmitAt = selection.SubmitAt.Format("2006-01-02 15:04:05")
	reSelectionDetail.RewardSum = selection.EstimatedCost
	var creatorName, phone string
	//var rewardSum float64
	if selection.SubAccountId == 0 {
		enterprise, err := dao.EnterpriseDao{}.GetEnterprise(selection.EnterpriseID)
		if err == nil && enterprise != nil {
			creatorName = enterprise.BusinessName
			phone, err = dao.UserDao{}.GetPhoneByUserId(enterprise.UserId)
		}
	} else {
		subAccount, err := dao.SubAccountDao{}.GetSubAccount(selection.SubAccountId)
		if err == nil && subAccount != nil {
			creatorName = subAccount.SubAccountName
			phone, err = dao.UserDao{}.GetPhoneByUserId(subAccount.UserId)
		}
	}
	reSelectionDetail.CreatorName = creatorName
	reSelectionDetail.Phone = phone
	// 关联商品
	var reProduct vo.ReProductPreview
	product, err := dao.ProductDAO{}.GetProductByID(selection.ProductID)
	if err == nil {
		photoUrl, e := dao.ProductPhotoDAO{}.GetMainPhotoByProductID(product.ProductID)
		if e != nil {
			photoUrl = ""
		}
		reProduct = vo.ReProductPreview{
			ProductID:       product.ProductID,
			ProductName:     product.ProductName,
			ProductType:     product.ProductType,
			ProductCategory: product.ProductCategory,
			ProductPrice:    product.ProductPrice,
			ProductDetail:   product.ProductDetail,
			CreatedAt:       product.CreatedAt.Format("2006-01-02 15:04:05"),
			PhotoUrl:        photoUrl,
		}
	}
	reSelectionDetail.ProductInfo = &reProduct
	// 样品奖励
	reSelectionDetail.TaskDdl = selection.TaskDdl.Format("2006-01-02 15:04:05")
	reSelectionDetail.SampleNum = selection.SampleNum
	var freeStrategyPreviews []*vo.FreeStrategyPreview // 领样策略
	freeStrategys, err := dao.FreeStrategyDao{}.GetFreeStrategyBySelectionId(selectionId)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetFreeStrategy error,err:%+v", err)
		return nil, err
	}
	for _, freeStrategy := range freeStrategys {
		freeStrategyPreview := &vo.FreeStrategyPreview{
			StrategyId:     freeStrategy.StrategyId,
			FollowersLow:   freeStrategy.FollowersLow,
			FollowersUp:    freeStrategy.FollowersUp,
			SaleNum:        freeStrategy.SaleNum,
			StrategyStatus: freeStrategy.StrategyStatus,
		}
		freeStrategyPreviews = append(freeStrategyPreviews, freeStrategyPreview)
	}
	reSelectionDetail.FreeStrategys = freeStrategyPreviews
	var rewardStrategyPreviews []*vo.RewardStrategyPreview // 悬赏策略
	rewardStrategys, err := dao.RewardStrategyDao{}.GetRewardStrategyBySelectionId(selectionId)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetRewardStrategy error,err:%+v", err)
		return nil, err
	}
	for _, rewardStrategy := range rewardStrategys {
		rewardStrategyPreview := &vo.RewardStrategyPreview{
			Reward:         rewardStrategy.Reward,
			SaleActual:     rewardStrategy.SaleActual,
			PerReward:      rewardStrategy.PerReward,
			StrategyStatus: rewardStrategy.StrategyStatus,
		}
		rewardStrategyPreviews = append(rewardStrategyPreviews, rewardStrategyPreview)
	}
	reSelectionDetail.FreeStrategys = freeStrategyPreviews
	reSelectionDetail.RewardStrategys = rewardStrategyPreviews
	//for _, rewardStrategy := range rewardStrategys {
	//	rewardSum += rewardStrategy.Reward
	//}
	//reSelectionDetail.RewardSum = rewardSum
	// 补充信息
	selectionBriefInfos, err := dao.SecBriefDao{}.GetSelectionBriefInfo(selectionId)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetSelectionBriefInfo error,err:%+v", err)
		return nil, err
	}
	selectionMaterials, err := dao.SecMaterialDao{}.GetSelectionMaterialInfo(selectionId)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetSelectionMaterialInfo error,err:%+v", err)
		return nil, err
	}
	reSelectionDetail.SelectionBriefs = selectionBriefInfos
	reSelectionDetail.SelectionMaterials = selectionMaterials

	return &reSelectionDetail, nil
}

// 电商带货复制任务
func (s SelectionInfoService) CopySelection(param *vo.SelectionSearchParam) (*string, error) {
	selectionOrigin, err := dao.SelectionInfoDAO{}.GetSelectionInfoById(param.SelectionId)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetSelection error,err:%+v", err)
		return nil, err
	}
	if selectionOrigin == nil {
		return nil, errors.New("任务不存在")
	}
	selectionIdOrigin := selectionOrigin.SelectionID
	selectionIdNew := strings.ReplaceAll(util.GenerateUUID(11), "-", "")
	t := time.Now()
	// 获取定时任务配置
	infoAutoTask := entity.InfoAutoTask{}
	infoAutoTask = dao.InfoAutoTaskDao{}.GetAutoTaskLast(param.EnterpriseId)

	// 复制选品
	selectionNew := entity.SelectionInfo{
		SelectionStatus:  1,
		SelectionID:      selectionIdNew,
		ProductID:        selectionOrigin.ProductID,
		ProductCategory:  selectionOrigin.ProductCategory,
		EnterpriseID:     param.EnterpriseId,
		SubAccountId:     param.SubAccountId,
		Platform:         selectionOrigin.Platform,
		ProductSnap:      selectionOrigin.ProductSnap,
		ProductPhotoSnap: selectionOrigin.ProductPhotoSnap,
		SelectionName:    selectionOrigin.SelectionName,
		TaskDdl:          selectionOrigin.TaskDdl,
		SampleNum:        selectionOrigin.SampleNum,
		RemainNum:        selectionOrigin.SampleNum,
		SampleMode:       selectionOrigin.SampleMode,
		TaskMode:         selectionOrigin.TaskMode,
		CreatedAt:        t,
		AutoTaskID:       infoAutoTask.AutoTaskID,
		EstimatedCost:    selectionOrigin.EstimatedCost,
	}
	err = dao.SelectionInfoDAO{}.CreateSelectionInfo(selectionNew)
	if err != nil {
		return nil, err
	}

	// 更新选品brief和示例（带货任务补充信息）
	selectionBriefInfos, err := dao.SecBriefDao{}.GetSelectionBriefInfo(selectionIdOrigin)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetSelectionBriefInfo error,err:%+v", err)
		return nil, err
	}
	if selectionBriefInfos != nil {
		for _, v := range selectionBriefInfos {
			brief := entity.SecBrief{
				SelectionID: selectionIdNew,
				FileUid:     v.FileUid,
				FileName:    v.FileName,
				FileUrl:     v.FileUrl,
				CreatedAt:   time.Now(),
				Type:        v.Type,
			}
			err = dao.SecBriefDao{}.CreateSecBrief(brief)
			if err != nil {
				return nil, err
			}
		}
	}
	selectionMaterials, err := dao.SecMaterialDao{}.GetSelectionMaterialInfo(selectionIdOrigin)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetSelectionMaterialInfo error,err:%+v", err)
		return nil, err
	}
	if selectionMaterials != nil {
		for _, v := range selectionMaterials {
			secMaterial := entity.SecMaterial{
				SelectionID: selectionIdNew,
				FileUid:     v.FileUid,
				FileName:    v.FileName,
				FileUrl:     v.FileUrl,
				CreatedAt:   time.Now(),
				Type:        v.Type,
			}
			err = dao.SecMaterialDao{}.CreateSecMaterial(secMaterial)
			if err != nil {
				return nil, err
			}
		}
	}

	// 更新带货任务的免费领样策略
	freeStrategys, err := dao.FreeStrategyDao{}.GetFreeStrategyBySelectionId(selectionIdOrigin)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetFreeStrategy error,err:%+v", err)
		return nil, err
	}
	if freeStrategys != nil {
		var frees []entity.FreeStrategy
		for _, v := range freeStrategys {
			free := entity.FreeStrategy{
				SelectionId:    selectionIdNew,
				StrategyId:     v.StrategyId,
				FollowersLow:   v.FollowersLow,
				FollowersUp:    v.FollowersUp,
				SaleNum:        v.SaleNum,
				StrategyStatus: v.StrategyStatus,
				EnrollNum:      0,
				ChooseNum:      0,
			}
			frees = append(frees, free)
		}
		err = dao.FreeStrategyDao{}.CreateFreeStrategy(frees)
		if err != nil {
			return nil, err
		}
	}
	// 更新带货任务的悬赏策略
	rewardStrategys, err := dao.RewardStrategyDao{}.GetRewardStrategyBySelectionId(selectionIdOrigin)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetRewardStrategy error,err:%+v", err)
		return nil, err
	}
	if rewardStrategys != nil {
		var rewards []entity.RewardStrategy
		for _, v := range rewardStrategys {
			reward := entity.RewardStrategy{
				SelectionId:    selectionIdNew,
				Reward:         v.Reward,
				SaleActual:     v.SaleActual,
				PerReward:      v.PerReward,
				StrategyStatus: 1,
			}
			rewards = append(rewards, reward)
		}
		err = dao.RewardStrategyDao{}.CreateRewardStrategy(rewards)
		if err != nil {
			return nil, err
		}
	}

	return &selectionIdNew, nil
}

// 电商带货提交审核
func (s SelectionInfoService) SelectionToReview(param *vo.SelectionInfoUpdateParam) (*string, error) {
	selectionId := param.SelectionID
	selection, err := dao.SelectionInfoDAO{}.GetSelectionInfoById(selectionId)
	if err != nil {
		logrus.Errorf("[selectionInfoDB service] call GetSelection error,err:%+v", err)
		return nil, err
	}

	selectionName := selection.SelectionName // 任务标题
	product, err := dao.ProductDAO{}.GetProductByID(selection.ProductID)
	if err != nil {
		return nil, err
	}
	productName := product.ProductName     // 商品标题
	productDetail := product.ProductDetail // 卖点总结
	mainPhoto, err1 := dao.ProductPhotoDAO{}.GetMainPhotoByProductID(selection.ProductID)
	if err1 != nil {
		return nil, err1
	}
	var images []string
	var videos []string
	var videoJobIds []string
	var documents []string
	var documentJobIds []string
	reviewService := review_service.GetConfig()

	productPhotos, err2 := dao.ProductPhotoDAO{}.GetProductPhotoByProductID(selection.ProductID)
	if err2 != nil {
		return nil, err2
	}
	for _, productPhoto := range productPhotos {
		if productPhoto.Symbol == 2 || productPhoto.Symbol == 4 {
			images = append(images, productPhoto.PhotoUrl)
		} else if productPhoto.Symbol == 3 || productPhoto.Symbol == 5 {
			var videoJobId *string
			var reviewErr error
			i := 10
			for {
				videoJobId, reviewErr = reviewService.CheckVideo(productPhoto.PhotoUrl)
				if reviewErr == nil || i == 0 {
					break
				}
				i -= 1
			}
			if reviewErr != nil {
				return nil, reviewErr
			}
			videos = append(videos, productPhoto.PhotoUrl)
			videoJobIds = append(videoJobIds, *videoJobId)
		}
	}

	selectionBriefInfos, err := dao.SecBriefDao{}.GetSelectionBriefInfo(selectionId)
	if err != nil {
		return nil, err
	}
	for _, selectionBriefInfo := range selectionBriefInfos {
		if selectionBriefInfo.Type == 1 {
			images = append(images, selectionBriefInfo.FileUrl)
		} else if selectionBriefInfo.Type == 2 {
			var documentJobId *string
			var reviewErr error
			i := 10
			fileType := "pdf"
			parts := strings.Split(selectionBriefInfo.FileName, ".")
			if len(parts) > 1 {
				fileType = parts[len(parts)-1]
			}
			for {
				documentJobId, reviewErr = reviewService.CheckDocument(selectionBriefInfo.FileUrl, fileType)
				if reviewErr == nil || i == 0 {
					break
				}
				i -= 1
			}
			if reviewErr != nil {
				return nil, reviewErr
			}
			documents = append(documents, selectionBriefInfo.FileUrl)
			documentJobIds = append(documentJobIds, *documentJobId)
		}
	}
	selectionMaterials, err := dao.SecMaterialDao{}.GetSelectionMaterialInfo(selectionId)
	if err != nil {
		return nil, err
	}
	for _, selectionMaterial := range selectionMaterials {
		if selectionMaterial.Type == 1 {
			images = append(images, selectionMaterial.FileUrl)
		} else if selectionMaterial.Type == 2 {
			var videoJobId *string
			var reviewErr error
			i := 10
			for {
				videoJobId, reviewErr = reviewService.CheckVideo(selectionMaterial.FileUrl)
				if reviewErr == nil || i == 0 {
					break
				}
				i -= 1
			}
			if reviewErr != nil {
				return nil, reviewErr
			}
			videos = append(videos, selectionMaterial.FileUrl)
			videoJobIds = append(videoJobIds, *videoJobId)
		}
	}

	newReviewSelection := &entity.ReviewSelection{
		SelectionID:    selectionId,
		TaskName:       selectionName,
		ProductName:    productName,
		ProductDetail:  productDetail,
		MainPhoto:      mainPhoto,
		Images:         strings.Join(images, ","),
		Videos:         strings.Join(videos, ","),
		Documents:      strings.Join(documents, ","),
		VideoJobIds:    strings.Join(videoJobIds, ","),
		DocumentJobIds: strings.Join(documentJobIds, ","),
		Status:         1,
	}
	err5 := dao.SelectionReviewDao{}.Create(newReviewSelection)
	if err5 != nil {
		return nil, err5
	}

	t := time.Now()
	updateSelection := entity.SelectionInfo{
		SelectionID:     selectionId,
		SelectionStatus: 2,
		SubmitAt:        t,
		UpdatedAt:       t,
	}
	err6 := dao.SelectionInfoDAO{}.UpdateSelectionInfo(updateSelection)
	if err6 != nil {
		return nil, err
	}
	return &selectionId, nil
}

// 电商带货任务列表
func (s SelectionInfoService) GetSelectionTaskList(param *vo.SelectionSearchParam) (vo.ResultVO, error) {
	if param.Page == 0 {
		param.Page = 1
	}
	if param.PageSize == 0 {
		param.PageSize = 10
	}
	var result vo.ResultVO
	reSelectionTaskPreviews, total, err := (&dao.SelectionInfoDAO{}).GetSelectionPreviews(param)
	if err != nil {
		return result, err
	}
	for i := range reSelectionTaskPreviews {
		var createrName string
		var productName string
		var productPrice float64
		var mainImage string
		//var reward float64
		if reSelectionTaskPreviews[i].SubAccountId == 0 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(reSelectionTaskPreviews[i].EnterpriseId)
			if err == nil && enterprise != nil {
				createrName = enterprise.BusinessName
			}
		} else {
			subAccount, err := dao.SubAccountDao{}.GetSubAccount(reSelectionTaskPreviews[i].SubAccountId)
			if err == nil && subAccount != nil {
				createrName = subAccount.SubAccountName
			}
		}
		product, err := dao.ProductDAO{}.GetProductByID(reSelectionTaskPreviews[i].ProductId)
		if err == nil && product != nil {
			productName = product.ProductName
			productPrice = product.ProductPrice
		}
		mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByProductID(reSelectionTaskPreviews[i].ProductId)
		rewardStrategys, _ := dao.RewardStrategyDao{}.GetRewardStrategyBySelectionId(reSelectionTaskPreviews[i].SelectionId)
		freeStrategys, _ := dao.FreeStrategyDao{}.GetFreeStrategyBySelectionId(reSelectionTaskPreviews[i].SelectionId)
		if rewardStrategys != nil && len(rewardStrategys) > 0 {
			reSelectionTaskPreviews[i].HaveRewardStrategys = 1
		}
		if freeStrategys != nil && len(freeStrategys) > 0 {
			reSelectionTaskPreviews[i].HaveFreeStrategys = 1
		}
		//for _, rewardStrategy := range rewardStrategys {
		//	reward += rewardStrategy.Reward
		//}
		//reSelectionTaskPreviews[i].Reward = reward
		reSelectionTaskPreviews[i].CreatorName = createrName
		reSelectionTaskPreviews[i].ProductName = productName
		reSelectionTaskPreviews[i].ProductPrice = productPrice
		reSelectionTaskPreviews[i].MainImage = mainImage
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reSelectionTaskPreviews,
	}
	return result, nil
}

// 删除带货任务
func (s SelectionInfoService) DeleteSelection(selectionId string) (*string, error) {
	res, err := dao.SelectionInfoDAO{}.DeleteSelection(selectionId)
	if err != nil {
		logrus.Errorf("[selectionDB service] call DeleteSelection error,err:%+v", err)
		return res, err
	}
	return res, nil
}

// 结束带货任务
func (s SelectionInfoService) CloseSelection(selectionId string) (string, error) {
	// 任务待办：待审核、待支付、达人未处理  待发货、待签收  未传初稿、未发作品、未传数据
	selectionInfo, err := dao.SelectionInfoDAO{}.GetSelectionInfoById(selectionId)
	if err != nil {
		return "0", err
	}
	if selectionInfo == nil {
		return "0", errors.New("任务不存在")
	}
	var needProcess int64
	if selectionInfo.SelectionStatus == 6 {
		// 达人未处理 or 物流待办
		_ = dao.Db.Model(&entity.SelectionTaskInfo{}).Where("selection_id = ? and (task_status = ? or logistics_status != ?)", selectionId, 1, 3).Count(&needProcess).Error // task_status=1待选
	}
	if selectionInfo.SelectionStatus == 2 || selectionInfo.SelectionStatus == 4 || needProcess > 0 {
		// 存在待办不可结束
		return "1", nil
	} else {
		err = dao.SelectionInfoDAO{}.UpdateSelectionInfo(entity.SelectionInfo{
			SelectionID:     selectionId,
			SelectionStatus: 8,
			UpdatedAt:       time.Now(),
		})
		return "0", err
	}
}

// 电商带货选达人角标 未处理、同意合作、拒绝合作
func (s SelectionInfoService) SelectionTalentCount(selectionId string) map[string]int64 {
	res := make(map[string]int64)
	var unhandledNum int64
	var agreeNum int64
	var refuseNum int64
	dao.Db.Model(&entity.SelectionTaskInfo{}).Where("selection_id = ? AND free_stage in ?", selectionId, []int{1}).Count(&unhandledNum)
	dao.Db.Model(&entity.ProjectTaskInfo{}).Where("selection_id = ? AND free_stage in ?", selectionId, []int{3, 4, 5}).Count(&agreeNum)
	dao.Db.Model(&entity.ProjectTaskInfo{}).Where("selection_id = ? AND free_stage in ?", selectionId, []int{2}).Count(&refuseNum)
	res["unhandledNum"] = unhandledNum
	res["agreeNum"] = agreeNum
	res["refuseNum"] = refuseNum

	return res
}

// 草稿箱——电商带货
func (s SelectionInfoService) GetSelectionDraftList(param *vo.SelectionDraftParam) (vo.ResultVO, error) {
	if param.Page == 0 {
		param.Page = 1
	}
	if param.PageSize == 0 {
		param.PageSize = 10
	}
	var result vo.ResultVO
	reSelectionTaskPreviews, total, err := (&dao.SelectionInfoDAO{}).GetSelectionDraftList(param)
	if err != nil {
		return result, err
	}
	for i := range reSelectionTaskPreviews {
		var creatorName string
		var productName string
		var productPrice float64
		var mainImage string
		if reSelectionTaskPreviews[i].SubAccountId == 0 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(reSelectionTaskPreviews[i].EnterpriseId)
			if err == nil && enterprise != nil {
				creatorName = enterprise.BusinessName
			}
		} else {
			subAccount, err := dao.SubAccountDao{}.GetSubAccount(reSelectionTaskPreviews[i].SubAccountId)
			if err == nil && subAccount != nil {
				creatorName = subAccount.SubAccountName
			}
		}
		product, err := dao.ProductDAO{}.GetProductByID(reSelectionTaskPreviews[i].ProductId)
		if err == nil && product != nil {
			productName = product.ProductName
			productPrice = product.ProductPrice
		}
		mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByProductID(reSelectionTaskPreviews[i].ProductId)
		reSelectionTaskPreviews[i].CreatorName = creatorName
		reSelectionTaskPreviews[i].ProductName = productName
		reSelectionTaskPreviews[i].ProductPrice = productPrice
		reSelectionTaskPreviews[i].MainImage = mainImage
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reSelectionTaskPreviews,
	}
	return result, nil
}

// 电商带货任务待办
func (s SelectionInfoService) GetTaskToDo(enterpriseId string, subAccountId int64) (map[string]map[string]int64, error) {
	res := make(map[string]map[string]int64)
	kuaishou, err1 := dao.SelectionInfoDAO{}.GetSelectionToDo(enterpriseId, subAccountId, 4)
	if err1 != nil {
		logrus.Errorf("[GetSelectionToDo service] call GetSelectionToDo error,err:%+v", err1)
		return res, err1
	}
	all := make(map[string]int64)
	all["needReview"] = kuaishou["needReview"]
	all["needPay"] = kuaishou["needPay"]
	all["needProcess"] = kuaishou["needProcess"]
	res["kuaishou"] = kuaishou
	res["all"] = all

	return res, nil
}

// 寄样物流任务待办
func (s SelectionInfoService) GetLogisticsToDo(enterpriseId string, subAccountId int64) (map[string]map[string]int64, error) {
	res := make(map[string]map[string]int64)
	kuaishou, err1 := dao.SelectionInfoDAO{}.GetLogisticsToDo(enterpriseId, subAccountId, 4)
	if err1 != nil {
		logrus.Errorf("[GetSelectionToDo service] call GetSelectionToDo error,err:%+v", err1)
		return res, err1
	}
	all := make(map[string]int64)
	all["needDelivery"] = kuaishou["needDelivery"]
	all["needReceive"] = kuaishou["needReceive"]
	res["kuaishou"] = kuaishou
	res["all"] = all

	return res, nil
}
