package service

import (
	"context"
	"time"
	"youngee_b_api/db"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
)

var Cooperate *cooperate

type cooperate struct {
}

// GetEnterpriseInfoBySupplierId 通过supplierId和合作状态筛选合作商家信息
func (*cooperate) GetEnterpriseInfoBySupplierId(ctx context.Context, request *http_model.EnterpriseListRequest) (*http_model.EnterpriseListData, error) {
	enterpriseListInfo, total, enterpriseListInfoErr := db.GetCooperateInfoByIds(ctx, request.SupplierId, request.CooperateStatus, request.PageSize, request.PageNum)
	if enterpriseListInfoErr != nil {
		return nil, enterpriseListInfoErr
	}
	var enterpriseListData *http_model.EnterpriseListData
	enterpriseListData = &http_model.EnterpriseListData{}
	if enterpriseListInfo != nil {
		enterpriseListData.EnterpriseListInfo = enterpriseListInfo
		enterpriseListData.Total = total
	}
	return enterpriseListData, nil
}

// CreateCooperate 创建合作关系
func (*cooperate) CreateCooperate(ctx context.Context, enterpriseId string, supplierId int, subAccountId int) error {
	var cooperateInfo *gorm_model.EnterpriseSupplierCooperate
	cooperateInfo = &gorm_model.EnterpriseSupplierCooperate{}
	cooperateInfo.CooperateStatus = 2
	var currentTime time.Time
	currentTime = time.Now()
	cooperateInfo.AgreeTime = &currentTime
	cooperateInfo.CreateTime = &currentTime
	cooperateInfo.SupplierId = supplierId
	cooperateInfo.EnterpriseId = enterpriseId
	if subAccountId != 0 {
		cooperateInfo.SOperator = subAccountId
		cooperateInfo.SOperatorType = 2
	} else {
		cooperateInfo.SOperator = supplierId
		cooperateInfo.SOperatorType = 1
	}
	totol, findErr := db.FindCooperateInfoBySupplierAndEnterprise(ctx, supplierId, enterpriseId)
	if findErr != nil {
		return findErr
	}
	if totol == 0 {
		err := db.CreateCooperateInfo(ctx, cooperateInfo)
		if err != nil {
			return err
		}
	}
	return nil
}

// AgreeEnterpriseCooperate 同意商家合作邀约请求
func (*cooperate) AgreeEnterpriseCooperate(ctx context.Context, cooperateId int) error {
	err := db.UpdateCooperateInfo(ctx, cooperateId, 2)
	if err != nil {
		return err
	}
	return nil
}

// RejectEnterpriseCooperate 拒绝商家合作邀约请求
func (*cooperate) RejectEnterpriseCooperate(ctx context.Context, cooperateId int) error {
	err := db.UpdateCooperateInfo(ctx, cooperateId, 3)
	if err != nil {
		return err
	}
	return nil
}
