package schedule

import (
	"github.com/robfig/cron/v3"
	"log"
	"time"
	"youngee_b_api/app/dao"
	"youngee_b_api/app/entity"
)

func AutoTaskSettle() error {
	// 新建一个定时任务对象
	crontab := cron.New(cron.WithSeconds()) // 精确到秒
	spec := "0 */1 * * * ?"                 //cron表达式，每5分钟一次

	// 添加定时任务
	// 定时任务1  电商带货结案与解冻处理
	_, err2 := crontab.AddFunc(spec, AutoSelectionSettleTask)
	if err2 != nil {
		return err2
	}
	// 定时任务2  品牌种草结案与解冻处理
	_, err1 := crontab.AddFunc(spec, AutoProjectSettleTask)
	if err1 != nil {
		return err1
	}
	// 定时任务3  本地生活结案与解冻处理
	_, err3 := crontab.AddFunc(spec, AutoLocalLifeSettleTask)
	if err3 != nil {
		return err3
	}

	// 启动定时器
	crontab.Start()
	// 定时任务是另起协程执行的,这里使用 select 简单阻塞.需要根据实际情况进行控制
	//select {} //阻塞主线程停止
	return nil
}

// 定时任务1  电商带货结案与解冻处理
func AutoSelectionSettleTask() {
	log.Println("AutoSelectionSettleTask running Start, Time :", time.Now())
	var selectionInfos []*entity.SelectionInfo
	err1 := dao.Db.Model(&entity.SelectionInfo{}).Where("selection_status = ? and settle_flag = ? ", 8, 0).Select("selection_id, enterprise_id, estimated_cost, settlement_amount").Find(&selectionInfos).Error
	if err1 != nil {
		return
	}
	for _, selectionInfo := range selectionInfos {
		selectionID := selectionInfo.SelectionID
		// 解冻资金
		_, err3 := dao.EnterpriseDao{}.UpdateEnterpriseBalanceAndFrozen2(selectionInfo.EnterpriseID, selectionInfo.EstimatedCost, selectionInfo.SettlementAmount)
		if err3 != nil {
			continue
		}
		// 更新任务状态
		err4 := dao.SelectionInfoDAO{}.UpdateSelectionInfo(entity.SelectionInfo{SelectionID: selectionID, SettleFlag: 1})
		if err4 != nil {
			return
		}
	}
	log.Println("AutoSelectionSettleTask running End, Time :", time.Now())
}

// 定时任务2  品牌种草结案与解冻处理
func AutoProjectSettleTask() {
	log.Println("AutoProjectSettleTask running Start, Time :", time.Now())
	var projectInfos []*entity.Project
	err1 := dao.Db.Model(&entity.Project{}).Where("project_status = ? and settle_flag = ? ", 8, 1).Select("project_id, project_type, enterprise_id, need_pay").Find(&projectInfos).Error
	if err1 != nil {
		return
	}
	// 对于所有子任务结案但未解冻的品牌种草项目进行处理
	for _, projectInfo := range projectInfos {
		projectId := projectInfo.ProjectId
		// 只有公开任务需要冻结&解冻资金
		if projectInfo.ProjectType == 1 {
			// 1. 处理商家账户金额
			var realPayments float64
			var projectTaskInfos []*entity.ProjectTaskInfo
			err2 := dao.Db.Model(&entity.ProjectTaskInfo{}).Where("project_id = ? and task_stage = ? ", projectId, 15).Select("real_payment").Find(&projectTaskInfos).Error
			if err2 != nil {
				continue
			}
			for _, projectTaskInfo := range projectTaskInfos {
				realPayments += projectTaskInfo.RealPayment
			}
			// 解冻资金
			_, err3 := dao.EnterpriseDao{}.UpdateEnterpriseBalanceAndFrozen2(projectInfo.EnterpriseID, projectInfo.NeedPay, realPayments)
			if err3 != nil {
				return
			}
		}
		// 更新任务状态为结案
		err4 := dao.ProjectDAO{}.UpdateProject(entity.Project{ProjectId: projectId, ProjectStatus: 10})
		if err4 != nil {
			return
		}
		// 2、处理涉及到的服务商账户金额
		sProjectInfos, err5 := dao.SProjectDao{}.GetSProjectByProjectId(projectId)
		if err5 != nil {
			return
		}
		for _, sProjectInfo := range sProjectInfos {
			var incomeStatus int64
			if sProjectInfo.SupplierType == 1 {
				incomeStatus = 5
			} else {
				incomeStatus = 1
			}
			_, err6 := dao.SupplierIncomeDao{}.CreateSupplierIncome(entity.SupplierIncome{
				SupplierID:          sProjectInfo.SupplierID,
				SupplierType:        sProjectInfo.SupplierType,
				SProjectID:          sProjectInfo.SProjectID,
				IncomeType:          1,
				IncomeStatus:        incomeStatus,
				ServiceChargeSettle: sProjectInfo.ServiceChargeSettle,
			})
			if err6 != nil {
				return
			}
			err7 := dao.SProjectDao{}.UpdateSProject(entity.SProjectInfo{SProjectID: sProjectInfo.SProjectID, ProjectStatus: 10})
			if err7 != nil {
				return
			}
		}
	}
	log.Println("AutoProjectSettleTask running End, Time :", time.Now())
}

// 定时任务3  本地生活结案与解冻处理
func AutoLocalLifeSettleTask() {
	log.Println("AutoLocalLifeSettleTask running Start, Time :", time.Now())
	var localLifeInfos []*entity.LocalLifeInfo
	err1 := dao.Db.Model(&entity.LocalLifeInfo{}).Where("task_status = ? and settle_flag = ? ", 8, 1).Select("local_id, local_type, enterprise_id, need_pay").Find(&localLifeInfos).Error
	if err1 != nil {
		return
	}
	// 对于所有子任务结案但未解冻的本地生活项目进行处理
	for _, localLifeInfo := range localLifeInfos {
		localId := localLifeInfo.LocalID
		// 只有公开任务需要冻结&解冻资金
		if localLifeInfo.LocalType == 1 {
			// 1. 处理商家账户金额
			var realPayments float64
			var localTaskInfos []*entity.LocalLifeTaskInfo
			err2 := dao.Db.Model(&entity.LocalLifeTaskInfo{}).Where("local_id = ? and task_stage = ? ", localId, 15).Select("real_payment").Find(&localTaskInfos).Error
			if err2 != nil {
				continue
			}
			for _, localTaskInfo := range localTaskInfos {
				realPayments += localTaskInfo.RealPayment
			}
			// 解冻资金
			_, err3 := dao.EnterpriseDao{}.UpdateEnterpriseBalanceAndFrozen2(localLifeInfo.EnterpriseID, localLifeInfo.NeedPay, realPayments)
			if err3 != nil {
				continue
			}
		}
		// 更新任务状态为结案
		err4 := dao.LocalLifeDao{}.UpdateLocal(entity.LocalLifeInfo{LocalID: localId, TaskStatus: 10})
		if err4 != nil {
			return
		}
		// 2、处理涉及到的服务商账户金额
		sLocalLifeInfos, err5 := dao.SLocalLifeDao{}.GetSLocalLifeByLocalId(localId)
		if err5 != nil {
			return
		}
		for _, sLocalLifeInfo := range sLocalLifeInfos {
			var incomeStatus int64
			if sLocalLifeInfo.SupplierType == 1 {
				incomeStatus = 5
			} else {
				incomeStatus = 1
			}
			_, err6 := dao.SupplierIncomeDao{}.CreateSupplierIncome(entity.SupplierIncome{
				SupplierID:          sLocalLifeInfo.SupplierID,
				SupplierType:        sLocalLifeInfo.SupplierType,
				SLocalLifeID:        sLocalLifeInfo.SLocalID,
				IncomeType:          3,
				IncomeStatus:        incomeStatus,
				ServiceChargeSettle: sLocalLifeInfo.ServiceChargeSettle,
			})
			if err6 != nil {
				return
			}
			err7 := dao.SLocalLifeDao{}.UpdateSLocalLife(entity.SLocalLifeInfo{SLocalID: sLocalLifeInfo.SLocalID, TaskStatus: 10})
			if err7 != nil {
				return
			}
		}
	}
	log.Println("AutoLocalLifeSettleTask running End, Time :", time.Now())
}
