package backstage_service

import (
	"context"
	"errors"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"strconv"
	"youngmini_server/app/dao"
	"youngmini_server/app/model/backstage_model"
)

var Task = serviceTask{}

type serviceTask struct {
}

// CreatTask  创建任务用事务处理
func (s *serviceTask) CreatTask(allCreatParam *backstage_model.RequestAllCreatParam) error {
	g.DB().SetDebug(true)
	err := g.DB().Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
		// 品牌创建
		brand, err := tx.Ctx(ctx).Model("brand").
			Data(allCreatParam.Brand).OmitEmpty().Insert()
		if err != nil {
			return err
		}
		brandId, _ := brand.LastInsertId()
		// 将基础信息获取的int64转换成string
		temp := strconv.FormatInt(brandId, 10)
		// 将string 转换成int
		brandIdTemp, _ := strconv.Atoi(temp)

		// 商品创建
		product, err := tx.Ctx(ctx).Model("product").
			Data(allCreatParam.Product).OmitEmpty().Insert()
		if err != nil {
			return err
		}
		productId, _ := product.LastInsertId()
		// 将基础信息获取的int64转换成string
		temp = strconv.FormatInt(productId, 10)
		// 将string 转换成int
		productIdTemp, _ := strconv.Atoi(temp)

		if len(allCreatParam.ProductPhoto) != 0 {
			// 商品图片创建
			for k, _ := range allCreatParam.ProductPhoto {
				allCreatParam.ProductPhoto[k].ProductId = productIdTemp
			}
			_, err = tx.Ctx(ctx).Model("product_photo").
				Data(allCreatParam.ProductPhoto).OmitEmpty().Insert()
			if err != nil {
				return err
			}
		}
		// 任务基础信息创建
		allCreatParam.TaskBaseInfo.BrandId = brandIdTemp
		allCreatParam.TaskBaseInfo.ProductId = productIdTemp
		allCreatParam.TaskBaseInfo.TaskStatus = 1
		allCreatParam.TaskBaseInfo.BrandName = allCreatParam.Brand.BrandName
		task, err := tx.Ctx(ctx).Model("task_base_info").
			Data(allCreatParam.TaskBaseInfo).OmitEmpty().Insert()
		if err != nil {
			return err
		}
		taskId, _ := task.LastInsertId()
		// 将基础信息获取的int64转换成string
		temp = strconv.FormatInt(taskId, 10)
		// 将string 转换成int
		taskIdTemp, _ := strconv.Atoi(temp)

		// 任务配置总流程创建
		allCreatParam.TaskProcedureDecisionCondition.TaskBaseId = taskIdTemp
		if allCreatParam.TaskProcedureDecisionCondition.BuySamplesRefund == "" {
			allCreatParam.TaskProcedureDecisionCondition.BuySamplesRefund = "0"
		}
		// allCreatParam.TaskProcedureDecisionCondition.BuySamplesRefund = allCreatParam.TaskProcedureDecisionCondition.BuySamplesCost
		_, err = tx.Ctx(ctx).Model("task_procedure_decision_condition").
			Data(allCreatParam.TaskProcedureDecisionCondition).OmitEmpty().Insert()
		if err != nil {
			return err
		}

		// 任务流程需要配置初稿部分
		allCreatParam.TaskProcedureDraftInfo.TaskBaseId = taskIdTemp
		_, err = tx.Ctx(ctx).Model("task_procedure_draft_info").
			Data(allCreatParam.TaskProcedureDraftInfo).OmitEmpty().Insert()
		if err != nil {
			return errors.New("必填字段未传完，请检查")
		}

		// 任务流程需要配置作品部分
		allCreatParam.TaskProcedureArticleInfo.TaskBaseId = taskIdTemp
		_, err = tx.Ctx(ctx).Model("task_procedure_article_info").
			Data(allCreatParam.TaskProcedureArticleInfo).OmitEmpty().Insert()
		if err != nil {
			return err
		}

		// 任务配置流程链接质检配置
		allCreatParam.TaskProcedureQualityDataTestInfo.TaskBaseId = taskIdTemp
		_, err = tx.Ctx(ctx).Model("task_procedure_quality_data_test_info").
			Data(allCreatParam.TaskProcedureQualityDataTestInfo).OmitEmpty().Insert()
		if err != nil {
			return err
		}

		// 达人任务奖励
		allCreatParam.TaskReward.TaskBaseId = taskIdTemp
		_, err = tx.Ctx(ctx).Model("task_reward").
			Data(allCreatParam.TaskReward).OmitEmpty().Insert()
		if err != nil {
			return err
		}

		// 招募要求
		allCreatParam.TaskRecruitRequirements.TaskBaseId = taskIdTemp
		_, err = tx.Ctx(ctx).Model("task_recruit_requirements").
			Data(allCreatParam.TaskRecruitRequirements).OmitEmpty().Insert()
		if err != nil {
			return err
		}

		if len(allCreatParam.TaskRecruitTalentLevel) != 0 {
			// 合作方式、所需达人数量及对应稿费
			for k, _ := range allCreatParam.TaskRecruitTalentLevel {
				allCreatParam.TaskRecruitTalentLevel[k].TaskBaseId = taskIdTemp
			}
			_, err = tx.Ctx(ctx).Model("task_recruit_talent_level").
				Data(allCreatParam.TaskRecruitTalentLevel).OmitEmpty().Insert()
			if err != nil {
				return err
			}
		}

		// 任务执行帮助
		allCreatParam.TaskPerformHelpInfo.TaskBaseId = taskIdTemp
		_, err = tx.Ctx(ctx).Model("task_perform_help_info").
			Data(allCreatParam.TaskPerformHelpInfo).OmitEmpty().Insert()
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return errors.New("创建失败，请检查必填字段是否未填")
	}
	return nil
}

// 拼接数据库数据库where语句字符串
func (s *serviceTask) contact(task *backstage_model.TaskCondition) string {
	if task == nil {
		return ""
	}
	var res []string
	if task.TaskId != "" {
		res = append(res, "task_id="+task.TaskId)
	}
	if task.TaskName != "" {
		res = append(res, "task_name= '"+task.TaskName+"'")
	}
	if task.BusinessType != "" {
		res = append(res, "business_type="+task.BusinessType)
	}
	if task.TaskStatus != "" {
		res = append(res, "task_status="+task.TaskStatus)
	} else {
		res = append(res, "task_status < 4")
	}
	if task.TaskPlatform != "" {
		res = append(res, "task_platform="+task.TaskPlatform)
	}
	if task.ContentForm != "" {
		res = append(res, "content_form="+task.ContentForm)
	}
	// WhereBetween("online_time", findAll.Task.OnlineTime[0]+" 00:00:00", findAll.Task.OnlineTime[1]+" 23:59:59")
	if len(task.OnlineTime) != 0 && task.OnlineTime[0] != "" {
		res = append(res, "online_time>'"+task.OnlineTime[0]+" 00:00:00' and "+
			"online_time<'"+task.OnlineTime[1]+" 23:59:59'")
	}
	var result string
	for k, value := range res {
		if k == 0 {
			result += value
		} else {
			result += " and " + value
		}
	}
	return result
}

// FindConditionAll 根据时间范围进行查询
func (s *serviceTask) FindConditionAll(findAll *backstage_model.TaskFindAll) ([]*backstage_model.FindAllResponse, int, error) {
	var taskList []*backstage_model.FindAllResponse
	g.DB().SetDebug(true)
	contact := s.contact(findAll.Task)
	err := g.DB().Model("task_base_info").Where("task_status < 4").
		LeftJoin("(SELECT task_base_id, SUM(need_talent_count) AS talent_sum FROM task_recruit_talent_level GROUP BY task_base_id) s",
			"task_base_info.task_id=s.task_base_id").
		Fields("task_base_info.task_id", "task_name", "business_type", "task_mode", "s.talent_sum",
			"content_form", "online_time", "deadline_time", "start_time", "task_status", "task_platform", "brand_id", "product_id").Where(contact).OmitEmpty().
		OrderDesc("created_at").
		Page(findAll.IndexPage, findAll.PageSize).Scan(&taskList)
	if err != nil {
		return nil, 0, err
	}
	count, err := g.DB().Model("task_base_info").Where(contact).OmitEmpty().Count()
	if err != nil {
		return nil, 0, err
	}
	return taskList, count, nil
}

// AlterTaskStatus 修改任务状态
func (s *serviceTask) AlterTaskStatus(status *backstage_model.RequestStatus) error {
	g.DB().SetDebug(true)
	if status.TaskStatus == 2 {
		_, err := g.DB().Model("task_base_info").Data(g.Map{"task_status": status.TaskStatus,
			"online_time": gtime.Now()}).
			Where("task_id", status.TaskId).Update()
		if err != nil {
			return err
		}
	} else {
		_, err := g.DB().Model("task_base_info").Data("task_status", status.TaskStatus).
			Where("task_id", status.TaskId).Update()
		if err != nil {
			return err
		}
	}
	return nil
}

// TaskInfoShow 任务信息查看
func (s *serviceTask) TaskInfoShow(taskBase *backstage_model.RequestTaskInfo) (*backstage_model.ResponseAllCreatParam, error) {
	// 需要参数，任务id,商品id,品牌id
	// 返回值
	var result = new(backstage_model.ResponseAllCreatParam)
	g.DB().SetDebug(true)
	// 查询品牌信息
	var brand *backstage_model.RequestBrand
	err := g.DB().Model("brand").Where("brand_id", taskBase.BrandId).Scan(&brand)
	if err != nil {
		return nil, err
	}
	result.Brand = brand
	// 查询商品信息
	err = g.DB().Model("product").Where("product_id", taskBase.ProductId).Scan(&result.Product)
	if err != nil {
		return nil, err
	}
	// 查询商品图片信息
	err = g.DB().Model("product_photo").Where("product_id", taskBase.ProductId).Scan(&result.ProductPhoto)
	if err != nil {
		return nil, err
	}
	// 任务基础信息
	err = g.DB().Model("task_base_info").Where("task_id", taskBase.TaskId).Scan(&result.TaskBaseInfo)
	if err != nil {
		return nil, err
	}
	// 任务配置总流程
	err = g.DB().Model("task_procedure_decision_condition").Where("task_base_id", taskBase.TaskId).Scan(&result.TaskProcedureDecisionCondition)
	if err != nil {
		return nil, err
	}
	// 任务流程初稿配置
	err = g.DB().Model("task_procedure_draft_info").Where("task_base_id", taskBase.TaskId).Scan(&result.TaskProcedureDraftInfo)
	if err != nil {
		return nil, err
	}
	// 任务流程作品配置
	err = g.DB().Model("task_procedure_article_info").Where("task_base_id", taskBase.TaskId).Scan(&result.TaskProcedureArticleInfo)
	if err != nil {
		return nil, err
	}
	// 任务流程质检链接配置
	err = g.DB().Model("task_procedure_quality_data_test_info").Where("task_base_id", taskBase.TaskId).Scan(&result.TaskProcedureQualityDataTestInfo)
	if err != nil {
		return nil, err
	}
	// 达人任务奖励配置
	err = g.DB().Model("task_reward").Where("task_base_id", taskBase.TaskId).Scan(&result.TaskReward)
	if err != nil {
		return nil, err
	}
	// 招募要求配置
	err = g.DB().Model("task_recruit_requirements").Where("task_base_id", taskBase.TaskId).Scan(&result.TaskRecruitRequirements)
	if err != nil {
		return nil, err
	}

	// 合作方式，所需达人数量及对应稿费
	err = g.DB().Model("task_recruit_talent_level").Where("task_base_id", taskBase.TaskId).Scan(&result.TaskRecruitTalentLevel)
	if err != nil {
		return nil, err
	}
	// 任务执行帮助
	err = g.DB().Model("task_perform_help_info").Where("task_base_id", taskBase.TaskId).Scan(&result.TaskPerformHelpInfo)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// UpdateBrand 修改品牌信息接口
func (s *serviceTask) UpdateBrand(brand *backstage_model.RequestBrand) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("brand").Data(brand).OmitEmpty().Where("brand_id", brand.BrandId).Update()
	if err != nil {
		return err
	}
	return nil
}

// UpdateProduct 修改商品信息
func (s *serviceTask) UpdateProduct(product *backstage_model.RequestProduct) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("product").Data(product).OmitEmpty().Where("product_id", product.ProductId).Update()
	if err != nil {
		return err
	}
	return nil
}

// UpdateProductPhoto 修改商品图片信息
func (s *serviceTask) UpdateProductPhoto(ProductPhoto *backstage_model.RequestProductPhoto) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("product_photo").Data(ProductPhoto).OmitEmpty().Where("product_photo_id", ProductPhoto.ProductPhotoId).Update()
	if err != nil {
		return err
	}
	return nil
}

// AddProductPhoto 增加图片信息
func (s *serviceTask) AddProductPhoto(ProductPhoto *backstage_model.RequestProductPhoto) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("product_photo").Data(ProductPhoto).OmitEmpty().Insert()
	if err != nil {
		return err
	}
	return nil
}

// DeleteProductPhoto 删除图片信息
func (s *serviceTask) DeleteProductPhoto(ProductPhoto *backstage_model.RequestProductPhoto) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("product_photo").Where("product_photo_id", ProductPhoto.ProductPhotoId).Delete()
	if err != nil {
		return err
	}
	return nil
}

// UpdateTaskBaseInfo 修改任务基础信息
func (s *serviceTask) UpdateTaskBaseInfo(TaskBaseInfo *backstage_model.RequestTaskBaseInfo) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_base_info").Data(TaskBaseInfo).OmitEmpty().Where("task_id", TaskBaseInfo.TaskId).Update()
	if err != nil {
		return err
	}
	return nil
}

// UpdateProcedure 修改任务配置总流程
func (s *serviceTask) UpdateProcedure(procedure *backstage_model.RequestTaskProcedureDecisionCondition) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_procedure_decision_condition").Data(procedure).OmitEmpty().Where("tpd_id", procedure.TpdId).Update()
	if err != nil {
		return err
	}
	return nil
}

// UpdateDraftInfo 修改流程初稿配置
func (s *serviceTask) UpdateDraftInfo(draftInfo *backstage_model.RequestTaskProcedureDraftInfo) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_procedure_draft_info").Data(draftInfo).OmitEmpty().Where("task_pd_id", draftInfo.TaskPdId).Update()
	if err != nil {
		return err
	}
	return nil
}

// UpdateArticleInfo 修改流程作品配置
func (s *serviceTask) UpdateArticleInfo(articleInfo *backstage_model.RequestTaskProcedureArticleInfo) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_procedure_article_info").Data(articleInfo).OmitEmpty().Where("tpa_id", articleInfo.TpaId).Update()
	if err != nil {
		return err
	}
	return nil
}

// UpdateQualityInfo 修改质检链接配置
func (s *serviceTask) UpdateQualityInfo(qualityInfo *backstage_model.RequestTaskProcedureQualityDataTestInfo) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_procedure_quality_data_test_info").Data(qualityInfo).OmitEmpty().Where("tpq_id", qualityInfo.TpqId).Update()
	if err != nil {
		return err
	}
	return nil
}

// UpdateReward 修改达人任务奖励配置
func (s *serviceTask) UpdateReward(reward *backstage_model.RequestTaskReward) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_reward").Data(reward).OmitEmpty().Where("reward_id", reward.RewardId).Update()
	if err != nil {
		return err
	}
	return nil
}

// UpdateRecruitRequirement 修改招募要求配置
func (s *serviceTask) UpdateRecruitRequirement(recruitRequirement *backstage_model.RequestTaskRecruitRequirements) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_recruit_requirements").Data(recruitRequirement).OmitEmpty().Where("trr_id", recruitRequirement.TrrId).Update()
	if err != nil {
		return err
	}
	return nil
}

// UpdateRecruitLevel 修改合作方式，所需达人数量及其对应稿费
func (s *serviceTask) UpdateRecruitLevel(recruitLevel *backstage_model.RequestTaskRecruitTalentLevel) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_recruit_talent_level").Data(recruitLevel).OmitEmpty().Where("trt_id", recruitLevel.TrtId).Update()
	if err != nil {
		return err
	}
	return nil
}

// AddRecruitLevel 增加合作方式，所需达人数量及其对应稿费
func (s *serviceTask) AddRecruitLevel(recruitLevel *backstage_model.RequestTaskRecruitTalentLevel) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_recruit_talent_level").Data(recruitLevel).OmitEmpty().Insert()
	if err != nil {
		return err
	}
	return nil
}

// DeleteRecruitLevel 删除合作仿作方式，所需达人数量及其对应稿费
func (s *serviceTask) DeleteRecruitLevel(recruitLevel *backstage_model.RequestTaskRecruitTalentLevel) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_recruit_talent_level").Where("trt_id", recruitLevel.TrtId).Delete()
	if err != nil {
		return err
	}
	return nil
}

// UpdatePerformHelp 修改任务执行帮助
func (s *serviceTask) UpdatePerformHelp(performHelp *backstage_model.RequestTaskPerformHelpInfo) error {
	g.DB().SetDebug(true)
	_, err := g.DB().Model("task_perform_help_info").Data(performHelp).OmitEmpty().Where("tph_id", performHelp.TphId).Update()
	if err != nil {
		return err
	}
	return nil
}

// FindSendAddress 发货信息查询
func (s *serviceTask) FindSendAddress(TaskFindAll *backstage_model.SendProductAddress) ([]*backstage_model.ResponseOrderDeliveryInfo, int, error) {
	var result []*backstage_model.ResponseOrderDeliveryInfo
	err := g.DB().Model("order_delivery_info").Page(TaskFindAll.IndexPage, TaskFindAll.PageSize).Scan(&result)
	if err != nil {
		return nil, 0, err
	}
	count, err := g.DB().Model("order_delivery_info").Count()
	if err != nil {
		return nil, 0, err
	}
	return result, count, nil
}

// FindRecruit 招募进度信息查询
func (s *serviceTask) FindRecruit(taskId *backstage_model.RequestTaskInfo) ([]*backstage_model.ResponseRecruit, error) {
	// 根据任务id查询招募等级表的id。获取一个id组成的切片
	g.DB().SetDebug(true)
	array, err := g.DB().Model("task_recruit_talent_level").Where("task_base_id", taskId.TaskId).
		Page(taskId.IndexPage, taskId.PageSize).Fields("trt_id").Array()
	if err != nil {
		return nil, err
	}
	// 根据招募等级表的id,循环执行招募等级表
	var result []*backstage_model.ResponseRecruit
	var temp *backstage_model.ResponseRecruit
	for _, v := range array {
		err := g.DB().Model("task_recruit_talent_level").Where("trt_id", v).
			Fields("trt_id", "task_base_id", "fans_count_min", "fans_count_max", "need_talent_count",
				"(select count(task_level_id) from order_info where task_level_id ="+v.String()+") as count_sum",
				"(select count(task_level_id) from order_info where task_level_id ="+v.String()+" and order_status = 2) as count_select").
			Scan(&temp)
		if err != nil {
			return nil, err
		}
		result = append(result, temp)
		temp = nil
	}
	return result, nil
}

// FindBIStatistics 任务所包含的订单数据BI统计
func (s *serviceTask) FindBIStatistics(taskId *backstage_model.RequestTaskInfo) (*backstage_model.ResponseBI, error) {
	g.DB().SetDebug(true)
	var result *backstage_model.ResponseBI
	temp := strconv.Itoa(taskId.TaskId)
	err := g.DB().Model("order_info").Fields("count(task_id) as apply_sum",
		"(select count(task_id)  from order_info where task_id = "+temp+" and order_status = 2) as task_id_select",
		"(select count(task_id)  from order_info where task_id = "+temp+" and order_status = 3) as task_id_draft",
		"(select count(task_id)  from order_info where task_id = "+temp+" and order_status = 4) as task_id_link",
		"(select count(task_id)  from order_info where task_id = "+temp+" and order_status = 5) as task_id_finish").
		Where("task_id", taskId.TaskId).Scan(&result)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// DeleteTask 删除任务
func (s *serviceTask) DeleteTask(taskId int) error {
	rec, err := g.DB().Model(dao.TaskBaseInfo.Table).Fields(dao.TaskBaseInfo.Columns.TaskStatus).One(dao.TaskBaseInfo.Columns.TaskId, taskId)
	if err != nil {
		return err
	}

	if rec[dao.TaskBaseInfo.Columns.TaskStatus].Int() != 3 {
		return errors.New("任务不为终止状态")
	}

	_, err = g.DB().Model(dao.TaskBaseInfo.Table).
		Update(g.Map{dao.TaskBaseInfo.Columns.TaskStatus:4}, dao.TaskBaseInfo.Columns.TaskId, taskId)
	return err
}
