package db

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"log"
	"time"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/util"

	"github.com/sirupsen/logrus"
)

// Terminate 批量提交解约申请
func Terminate(ctx context.Context, TaskIDs []string, projectIds []string) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YoungeeContractInfo{}).Where("task_id in ?  and (default_status = 1 or default_status = 4)", TaskIDs).
		Updates(map[string]interface{}{"default_status": 3, "terminate_at": time.Now()}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Data db] Update YoungeeContractInfo error,err:%+v", err)
		return err
	}
	dbc := GetReadDB(ctx)
	errCurDef := dbc.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id in ?", TaskIDs).
		Updates(map[string]interface{}{"cur_default_type": 9}).Error
	if errCurDef != nil {
		logrus.WithContext(ctx).Errorf("[Data db] Update YoungeeTaskInfo error,err:%+v", errCurDef)
		return errCurDef
	}
	projectIds = util.RemoveStrRepByMap(projectIds)
	var unfinishedNum int64
	for _, projectId := range projectIds {
		err1 := db.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_status = 2 AND task_stage < 15", projectId).Count(&unfinishedNum).Error
		if err1 != nil {
			logrus.WithContext(ctx).Errorf("[Data db] Count YoungeeTaskInfo error,err:%+v", err)
			return err1
		}
		var finishedNum int64
		db.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? and task_status = 2 and task_stage >= 15", projectId).Count(&finishedNum)
		if unfinishedNum == 0 && finishedNum != 0 {
			// 2. 释放企业账户因项目冻结的资金
			// 1） 计算剩余资金
			db1 := GetReadDB(ctx)
			var allPayment float64
			var realPayment float64
			err = db1.Model(gorm_model.YoungeeTaskInfo{}).
				Where("project_id = ? and task_status = 2 and task_stage >= 15", projectId).Pluck("COALESCE(SUM(all_payment), 0) as allPayment", &allPayment).Error
			if err != nil {
				log.Println("DB GetAutoCaseCloseTask error in data:", err)
				return err
			}
			err = db1.Model(gorm_model.YoungeeTaskInfo{}).Select("sum(real_payment) as realPayment").
				Where("project_id = ? and task_status = 2 and task_stage >= 15", projectId).Pluck("COALESCE(SUM(real_payment), 0) as realPayment", &realPayment).Error
			if err != nil {
				log.Println("DB GetAutoCaseCloseTask error in data:", err)
				return err
			}
			fmt.Println("企业应支付金额总计：", allPayment, "实际支付总计：", realPayment)
			db2 := GetReadDB(ctx)
			var enterpriseID int64
			db2.Model(gorm_model.ProjectInfo{}).Select("enterprise_id").Where("project_id = ?", projectId).Find(&enterpriseID)
			// 	2）. 释放剩余资金
			err = db1.Model(gorm_model.Enterprise{}).Where("enterprise_id = ?", enterpriseID).Updates(
				map[string]interface{}{
					"frozen_balance":    gorm.Expr("frozen_balance - ?", allPayment),
					"balance":           gorm.Expr("balance - ?", realPayment),
					"available_balance": gorm.Expr("available_balance + ?", allPayment-realPayment)}).Error
			if err != nil {
				log.Println("DB GetAutoCaseCloseTask error in data:", err)
				return err
			}
			// 1. 更新项目状态为已结束
			t := time.Now()
			err = db.Model(gorm_model.ProjectInfo{}).Where("project_id = ?", projectId).
				Updates(map[string]interface{}{"project_status": 10, "payment_amount": realPayment, "finish_at": &t}).Error
			if err != nil {
				logrus.WithContext(ctx).Errorf("[Project db] Update ProjectInfo error,err:%+v", err)
				return err
			}
		}
	}
	return nil
}
