package service

import (
	"errors"
	"github.com/sirupsen/logrus"
	"reflect"
	"strconv"
	"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 LocalLifeService struct{}

// 创建本地生活任务
func (s LocalLifeService) CreateLocalLife(localCreateParam *vo.LocalCreateParam) (*string, error) {
	// a) 生成本地生活项目id
	localId := strings.ReplaceAll(util.GenerateUUID(11), "-", "")
	// b) 查找关联门店信息
	product, err := dao.StoreDao{}.GetStoreByID(localCreateParam.StoreId)
	if err != nil {
		return nil, err
	}
	if product == nil {
		return nil, errors.New("未找到关联门店")
	}
	// c)创建本地生活任务
	var operatorType int64
	if localCreateParam.SubAccountId == 0 {
		operatorType = 1
	} else {
		operatorType = 2
	}
	// d) 任务截止时间
	recruitDdl, err1 := time.ParseInLocation("2006-01-02 15:04:05", localCreateParam.RecruitDdl, time.Local)
	if err1 != nil {
		return nil, errors.New("failed to parse recruitDdl")
	}
	// 获取定时任务配置id
	infoAutoTask := entity.InfoAutoTask{}
	infoAutoTask = dao.InfoAutoTaskDao{}.GetAutoTaskLast(localCreateParam.EnterpriseId)
	infoAutoDefault := entity.InfoAutoDefault{}
	infoAutoDefault = dao.InfoAutoDefaultDao{}.GetAutoDefaultLast(localCreateParam.EnterpriseId)
	t := time.Now()
	if recruitDdl.Before(t) {
		return nil, errors.New("请修改截止时间")
	}
	newLocalLife := entity.LocalLifeInfo{
		EnterpriseID:        localCreateParam.EnterpriseId,
		SubAccountID:        localCreateParam.SubAccountId,
		OperatorType:        operatorType,
		TaskStatus:          1,
		LocalID:             localId,
		LocalType:           localCreateParam.LocalType,
		LocalPlatform:       localCreateParam.Platform,
		StoreID:             localCreateParam.StoreId,
		StoreRelatedAt:      time.Now(),
		PromoteBody:         localCreateParam.PromoteBody,
		Donate:              localCreateParam.Donate,
		TeamBuyingId:        localCreateParam.TeamBuyingId,
		TeamBuyingRelatedAt: time.Now(),
		CreatedAt:           t,
		AutoTaskID:          infoAutoTask.AutoTaskID,
		AutoDefaultID:       infoAutoDefault.AutoDefaultID,
		LocalName:           localCreateParam.LocalName,
		TalentType:          localCreateParam.TalentType,
		RecruitDdl:          recruitDdl,
		TaskForm:            localCreateParam.TaskForm,
		ContentType:         localCreateParam.ContentType,
		TaskDetail:          localCreateParam.TaskDetail,
	}
	if localCreateParam.LocalType == 1 {
		newLocalLife.ServiceChargeRate = localCreateParam.ServiceChargeRate
	}
	err = dao.LocalLifeDao{}.CreateLocalLife(newLocalLife)
	if err != nil {
		return nil, err
	}

	// 4. 更新选品brief和示例（本地生活任务补充信息）
	if localCreateParam.LocalBrief != nil {
		// 插入新的brief
		for _, v := range localCreateParam.LocalBrief {
			brief := entity.LocalLifeBrief{
				LocalID:   localId,
				FileUid:   v.FileUid,
				FileName:  v.Name,
				FileUrl:   v.FileUrl,
				CreatedAt: time.Now(),
				Type:      v.Type,
			}
			err = dao.LocalLifeBriefDao{}.CreateLocalBrief(brief)
			if err != nil {
				return nil, err
			}
		}
	}

	if localCreateParam.LocalMaterial != nil {
		// 插入新的示例
		for _, v := range localCreateParam.LocalMaterial {
			material := entity.LocalLifeMaterial{
				LocalID:   localId,
				FileUid:   v.FileUid,
				FileName:  v.Name,
				FileUrl:   v.FileUrl,
				CreatedAt: time.Now(),
				Type:      v.Type,
			}
			err = dao.LocalLifeMaterialDao{}.CreateLocalMaterial(material)
			if err != nil {
				return nil, err
			}
		}
	}

	// 更新公开种草任务的招募策略
	var totalRecruitNum int64
	var estimatedCost float64
	if localCreateParam.RecruitStrategys != nil {
		// 2. 接收并创建新的招募策略
		if len(localCreateParam.RecruitStrategys) != 0 {
			var recruits []entity.RecruitStrategy
			for _, strategy := range localCreateParam.RecruitStrategys {
				if strategy.FeeForm == 2 {
					estimatedCost += float64(strategy.RecruitNumber) * strategy.Offer
				}
				recruitStrategy := entity.RecruitStrategy{
					FeeForm:       strategy.FeeForm,
					StrategyID:    strategy.StrategyID,
					FollowersLow:  strategy.FollowersLow,
					FollowersUp:   strategy.FollowersUp,
					RecruitNumber: strategy.RecruitNumber,
					ProjectID:     localId,
					StrategyType:  1,
					ServiceRate:   localCreateParam.ServiceChargeRate,
				}
				totalRecruitNum += strategy.RecruitNumber
				if strategy.FeeForm == 2 {
					recruitStrategy.Offer = strategy.Offer
					recruitStrategy.ServiceCharge = strategy.Offer * localCreateParam.ServiceChargeRate * 0.01
					recruitStrategy.TOffer = strategy.Offer * (1 - localCreateParam.ServiceChargeRate*0.01)
				}
				recruits = append(recruits, recruitStrategy)
			}
			err = dao.RecruitStrategyDao{}.CreateRecruitStrategy(recruits)
			if err != nil {
				return nil, err
			}
		}
	}
	_ = dao.LocalLifeDao{}.UpdateLocal(entity.LocalLifeInfo{LocalID: localId, EstimatedCost: estimatedCost})

	return &localId, nil
}

// 更新公开本地生活任务（招募要求、执行要求）
func (s LocalLifeService) UpdateLocal(localUpdateParam *vo.LocalUpdateParam) (*string, error) {
	// 1. 检查该项目id有无本地任务
	localID := localUpdateParam.LocalID
	localLife, err := dao.LocalLifeDao{}.GetLocalById(localID)
	if err != nil {
		return nil, err
	}
	if localLife == nil {
		return nil, errors.New("本地生活项目不存在")
	}
	recruitDdl := time.Time{} //赋零值
	recruitDdl, _ = time.ParseInLocation("2006-01-02 15:04:05", localUpdateParam.RecruitDdl, time.Local)
	if recruitDdl.Before(localLife.CreatedAt) {
		return nil, errors.New("请修改截止时间")
	}
	// 更新公开种草任务的招募策略
	var totalRecruitNum int64
	var estimatedCost float64
	if localUpdateParam.RecruitStrategys != nil {
		// 1. 删除已有的招募策略
		err = dao.RecruitStrategyDao{}.DeleteRecruitStrategyByProjectID(localUpdateParam.LocalID)
		if err != nil {
			return nil, err
		}
		// 2. 接收并创建新的招募策略
		if len(localUpdateParam.RecruitStrategys) != 0 {
			var recruits []entity.RecruitStrategy
			for _, strategy := range localUpdateParam.RecruitStrategys {
				if strategy.FeeForm == 2 {
					estimatedCost += float64(strategy.RecruitNumber) * strategy.Offer
				}
				recruitStrategy := entity.RecruitStrategy{
					FeeForm:       strategy.FeeForm,
					StrategyID:    strategy.StrategyID,
					FollowersLow:  strategy.FollowersLow,
					FollowersUp:   strategy.FollowersUp,
					RecruitNumber: strategy.RecruitNumber,
					ProjectID:     localLife.LocalID,
					StrategyType:  1,
					ServiceRate:   localLife.ServiceChargeRate,
				}
				totalRecruitNum += strategy.RecruitNumber
				if strategy.FeeForm == 2 {
					recruitStrategy.Offer = strategy.Offer
					recruitStrategy.ServiceCharge = strategy.Offer * localUpdateParam.ServiceChargeRate * 0.01
					recruitStrategy.TOffer = strategy.Offer * (1 - localUpdateParam.ServiceChargeRate*0.01)
				}
				recruits = append(recruits, recruitStrategy)
			}
			err = dao.RecruitStrategyDao{}.CreateRecruitStrategy(recruits)
			if err != nil {
				return nil, err
			}
		}
	}
	// 2. 数据准备
	//// a) 查找关联商品信息
	//product, err := dao.ProductDAO{}.GetProductByID(project.ProductID)
	//if err != nil {
	//	return nil, err
	//}
	//productPhotos, err := dao.ProductPhotoDAO{}.GetProductPhotoByProductID(project.ProductID)
	//productInfoToJson, _ := json.Marshal(product)
	//productPhotosToJson, _ := json.Marshal(productPhotos)
	// d) 任务截止时间
	//// f) 更新选品状态
	//if localUpdateParam.LocalStatus != 2 && localUpdateParam.LocalStatus != 8 {
	//	localUpdateParam.LocalStatus = 1
	//}
	t := time.Now()
	updateLocalLife := entity.LocalLifeInfo{
		StoreID:           localUpdateParam.StoreId,
		TeamBuyingId:      localUpdateParam.TeamBuyingId,
		ServiceChargeRate: localUpdateParam.ServiceChargeRate,
		PromoteBody:       localUpdateParam.PromoteBody,
		Donate:            localUpdateParam.Donate,
		//TaskStatus:        localUpdateParam.LocalStatus,
		LocalName:     localUpdateParam.LocalName,
		TalentType:    localUpdateParam.TalentType,
		RecruitDdl:    recruitDdl,
		TaskForm:      localUpdateParam.TaskForm,
		ContentType:   localUpdateParam.ContentType,
		TaskDetail:    localUpdateParam.TaskDetail,
		UpdatedAt:     t,
		EstimatedCost: estimatedCost,
	}
	//if localUpdateParam.LocalStatus == 2 {
	//	updateLocalLife.SubmitAt = t
	//}
	// 合并传入参数和数据表中原记录，若传入参数字段值为空，则将字段赋值为原记录中值
	result := util.MergeStructValue(&updateLocalLife, localLife)
	// 利用反射机制将interface类型转换为结构体类型
	v := reflect.ValueOf(&result).Elem()
	if v.Kind() == reflect.Struct {
		updateLocalLife = v.Interface().(entity.LocalLifeInfo)
		//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.LocalLifeDao{}.UpdateLocal(updateLocalLife)
	if err != nil {
		return nil, err
	}
	// 4. 更新选品brief和示例（本地生活任务补充信息）
	if localUpdateParam.LocalBrief != nil {
		// 删除已有brief
		err = dao.LocalLifeBriefDao{}.DeleteLocalBriefByLocalId(localLife.LocalID)
		if err != nil {
			return nil, err
		}
		// 插入新的brief
		for _, v := range localUpdateParam.LocalBrief {
			brief := entity.LocalLifeBrief{
				LocalID:   localLife.LocalID,
				FileUid:   v.FileUid,
				FileName:  v.Name,
				FileUrl:   v.FileUrl,
				CreatedAt: time.Now(),
				Type:      v.Type,
			}
			err = dao.LocalLifeBriefDao{}.CreateLocalBrief(brief)
			if err != nil {
				return nil, err
			}
		}
	}

	if localUpdateParam.LocalMaterial != nil {
		// 删除已有示例
		err = dao.LocalLifeMaterialDao{}.DeleteLocalMaterialByLocalId(localLife.LocalID)
		if err != nil {
			return nil, err
		}
		// 插入新的示例
		for _, v := range localUpdateParam.LocalMaterial {
			material := entity.LocalLifeMaterial{
				LocalID:   localLife.LocalID,
				FileUid:   v.FileUid,
				FileName:  v.Name,
				FileUrl:   v.FileUrl,
				CreatedAt: time.Now(),
				Type:      v.Type,
			}
			err = dao.LocalLifeMaterialDao{}.CreateLocalMaterial(material)
			if err != nil {
				return nil, err
			}
		}
	}

	return &updateLocalLife.LocalID, nil
}

// 更新定向本地生活任务（招募要求、执行要求）
func (s LocalLifeService) UpdateLocalTarget(localUpdateParam *vo.LocalUpdateParam) (*string, error) {
	// 1. 检查该项目id有无本地任务
	localID := localUpdateParam.LocalID
	localLife, err := dao.LocalLifeDao{}.GetLocalById(localID)
	if err != nil {
		return nil, err
	}
	if localLife == nil {
		return nil, errors.New("本地生活项目不存在")
	}
	println("更新定向本地生活任务的招募策略")
	// 更新公开种草任务的招募策略
	var totalRecruitNum int64
	var estimatedCost float64
	if localUpdateParam.RecruitStrategys != nil {
		// 1. 删除已有的招募策略
		err = dao.RecruitStrategyDao{}.DeleteRecruitStrategyByProjectID(localUpdateParam.LocalID)
		if err != nil {
			return nil, err
		}
		// 2. 接收并创建新的招募策略
		if len(localUpdateParam.RecruitStrategys) != 0 {
			var recruits []entity.RecruitStrategy
			for _, strategy := range localUpdateParam.RecruitStrategys {
				if strategy.FeeForm == 2 {
					estimatedCost += float64(strategy.RecruitNumber) * strategy.Offer
				}
				recruitStrategy := entity.RecruitStrategy{
					FeeForm:       strategy.FeeForm,
					StrategyID:    strategy.StrategyID,
					FollowersLow:  strategy.FollowersLow,
					FollowersUp:   strategy.FollowersUp,
					RecruitNumber: strategy.RecruitNumber,
					ProjectID:     localLife.LocalID,
					StrategyType:  1,
					ServiceRate:   localLife.ServiceChargeRate,
				}
				totalRecruitNum += strategy.RecruitNumber
				if strategy.FeeForm == 2 {
					recruitStrategy.Offer = strategy.Offer // 报价
				}
				recruits = append(recruits, recruitStrategy)
			}
			err = dao.RecruitStrategyDao{}.CreateRecruitStrategy(recruits)
			if err != nil {
				return nil, err
			}
		}
	}
	// 2. 数据准备
	// a) 查找关联商品信息
	//product, err := dao.ProductDAO{}.GetProductByID(project.ProductID)
	//if err != nil {
	//	return nil, err
	//}
	//productPhotos, err := dao.ProductPhotoDAO{}.GetProductPhotoByProductID(project.ProductID)
	//productInfoToJson, _ := json.Marshal(product)
	//productPhotosToJson, _ := json.Marshal(productPhotos)
	// d) 任务截止时间
	recruitDdl := time.Time{} //赋零值
	recruitDdl, _ = time.ParseInLocation("2006-01-02 15:04:05", localUpdateParam.RecruitDdl, time.Local)
	//// f) 更新选品状态
	//if localUpdateParam.LocalStatus != 2 && localUpdateParam.LocalStatus != 8 {
	//	localUpdateParam.LocalStatus = 1
	//}
	t := time.Now()
	updateLocalLife := entity.LocalLifeInfo{
		StoreID:           localUpdateParam.StoreId,
		TeamBuyingId:      localUpdateParam.TeamBuyingId,
		ServiceChargeRate: localUpdateParam.ServiceChargeRate,
		PromoteBody:       localUpdateParam.PromoteBody,
		Donate:            localUpdateParam.Donate,
		//TaskStatus:        localUpdateParam.LocalStatus,
		LocalName:     localUpdateParam.LocalName,
		TalentType:    localUpdateParam.TalentType,
		RecruitDdl:    recruitDdl,
		TaskForm:      localUpdateParam.TaskForm,
		ContentType:   localUpdateParam.ContentType,
		TaskDetail:    localUpdateParam.TaskDetail,
		UpdatedAt:     t,
		Tools:         localUpdateParam.Tools,
		EstimatedCost: estimatedCost,
	}
	//if localUpdateParam.LocalStatus == 2 {
	//	updateLocalLife.SubmitAt = t
	//}
	// 合并传入参数和数据表中原记录，若传入参数字段值为空，则将字段赋值为原记录中值
	result := util.MergeStructValue(&updateLocalLife, localLife)
	// 利用反射机制将interface类型转换为结构体类型
	v := reflect.ValueOf(&result).Elem()
	if v.Kind() == reflect.Struct {
		updateLocalLife = v.Interface().(entity.LocalLifeInfo)
		//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.LocalLifeDao{}.UpdateLocal(updateLocalLife)
	if err != nil {
		return nil, err
	}
	// 4. 更新选品brief和示例（本地生活任务补充信息）
	if localUpdateParam.LocalBrief != nil {
		// 删除已有brief
		err = dao.ProjectBriefDao{}.DeleteSecBriefBySelectionId(localLife.LocalID)
		if err != nil {
			return nil, err
		}
		// 插入新的brief
		for _, v := range localUpdateParam.LocalBrief {
			brief := entity.ProjectBrief{
				ProjectID: localLife.LocalID,
				FileUid:   v.FileUid,
				FileName:  v.Name,
				FileUrl:   v.FileUrl,
				CreatedAt: time.Now(),
				Type:      v.Type,
			}
			err = dao.ProjectBriefDao{}.CreateProjectBrief(brief)
			if err != nil {
				return nil, err
			}
		}
	}

	if localUpdateParam.LocalMaterial != nil {
		// 删除已有示例
		err = dao.ProjectMaterialDao{}.DeleteProjectMaterialByProjectId(localLife.LocalID)
		if err != nil {
			return nil, err
		}
		// 插入新的示例
		for _, v := range localUpdateParam.LocalMaterial {
			projectMaterial := entity.ProjectMaterial{
				ProjectID: localLife.LocalID,
				FileUid:   v.FileUid,
				FileName:  v.Name,
				FileUrl:   v.FileUrl,
				CreatedAt: time.Now(),
				Type:      v.Type,
			}
			err = dao.ProjectMaterialDao{}.CreateProjectMaterial(projectMaterial)
			if err != nil {
				return nil, err
			}
		}
	}

	return &updateLocalLife.LocalID, nil
}

// 本地生活任务预览
func (s LocalLifeService) GetLocalLifeDetail(localId string) (*vo.ReLocalDetail, error) {
	reLocalDetail := vo.ReLocalDetail{}
	localLife, err := dao.LocalLifeDao{}.GetLocalById(localId)
	if err != nil {
		logrus.Errorf("[localLifeDB service] call GetLocalById error,err:%+v", err)
		return nil, err
	}
	// 系统信息
	reLocalDetail.LocalName = localLife.LocalName
	reLocalDetail.LocalId = localId
	reLocalDetail.LocalStatus = localLife.TaskStatus
	reLocalDetail.LocalPlatform = localLife.LocalPlatform
	reLocalDetail.CreatedAt = localLife.CreatedAt.Format("2006-01-02 15:04:05")
	if localLife.TaskStatus < 6 {
		reLocalDetail.EstimatedCost = localLife.EstimatedCost
	} else {
		reLocalDetail.EstimatedCost = localLife.NeedPay
	}
	reLocalDetail.ServiceChargeRate = localLife.ServiceChargeRate
	var creatorName, phone string
	if localLife.OperatorType == 1 && localLife.SubAccountID == 0 {
		enterprise, err := dao.EnterpriseDao{}.GetEnterprise(localLife.EnterpriseID)
		if err == nil && enterprise != nil {
			creatorName = enterprise.BusinessName
			phone, err = dao.UserDao{}.GetPhoneByUserId(enterprise.UserId)
		}
	} else if localLife.OperatorType == 1 && localLife.SubAccountID != 0 {
		subAccount, err := dao.SubAccountDao{}.GetSubAccount(localLife.SubAccountID)
		if err == nil && subAccount != nil {
			creatorName = subAccount.SubAccountName
			phone, err = dao.UserDao{}.GetPhoneByUserId(subAccount.UserId)
		}
	}
	reLocalDetail.CreatorName = creatorName
	reLocalDetail.Phone = phone
	// 关联主体
	var reStore vo.ReStorePreview
	store, err := dao.StoreDao{}.GetStoreByID(localLife.StoreID)
	if err == nil {
		photoUrl, e := dao.ProductPhotoDAO{}.GetMainPhotoByStoreID(store.StoreID)
		if e != nil {
			photoUrl = ""
		}
		reStore = vo.ReStorePreview{
			StoreID:       store.StoreID,
			StoreName:     store.StoreName,
			StoreLocation: store.StoreLocation,
			StoreCategory: store.StoreCategory,
			TeamNum:       store.TeamNum,
			StoreDetail:   store.StoreDetail,
			CreatedAt:     store.CreatedAt.Format("2006-01-02 15:04:05"),
			PhotoUrl:      photoUrl,
		}
	}
	reLocalDetail.StoreInfo = &reStore
	var reTeamBuying vo.ReTeamBuyingPreview
	teamBuying, err := dao.TeamBuyingDao{}.GetTeamBuyingByID(localLife.TeamBuyingId)
	if err == nil {
		photoUrl, e := dao.ProductPhotoDAO{}.GetMainPhotoByTeamBuyingID(teamBuying.TeamBuyingID)
		if e != nil {
			photoUrl = ""
		}
		reTeamBuying = vo.ReTeamBuyingPreview{
			TeamBuyingID:       teamBuying.TeamBuyingID,
			TeamBuyingName:     teamBuying.TeamBuyingName,
			TeamBuyingPrice:    teamBuying.TeamBuyingPrice,
			TeamBuyingCategory: teamBuying.TeamBuyingCategory,
			TeamBuyingDetail:   teamBuying.TeamBuyingDetail,
			CreatedAt:          teamBuying.CreatedAt.Format("2006-01-02 15:04:05"),
			PhotoUrl:           photoUrl,
		}
	}
	reLocalDetail.TeamBuyingInfo = &reTeamBuying
	reLocalDetail.PromoteBody = localLife.PromoteBody
	reLocalDetail.Donate = localLife.Donate
	// 招募要求
	reLocalDetail.TalentType = localLife.TalentType
	reLocalDetail.RecruitDdl = localLife.RecruitDdl.Format("2006-01-02 15:04:05")

	var recruitStrategysPreviews []*vo.LocalRecruitStrategy
	recruitStrategys, err := dao.RecruitStrategyDao{}.GetRecruitStrategyByProjectId(localId)
	if err != nil {
		logrus.Errorf("[localLifeDB service] call GetRecruitStrategy error,err:%+v", err)
		return nil, err
	}
	for _, recruitStrategy := range recruitStrategys {
		recruitStrategysPreview := &vo.LocalRecruitStrategy{
			StrategyId:     recruitStrategy.StrategyID,
			FeeForm:        recruitStrategy.FeeForm,
			FollowersLow:   recruitStrategy.FollowersLow,
			FollowersUp:    recruitStrategy.FollowersUp,
			RecruitNumber:  recruitStrategy.RecruitNumber,
			Offer:          recruitStrategy.Offer,
			TOffer:         recruitStrategy.TOffer,
			ServiceCharge:  recruitStrategy.ServiceCharge,
			SelectedNumber: recruitStrategy.SelectedNumber,
			TotalOffer:     recruitStrategy.TotalOffer,
		}
		recruitStrategysPreviews = append(recruitStrategysPreviews, recruitStrategysPreview)
	}
	reLocalDetail.RecruitStrategys = recruitStrategysPreviews
	// 执行要求
	reLocalDetail.TaskForm = localLife.TaskForm
	reLocalDetail.ContentType = localLife.ContentType
	reLocalDetail.TaskDetail = localLife.TaskDetail
	taskBriefInfos, err := dao.LocalLifeBriefDao{}.GetLocalBriefInfo(localId)
	if err != nil {
		logrus.Errorf("[localLifeDB service] call GetProjectBriefInfo error,err:%+v", err)
		return nil, err
	}
	taskMaterials, err := dao.LocalLifeMaterialDao{}.GetLocalMaterialInfo(localId)
	if err != nil {
		logrus.Errorf("[localLifeDB service] call GetprojectMaterialInfo error,err:%+v", err)
		return nil, err
	}
	reLocalDetail.TaskBriefs = taskBriefInfos
	reLocalDetail.TaskMaterials = taskMaterials
	reLocalDetail.Tools = localLife.Tools

	return &reLocalDetail, nil
}

// 复制本地生活任务
func (s LocalLifeService) CopyLocalLife(param *vo.LocalSearchParam) (*string, error) {
	localLifeOrigin, err := dao.LocalLifeDao{}.GetLocalById(param.LocalId)
	if err != nil {
		logrus.Errorf("[localLifeDB service] call GetLocalById error,err:%+v", err)
		return nil, err
	}
	if localLifeOrigin == nil {
		return nil, errors.New("任务不存在")
	}
	localIdOrigin := localLifeOrigin.LocalID
	localIdNew := strings.ReplaceAll(util.GenerateUUID(11), "-", "")
	t := time.Now()
	// 获取定时任务配置id
	infoAutoTask := entity.InfoAutoTask{}
	infoAutoTask = dao.InfoAutoTaskDao{}.GetAutoTaskLast(param.EnterpriseId)
	infoAutoDefault := entity.InfoAutoDefault{}
	infoAutoDefault = dao.InfoAutoDefaultDao{}.GetAutoDefaultLast(param.EnterpriseId)

	// 复制任务
	localLifeNew := entity.LocalLifeInfo{
		EnterpriseID:        param.EnterpriseId,
		SubAccountID:        param.SubAccountId,
		OperatorType:        localLifeOrigin.OperatorType,
		TaskStatus:          1,
		LocalID:             localIdNew,
		LocalType:           localLifeOrigin.LocalType,
		LocalPlatform:       localLifeOrigin.LocalPlatform,
		StoreID:             localLifeOrigin.StoreID,
		StoreRelatedAt:      t,
		PromoteBody:         localLifeOrigin.PromoteBody,
		Donate:              localLifeOrigin.Donate,
		TeamBuyingId:        localLifeOrigin.TeamBuyingId,
		TeamBuyingRelatedAt: t,
		CreatedAt:           t,
		AutoTaskID:          infoAutoTask.AutoTaskID,
		AutoDefaultID:       infoAutoDefault.AutoDefaultID,
		LocalName:           localLifeOrigin.LocalName,
		TalentType:          localLifeOrigin.TalentType,
		RecruitDdl:          localLifeOrigin.RecruitDdl,
		TaskForm:            localLifeOrigin.TaskForm,
		ContentType:         localLifeOrigin.ContentType,
		TaskDetail:          localLifeOrigin.TaskDetail,
		ServiceChargeRate:   localLifeOrigin.ServiceChargeRate,
		EstimatedCost:       localLifeOrigin.EstimatedCost,
	}
	err = dao.LocalLifeDao{}.CreateLocalLife(localLifeNew)
	if err != nil {
		return nil, err
	}

	// 更新选品brief和示例（本地生活任务补充信息）
	localBriefInfos, err := dao.LocalLifeBriefDao{}.GetLocalBriefInfo(localIdOrigin)
	if err != nil {
		logrus.Errorf("[projectDB service] call GetLocalBriefInfo error,err:%+v", err)
		return nil, err
	}
	if localBriefInfos != nil {
		for _, v := range localBriefInfos {
			brief := entity.LocalLifeBrief{
				LocalID:   localIdNew,
				FileUid:   v.FileUid,
				FileName:  v.FileName,
				FileUrl:   v.FileUrl,
				CreatedAt: time.Now(),
				Type:      v.Type,
			}
			err = dao.LocalLifeBriefDao{}.CreateLocalBrief(brief)
			if err != nil {
				return nil, err
			}
		}
	}
	localMaterials, err := dao.LocalLifeMaterialDao{}.GetLocalMaterialInfo(localIdOrigin)
	if err != nil {
		logrus.Errorf("[projectDB service] call GetLocalMaterialInfo error,err:%+v", err)
		return nil, err
	}
	if localMaterials != nil {
		for _, v := range localMaterials {
			material := entity.LocalLifeMaterial{
				LocalID:   localIdNew,
				FileUid:   v.FileUid,
				FileName:  v.FileName,
				FileUrl:   v.FileUrl,
				CreatedAt: time.Now(),
				Type:      v.Type,
			}
			err = dao.LocalLifeMaterialDao{}.CreateLocalMaterial(material)
			if err != nil {
				return nil, err
			}
		}
	}

	// 更新本地生活任务的招募策略
	recruitStrategys, err := dao.RecruitStrategyDao{}.GetRecruitStrategyByProjectId(localIdOrigin)
	if err != nil {
		logrus.Errorf("[localLifeDB service] call GetRecruitStrategy error,err:%+v", err)
		return nil, err
	}
	var totalRecruitNum int64
	if recruitStrategys != nil {
		// 2. 接收并创建新的招募策略
		if len(recruitStrategys) != 0 {
			var recruits []entity.RecruitStrategy
			for _, strategy := range recruitStrategys {
				recruitStrategy := entity.RecruitStrategy{
					FeeForm:       strategy.FeeForm,
					StrategyID:    strategy.StrategyID,
					FollowersLow:  strategy.FollowersLow,
					FollowersUp:   strategy.FollowersUp,
					RecruitNumber: strategy.RecruitNumber,
					ProjectID:     localIdNew,
					StrategyType:  strategy.StrategyType,
					ServiceRate:   strategy.ServiceRate,
					Offer:         strategy.Offer,
					ServiceCharge: strategy.ServiceCharge,
					TOffer:        strategy.TOffer,
				}
				totalRecruitNum += strategy.RecruitNumber
				recruits = append(recruits, recruitStrategy)
			}
			err = dao.RecruitStrategyDao{}.CreateRecruitStrategy(recruits)
			if err != nil {
				return nil, err
			}
		}
	}

	return &localIdNew, nil
}

// 本地生活提交审核
func (s LocalLifeService) LocalLifeToReview(localUpdateParam *vo.LocalUpdateParam) (*string, error) {
	localId := localUpdateParam.LocalID

	local, err := dao.LocalLifeDao{}.GetLocalById(localId)
	if err != nil {
		logrus.Errorf("[projectInfoDB service] call GetProject error,err:%+v", err)
		return nil, err
	}

	localName := local.LocalName    // 任务标题
	localDetail := local.TaskDetail // 任务详情
	store, err := dao.StoreDao{}.GetStoreByID(local.StoreID)
	if err != nil {
		return nil, err
	}
	storeName := store.StoreName     // 门店名称
	storeDetail := store.StoreDetail // 门店特点
	storeMainPhoto, err1 := dao.ProductPhotoDAO{}.GetMainPhotoByStoreID(store.StoreID)
	if err1 != nil {
		return nil, err1
	}
	teamBuying, err2 := dao.TeamBuyingDao{}.GetTeamBuyingByID(local.TeamBuyingId)
	if err2 != nil {
		return nil, err2
	}
	teamBuyingName := teamBuying.TeamBuyingName     // 团购标题
	teamBuyingDetail := teamBuying.TeamBuyingDetail // 团购详情
	teamBuyingMainPhoto, err3 := dao.ProductPhotoDAO{}.GetMainPhotoByTeamBuyingID(teamBuying.TeamBuyingID)
	if err3 != nil {
		return nil, err3
	}
	var images []string
	var videos []string
	var videoJobIds []string
	var documents []string
	var documentJobIds []string
	reviewService := review_service.GetConfig()

	storePhotos, err4 := dao.ProductPhotoDAO{}.GetProductPhotoByStoreID(local.StoreID)
	if err4 != nil {
		return nil, err4
	}
	for _, storePhoto := range storePhotos {
		if storePhoto.Symbol == 2 || storePhoto.Symbol == 4 {
			images = append(images, storePhoto.PhotoUrl)
		} else if storePhoto.Symbol == 3 || storePhoto.Symbol == 5 {
			var videoJobId *string
			var reviewErr error
			i := 10
			for {
				videoJobId, reviewErr = reviewService.CheckVideo(storePhoto.PhotoUrl)
				if reviewErr == nil || i == 0 {
					break
				}
				i -= 1
			}
			if reviewErr != nil {
				return nil, reviewErr
			}
			videos = append(videos, storePhoto.PhotoUrl)
			videoJobIds = append(videoJobIds, *videoJobId)
		}
	}
	teamBuyingPhotos, err5 := dao.ProductPhotoDAO{}.GetProductPhotoByTeamBuyingID(local.TeamBuyingId)
	if err5 != nil {
		return nil, err5
	}
	for _, teamBuyingPhoto := range teamBuyingPhotos {
		if teamBuyingPhoto.Symbol == 2 || teamBuyingPhoto.Symbol == 4 {
			images = append(images, teamBuyingPhoto.PhotoUrl)
		} else if teamBuyingPhoto.Symbol == 3 || teamBuyingPhoto.Symbol == 5 {
			var videoJobId *string
			var reviewErr error
			i := 10
			for {
				videoJobId, reviewErr = reviewService.CheckVideo(teamBuyingPhoto.PhotoUrl)
				if reviewErr == nil || i == 0 {
					break
				}
				i -= 1
			}
			if reviewErr != nil {
				return nil, reviewErr
			}
			videos = append(videos, teamBuyingPhoto.PhotoUrl)
			videoJobIds = append(videoJobIds, *videoJobId)
		}
	}

	localBriefInfos, err6 := dao.LocalLifeBriefDao{}.GetLocalBriefInfo(localId)
	if err6 != nil {
		return nil, err6
	}
	for _, localBriefInfo := range localBriefInfos {
		if localBriefInfo.Type == 1 {
			images = append(images, localBriefInfo.FileUrl)
		} else if localBriefInfo.Type == 2 {
			var documentJobId *string
			var reviewErr error
			i := 10
			fileType := "pdf"
			parts := strings.Split(localBriefInfo.FileName, ".")
			if len(parts) > 1 {
				fileType = parts[len(parts)-1]
			}
			for {
				documentJobId, reviewErr = reviewService.CheckDocument(localBriefInfo.FileUrl, fileType)
				if reviewErr == nil || i == 0 {
					break
				}
				i -= 1
			}
			if reviewErr != nil {
				return nil, reviewErr
			}
			documents = append(documents, localBriefInfo.FileUrl)
			documentJobIds = append(documentJobIds, *documentJobId)
		}
	}
	localMaterials, err7 := dao.LocalLifeMaterialDao{}.GetLocalMaterialInfo(localId)
	if err7 != nil {
		return nil, err7
	}
	for _, localMaterial := range localMaterials {
		if localMaterial.Type == 1 {
			images = append(images, localMaterial.FileUrl)
		} else if localMaterial.Type == 2 {
			var videoJobId *string
			var reviewErr error
			i := 10
			for {
				videoJobId, reviewErr = reviewService.CheckVideo(localMaterial.FileUrl)
				if reviewErr == nil || i == 0 {
					break
				}
				i -= 1
			}
			if reviewErr != nil {
				return nil, reviewErr
			}
			videos = append(videos, localMaterial.FileUrl)
			videoJobIds = append(videoJobIds, *videoJobId)
		}
	}

	newReviewLocal := &entity.ReviewLocalLife{
		LocalID:             localId,
		TaskName:            localName,
		TaskDetail:          localDetail,
		StoreMainPhoto:      storeMainPhoto,
		StoreName:           storeName,
		StoreDetail:         storeDetail,
		TeamBuyingMainPhoto: teamBuyingMainPhoto,
		TeamBuyingName:      teamBuyingName,
		TeamBuyingDetail:    teamBuyingDetail,
		Images:              strings.Join(images, ","),
		Videos:              strings.Join(videos, ","),
		Documents:           strings.Join(documents, ","),
		VideoJobIds:         strings.Join(videoJobIds, ","),
		DocumentJobIds:      strings.Join(documentJobIds, ","),
		Status:              1,
	}
	err8 := dao.LocalLifeReviewDao{}.Create(newReviewLocal)
	if err8 != nil {
		return nil, err8
	}

	t := time.Now()
	updateLocal := entity.LocalLifeInfo{
		LocalID:    localId,
		TaskStatus: 2,
		SubmitAt:   t,
		UpdatedAt:  t,
	}
	err9 := dao.LocalLifeDao{}.UpdateLocal(updateLocal)
	if err9 != nil {
		return nil, err9
	}
	return &localId, nil
}

// 本地生活任务列表
func (s LocalLifeService) GetLocalLifeTaskList(param *vo.LocalSearchParam) (vo.ResultVO, error) {
	if param.Page == 0 {
		param.Page = 1
	}
	if param.PageSize == 0 {
		param.PageSize = 10
	}
	var result vo.ResultVO
	reLocalTaskPreviews, total, err := (&dao.LocalLifeDao{}).GetLocalPreviews(param)
	if err != nil {
		return result, err
	}
	for i := range reLocalTaskPreviews {
		var creatorName string
		var storeName string
		var storeLocation string
		var mainImage string
		if reLocalTaskPreviews[i].SubAccountId == 0 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(reLocalTaskPreviews[i].EnterpriseId)
			if err == nil && enterprise != nil {
				creatorName = enterprise.BusinessName
			}
		} else {
			subAccount, err := dao.SubAccountDao{}.GetSubAccount(reLocalTaskPreviews[i].SubAccountId)
			if err == nil && subAccount != nil {
				creatorName = subAccount.SubAccountName
			}
		}
		store, err := dao.StoreDao{}.GetStoreByID(reLocalTaskPreviews[i].StoreId)
		if err == nil && store != nil {
			storeName = store.StoreName
			storeLocation = store.StoreLocation
		}
		mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByStoreID(reLocalTaskPreviews[i].StoreId)
		reLocalTaskPreviews[i].CreatorName = creatorName
		reLocalTaskPreviews[i].StoreName = storeName
		reLocalTaskPreviews[i].StoreLocation = storeLocation
		reLocalTaskPreviews[i].MainImage = mainImage
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reLocalTaskPreviews,
	}
	return result, nil
}

// 删除本地生活任务
func (s LocalLifeService) DeleteLocalLife(localId string) (*string, error) {
	res, err := dao.LocalLifeDao{}.DeleteLocalLife(localId)
	if err != nil {
		logrus.Errorf("[DeleteLocalLife service] call DeleteLocalLife error,err:%+v", err)
		return res, err
	}
	return res, nil
}

// 结束本地生活任务
func (s LocalLifeService) CloseLocalLife(localId string) (string, error) {
	// 任务待办：待审核、待支付、达人未处理、初稿待审、链接待审、待结算  (待发货、待签收)  达人待预约探店时间、探店时间待确认、达人待探店  未传初稿、未发作品、未传数据
	// 合作待办：可邀约、邀约中、合作中
	localLife, err := dao.LocalLifeDao{}.GetLocalById(localId)
	if err != nil {
		return "0", err
	}
	if localLife == nil {
		return "0", errors.New("任务不存在")
	}
	var needProcess int64
	if localLife.TaskStatus == 4 || localLife.TaskStatus == 8 {
		// 达人未处理 or 物流待办 or 初稿待审、链接待审、待结算
		_ = dao.Db.Model(&entity.LocalLifeTaskInfo{}).Where("local_id = ? and (task_status = ? or task_stage < ?)", localId, 1, 15).Count(&needProcess).Error // task_status=1待选
	}
	if localLife.TaskStatus == 2 || localLife.TaskStatus == 4 || needProcess > 0 {
		// 存在待办不可结束
		return "1", nil
	} else {
		err := dao.LocalLifeDao{}.UpdateLocal(entity.LocalLifeInfo{
			LocalID:    localId,
			TaskStatus: 10,
			UpdatedAt:  time.Now(),
		})
		return "0", err
	}
}

// 草稿箱——本地生活
func (s LocalLifeService) GetLocalLifeDraftList(param *vo.LocalDraftParam) (vo.ResultVO, error) {
	if param.Page == 0 {
		param.Page = 1
	}
	if param.PageSize == 0 {
		param.PageSize = 10
	}
	var result vo.ResultVO
	reLocalTaskPreviews, total, err := (&dao.LocalLifeDao{}).GetLocalDraftList(param)
	if err != nil {
		return result, err
	}
	for i := range reLocalTaskPreviews {
		var creatorName string
		var storeName string
		var storeLocation string
		var mainImage string
		if reLocalTaskPreviews[i].SubAccountId == 0 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(reLocalTaskPreviews[i].EnterpriseId)
			if err == nil && enterprise != nil {
				creatorName = enterprise.BusinessName
			}
		} else {
			subAccount, err := dao.SubAccountDao{}.GetSubAccount(reLocalTaskPreviews[i].SubAccountId)
			if err == nil && subAccount != nil {
				creatorName = subAccount.SubAccountName
			}
		}
		store, err := dao.StoreDao{}.GetStoreByID(reLocalTaskPreviews[i].StoreId)
		if err == nil && store != nil {
			storeName = store.StoreName
			storeLocation = store.StoreLocation
		}
		mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByStoreID(reLocalTaskPreviews[i].StoreId)
		reLocalTaskPreviews[i].CreatorName = creatorName
		reLocalTaskPreviews[i].StoreName = storeName
		reLocalTaskPreviews[i].StoreLocation = storeLocation
		reLocalTaskPreviews[i].MainImage = mainImage
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reLocalTaskPreviews,
	}
	return result, nil
}

// 探店本地生活列表
func (s LocalLifeService) GetStoreExploreList(param *vo.LocalSearchParam) (vo.ResultVO, error) {
	if param.Page == 0 {
		param.Page = 1
	}
	if param.PageSize == 0 {
		param.PageSize = 10
	}
	var result vo.ResultVO
	reLocalStoreExplorePreviews, total, err := (&dao.LocalLifeDao{}).GetLocalStoreExplorePreviews(param)
	if err != nil {
		return result, err
	}
	for i := range reLocalStoreExplorePreviews {
		var creatorName string
		var storeName string
		var storeLocation string
		var mainImage string
		if reLocalStoreExplorePreviews[i].SubAccountId == 0 {
			enterprise, err := dao.EnterpriseDao{}.GetEnterprise(reLocalStoreExplorePreviews[i].EnterpriseId)
			if err == nil && enterprise != nil {
				creatorName = enterprise.BusinessName
			}
		} else {
			subAccount, err := dao.SubAccountDao{}.GetSubAccount(reLocalStoreExplorePreviews[i].SubAccountId)
			if err == nil && subAccount != nil {
				creatorName = subAccount.SubAccountName
			}
		}
		store, err := dao.StoreDao{}.GetStoreByID(reLocalStoreExplorePreviews[i].StoreId)
		if err == nil && store != nil {
			storeName = store.StoreName
			storeLocation = store.StoreLocation
		}
		mainImage, err = dao.ProductPhotoDAO{}.GetMainPhotoByStoreID(reLocalStoreExplorePreviews[i].StoreId)
		reLocalStoreExplorePreviews[i].CreatorName = creatorName
		reLocalStoreExplorePreviews[i].StoreName = storeName
		reLocalStoreExplorePreviews[i].StoreLocation = storeLocation
		reLocalStoreExplorePreviews[i].MainImage = mainImage
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reLocalStoreExplorePreviews,
	}
	return result, nil
}

// 探店达人详情
func (s LocalLifeService) GetStoreExploreInfo(param *vo.StoreExploreParam) (*vo.ResultVO, error) {
	if param.Page <= 0 {
		param.Page = 1
	}
	if param.PageSize <= 0 {
		param.PageSize = 10
	}
	var reStoreExploreTalents []*vo.ReStoreExploreTalent
	var total int64
	result := vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reStoreExploreTalents,
	}
	var localLifeTaskInfos []*entity.LocalLifeTaskInfo
	var err error
	localLifeId := param.LocalLifeId
	if param.Status == 1 { // 待预约
		localLifeTaskInfos, total, err = dao.LocalLifeTaskInfoDao{}.GetListByTaskStage(localLifeId, 1, "", param.Page, param.PageSize)
	} else if param.Status == 2 { // 待确认
		localLifeTaskInfos, total, err = dao.LocalLifeTaskInfoDao{}.GetListByTaskStage(localLifeId, 2, param.SearchTime, param.Page, param.PageSize)
	} else if param.Status == 3 { // 待探店
		localLifeTaskInfos, total, err = dao.LocalLifeTaskInfoDao{}.GetListByTaskStage(localLifeId, 5, param.SearchTime, param.Page, param.PageSize)
	} else if param.Status == 4 { // 已探店
		localLifeTaskInfos, total, err = dao.LocalLifeTaskInfoDao{}.GetListByTaskStage(localLifeId, 6, param.SearchTime, param.Page, param.PageSize)
	}
	if err != nil {
		return nil, err
	}
	for _, localLifeTaskInfo := range localLifeTaskInfos {
		// 获取达人信息
		talentInfo, err := dao.TalentInfoDao{}.SelectTalentInfo(localLifeTaskInfo.TalentID)
		if err != nil {
			return nil, err
		}
		//regionName, err := dao.RegionInfoDao{}.SelectRegion(talentInfo.VisitStoreRegion)
		//if err != nil {
		//	regionName = ""
		//}
		regionName := localLifeTaskInfo.City
		talentPreview := &vo.TalentPreview{
			TalentId:    localLifeTaskInfo.TalentID,
			TalentPhoto: talentInfo.Avatar,
			TalentName:  talentInfo.TalentWxNickname,
			Account:     "",
			Location:    regionName,
			Gender:      talentInfo.Sex,
		}
		reStoreExploreTalent := &vo.ReStoreExploreTalent{
			ReTalentPreview: talentPreview,
			TaskId:          localLifeTaskInfo.TaskID,
		}
		if param.Status == 1 {
			reStoreExploreTalent.CooperateTime = localLifeTaskInfo.SelectDate.Format("2006-01-02 15:04:05")
		} else if param.Status == 2 {
			reStoreExploreTalent.ReserveTime = localLifeTaskInfo.ReserveTime.Format("2006-01-02 15:04:05")
		} else if param.Status == 3 {
			reStoreExploreTalent.ExploreTime = localLifeTaskInfo.ExploreTime.Format("2006-01-02 15:04:05")
			reStoreExploreTalent.Operator = ""
		} else if param.Status == 4 {
			reStoreExploreTalent.FinishExploreTime = localLifeTaskInfo.FinishExploreTime.Format("2006-01-02 15:04:05")
			reStoreExploreTalent.Operator = ""
		}
		reStoreExploreTalents = append(reStoreExploreTalents, reStoreExploreTalent)
	}
	result = vo.ResultVO{
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    total,
		Data:     reStoreExploreTalents,
	}
	return &result, nil
}

// 探店达人列表角标
func (t LocalLifeService) StoreExploreInfoCount(param *vo.StoreExploreParam) map[string]int64 {
	res := make(map[string]int64)
	var needBook int64
	var needConfirm int64
	var needExplore int64
	var explored int64
	dao.Db.Model(&entity.LocalLifeTaskInfo{}).Where("local_id = ? AND book_status = ?", param.LocalLifeId, 1).Count(&needBook)
	dao.Db.Model(&entity.LocalLifeTaskInfo{}).Where("local_id = ? AND book_status = ?", param.LocalLifeId, 2).Count(&needConfirm)
	dao.Db.Model(&entity.LocalLifeTaskInfo{}).Where("local_id = ? AND book_status = ?", param.LocalLifeId, 5).Count(&needExplore)
	dao.Db.Model(&entity.LocalLifeTaskInfo{}).Where("local_id = ? AND book_status = ?", param.LocalLifeId, 6).Count(&explored)
	res["needBook"] = needBook
	res["needConfirm"] = needConfirm
	res["needExplore"] = needExplore
	res["explored"] = explored

	return res
}

// 终止合作
func (s LocalLifeService) StoreExploreOver(param *vo.LocalTalentOperateParam) (*string, error) {
	taskId := param.TaskId
	if taskId == "" {
		return nil, errors.New("taskId is empty")
	}
	updateData := map[string]interface{}{
		"task_stage":       17,
		"terminate_reason": param.Reason,
		"terminate_time":   time.Now(),
	}
	if param.SubAccountId == 0 {
		updateData["terminate_operator_type"] = 1
		updateData["terminate_operator"] = param.EnterpriseId
	} else {
		updateData["terminate_operator_type"] = 2
		updateData["terminate_operator"] = param.SubAccountId
	}
	err := dao.LocalLifeTaskInfoDao{}.UpdateField(param.TaskId, updateData)
	if err != nil {
		return nil, err
	}
	return &taskId, nil
}

// 预约时间批量同意/驳回
func (s LocalLifeService) StoreExploreOperate(param *vo.LocalTalentOperateParam) error {
	taskIds := param.TaskIds
	if taskIds == nil {
		return errors.New("taskIds is empty")
	}
	var bookIds []int64
	for _, taskId := range taskIds {
		bookInfo, err := dao.BookInfoDao{}.GetLastByTaskId(taskId)
		if err != nil {
			return err
		}
		bookIds = append(bookIds, bookInfo.BookID)
	}
	var bookinfoNew entity.BookInfo
	if param.Status == 2 {
		bookinfoNew = entity.BookInfo{
			IsReview:      1,
			IsOk:          2,
			RejectAt:      time.Now(),
			ReviseOpinion: param.Reason,
		}
	} else if param.Status == 1 {
		bookinfoNew = entity.BookInfo{
			IsReview: 1,
			IsOk:     1,
			AgreeAt:  time.Now(),
		}
	} else {
		return errors.New("status error")
	}
	if param.SubAccountId == 0 {
		bookinfoNew.BOperatorType = 1
		bookinfoNew.BOperator = param.EnterpriseId
	} else {
		bookinfoNew.BOperatorType = 2
		bookinfoNew.BOperator = strconv.FormatInt(param.SubAccountId, 10)
	}
	err1 := dao.BookInfoDao{}.UpdateBookStatus(bookIds, bookinfoNew)
	if err1 != nil {
		return err1
	}
	if param.Status == 1 {
		err2 := dao.LocalLifeTaskInfoDao{}.UpdateLocalStatus(taskIds, entity.LocalLifeTaskInfo{
			TaskStage:  7,
			BookStatus: 5,
		})
		if err2 != nil {
			return err2
		}
	}

	return nil
}

// 本地生活任务待办
func (p LocalLifeService) GetTaskToDo(enterpriseId string, subAccountId int64, taskType int64) (map[string]map[string]int64, error) {
	res := make(map[string]map[string]int64)
	redbook, err1 := dao.LocalLifeDao{}.GetLocalLifeToDo(enterpriseId, subAccountId, 1, taskType)
	if err1 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err1)
		return res, err1
	}
	douyin, err2 := dao.LocalLifeDao{}.GetLocalLifeToDo(enterpriseId, subAccountId, 2, taskType)
	if err2 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err2)
		return res, err2
	}
	kuaishou, err3 := dao.LocalLifeDao{}.GetLocalLifeToDo(enterpriseId, subAccountId, 4, taskType)
	if err3 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err3)
		return res, err3
	}
	weibo, err4 := dao.LocalLifeDao{}.GetLocalLifeToDo(enterpriseId, subAccountId, 3, taskType)
	if err4 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err4)
		return res, err4
	}
	bilibili, err5 := dao.LocalLifeDao{}.GetLocalLifeToDo(enterpriseId, subAccountId, 5, taskType)
	if err5 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err5)
		return res, err5
	}
	all := make(map[string]int64)
	all["needReview"] = redbook["needReview"] + douyin["needReview"] + kuaishou["needReview"] + weibo["needReview"] + bilibili["needReview"]
	all["needPay"] = redbook["needPay"] + douyin["needPay"] + kuaishou["needPay"] + weibo["needPay"] + bilibili["needPay"]
	all["needProcess"] = redbook["needProcess"] + douyin["needProcess"] + kuaishou["needProcess"] + weibo["needProcess"] + bilibili["needProcess"]
	all["needCheck"] = redbook["needCheck"] + douyin["needCheck"] + kuaishou["needCheck"] + weibo["needCheck"] + bilibili["needCheck"]
	all["needQuality"] = redbook["needQuality"] + douyin["needQuality"] + kuaishou["needQuality"] + weibo["needQuality"] + bilibili["needQuality"]
	all["needCalculate"] = redbook["needCalculate"] + douyin["needCalculate"] + kuaishou["needCalculate"] + weibo["needCalculate"] + bilibili["needCalculate"]
	res["redbook"] = redbook
	res["douyin"] = douyin
	res["kuaishou"] = kuaishou
	res["weibo"] = weibo
	res["bilibili"] = bilibili
	res["all"] = all

	return res, nil
}

// 探店邀约任务待办
func (p LocalLifeService) GetExploreToDo(enterpriseId string, subAccountId int64) (map[string]map[string]int64, error) {
	res := make(map[string]map[string]int64)
	redbook, err1 := dao.LocalLifeDao{}.GetExploreToDo(enterpriseId, subAccountId, 1)
	if err1 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err1)
		return res, err1
	}
	douyin, err2 := dao.LocalLifeDao{}.GetExploreToDo(enterpriseId, subAccountId, 2)
	if err2 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err2)
		return res, err2
	}
	kuaishou, err3 := dao.LocalLifeDao{}.GetExploreToDo(enterpriseId, subAccountId, 4)
	if err3 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err3)
		return res, err3
	}
	weibo, err4 := dao.LocalLifeDao{}.GetExploreToDo(enterpriseId, subAccountId, 3)
	if err4 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err4)
		return res, err4
	}
	bilibili, err5 := dao.LocalLifeDao{}.GetExploreToDo(enterpriseId, subAccountId, 5)
	if err5 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err5)
		return res, err5
	}
	all := make(map[string]int64)
	all["needBook"] = redbook["needBook"] + douyin["needBook"] + kuaishou["needBook"] + weibo["needBook"] + bilibili["needBook"]
	all["needConfirm"] = redbook["needConfirm"] + douyin["needConfirm"] + kuaishou["needConfirm"] + weibo["needConfirm"] + bilibili["needConfirm"]
	all["needExplore"] = redbook["needExplore"] + douyin["needExplore"] + kuaishou["needExplore"] + weibo["needExplore"] + bilibili["needExplore"]
	res["redbook"] = redbook
	res["douyin"] = douyin
	res["kuaishou"] = kuaishou
	res["weibo"] = weibo
	res["bilibili"] = bilibili
	res["all"] = all

	return res, nil
}

// 违约管理任务待办
func (p LocalLifeService) GetDefaultToDo(enterpriseId string, subAccountId int64, taskType int64) (map[string]map[string]int64, error) {
	res := make(map[string]map[string]int64)
	redbook, err1 := dao.LocalLifeDao{}.GetDefaultToDo(enterpriseId, subAccountId, 1, taskType)
	if err1 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err1)
		return res, err1
	}
	douyin, err2 := dao.LocalLifeDao{}.GetDefaultToDo(enterpriseId, subAccountId, 2, taskType)
	if err2 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err2)
		return res, err2
	}
	kuaishou, err3 := dao.LocalLifeDao{}.GetDefaultToDo(enterpriseId, subAccountId, 4, taskType)
	if err3 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err3)
		return res, err3
	}
	weibo, err4 := dao.LocalLifeDao{}.GetDefaultToDo(enterpriseId, subAccountId, 3, taskType)
	if err4 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err4)
		return res, err4
	}
	bilibili, err5 := dao.LocalLifeDao{}.GetDefaultToDo(enterpriseId, subAccountId, 5, taskType)
	if err5 != nil {
		logrus.Errorf("[GetLocalLifeToDo service] call GetLocalLifeToDo error,err:%+v", err5)
		return res, err5
	}
	all := make(map[string]int64)
	all["noSketch"] = redbook["noSketch"] + douyin["noSketch"] + kuaishou["noSketch"] + weibo["noSketch"] + bilibili["noSketch"]
	all["noWork"] = redbook["noWork"] + douyin["noWork"] + kuaishou["noWork"] + weibo["noWork"] + bilibili["noWork"]
	all["noData"] = redbook["noData"] + douyin["noData"] + kuaishou["noData"] + weibo["noData"] + bilibili["noData"]
	all["cooperateOver"] = redbook["cooperateOver"] + douyin["cooperateOver"] + kuaishou["cooperateOver"] + weibo["cooperateOver"] + bilibili["cooperateOver"]
	res["redbook"] = redbook
	res["douyin"] = douyin
	res["kuaishou"] = kuaishou
	res["weibo"] = weibo
	res["bilibili"] = bilibili
	res["all"] = all

	return res, nil
}

// 合作待办-任务邀约
func (p LocalLifeService) GetTaskInviteToDo(enterpriseId string, subAccountId int64) (map[string]map[string]int64, error) {
	res := make(map[string]map[string]int64)
	redbook, err1 := dao.LocalLifeDao{}.GetTaskInviteToDo(enterpriseId, subAccountId, 1)
	if err1 != nil {
		logrus.Errorf("[GetTaskInviteToDo service] call GetTaskInviteToDo error,err:%+v", err1)
		return res, err1
	}
	douyin, err2 := dao.LocalLifeDao{}.GetTaskInviteToDo(enterpriseId, subAccountId, 2)
	if err2 != nil {
		logrus.Errorf("[GetTaskInviteToDo service] call GetTaskInviteToDo error,err:%+v", err2)
		return res, err2
	}
	kuaishou, err3 := dao.LocalLifeDao{}.GetTaskInviteToDo(enterpriseId, subAccountId, 4)
	if err3 != nil {
		logrus.Errorf("[GetTaskInviteToDo service] call GetTaskInviteToDo error,err:%+v", err3)
		return res, err3
	}
	weibo, err4 := dao.LocalLifeDao{}.GetTaskInviteToDo(enterpriseId, subAccountId, 3)
	if err4 != nil {
		logrus.Errorf("[GetTaskInviteToDo service] call GetTaskInviteToDo error,err:%+v", err4)
		return res, err4
	}
	bilibili, err5 := dao.LocalLifeDao{}.GetTaskInviteToDo(enterpriseId, subAccountId, 5)
	if err5 != nil {
		logrus.Errorf("[GetTaskInviteToDo service] call GetTaskInviteToDo error,err:%+v", err5)
		return res, err5
	}
	all := make(map[string]int64)
	all["availInvitationNum"] = redbook["availInvitationNum"] + douyin["availInvitationNum"] + kuaishou["availInvitationNum"] + weibo["availInvitationNum"] + bilibili["availInvitationNum"]
	all["invitingNum"] = redbook["invitingNum"] + douyin["invitingNum"] + kuaishou["invitingNum"] + weibo["invitingNum"] + bilibili["invitingNum"]
	all["cooperatingNum"] = redbook["cooperatingNum"] + douyin["cooperatingNum"] + kuaishou["cooperatingNum"] + weibo["cooperatingNum"] + bilibili["cooperatingNum"]
	res["redbook"] = redbook
	res["douyin"] = douyin
	res["kuaishou"] = kuaishou
	res["weibo"] = weibo
	res["bilibili"] = bilibili
	res["all"] = all

	return res, nil
}
