package service

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"time"
	"youngee_b_api/db"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"github.com/sirupsen/logrus"
)

var ProjectPay *projectPay

type projectPay struct {
}

func (*projectPay) Pay(ctx context.Context, projectPay http_model.ProjectPayRequest, enterpriseID string) (*int64, error) {
	// 修改企业账户金额
	balance, err := db.UpdateEnterpriseBalance(ctx, enterpriseID, 0, -projectPay.PaySum, projectPay.PaySum)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateEnterpriseBalance error,err:%+v", err)
		return nil, err
	}

	// 修改项目状态为执行中
	err = db.UpdateProjectStatus(ctx, projectPay.ProjectID, 9)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateEnterpriseBalance error,err:%+v", err)
		return nil, err
	}

	// 插入支付记录
	recordId, err1 := db.CreatePayRecord(ctx, enterpriseID, projectPay.PaySum, *balance, 2, projectPay.ProjectID)
	if err1 != nil {
		logrus.WithContext(ctx).Errorf("[projectPay service] call CreatePayRecord error,err:%+v", err)
		return nil, err1
	}

	// 支付更新任务状态
	//_, err2 := db.GetProjectDetail(ctx, projectPay.ProjectID)
	//if err2 != nil {
	//	logrus.WithContext(ctx).Errorf("[project service] call GetPorjectDetail error,err:%+v", err)
	//	return nil, err2
	//}
	err = db.UpdateTaskSelectAtByProjectId(ctx, projectPay.ProjectID, 2)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateTaskStatusPaying error,err:%+v", err)
		return nil, err
	}
	err = db.UpdateTaskStageByProjectId(ctx, projectPay.ProjectID, 2, 4)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateTaskStatusPaying error,err:%+v", err)
		return nil, err
	}

	//if project.ProjectForm != 4 {
	//	err = db.UpdateTaskStageByProjectId(ctx, projectPay.ProjectID, 2, 4)
	//	if err != nil {
	//		logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateTaskStatusPaying error,err:%+v", err)
	//		return nil, err
	//	}
	//} else {
	//	if project.ContentType == 1 {
	//		err = db.UpdateTaskStageByProjectId(ctx, projectPay.ProjectID, 2, 9) //修改为待传初稿
	//		if err != nil {
	//			logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateTaskStatusPaying error,err:%+v", err)
	//			return nil, err
	//		}
	//	} else {
	//		err = db.UpdateTaskStageByProjectId(ctx, projectPay.ProjectID, 2, 7) //修改为待传脚本
	//		if err != nil {
	//			logrus.WithContext(ctx).Errorf("[projectPay service] call UpdateTaskStatusPaying error,err:%+v", err)
	//			return nil, err
	//		}
	//	}
	//}

	// 插入消息-任务申请成功
	taskIds, err := db.GetTaskIds(ctx, projectPay.ProjectID) // 获取任务id列表
	if err != nil {
		logrus.WithContext(ctx).Errorf("[projectPay service] call GetTaskIds error,err:%+v", err)
		return nil, err
	}
	fmt.Printf("taskIds: %+v", taskIds)
	for _, taskId := range taskIds {
		err = db.CreateMessageByTaskId(ctx, 1, 1, taskId) // 插入消息
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call CreateMessageByTaskId error,err:%+v", err)
			return nil, err
		}
	}

	return recordId, nil
}

func (p *projectPay) SpecialSettlePay(ctx *gin.Context, req *http_model.SpecialSettlePayRequest) error {
	DB := db.GetReadDB(ctx)
	err := DB.Transaction(func(tx *gorm.DB) error {
		projectInfo := gorm_model.ProjectInfo{}
		err := tx.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", req.ProjectID).First(&projectInfo).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
			return err
		}
		task := gorm_model.YoungeeTaskInfo{}
		err = tx.Model(&gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", req.TaskId).First(&task).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
			return err
		}
		// 校验账户余额是否充足
		var balance float64
		err = tx.Model(&gorm_model.Enterprise{}).Select("balance").Where("enterprise_id = ?", req.EnterPriseId).Find(&balance).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
			return err
		}
		realPay := req.Amount * 1.05
		if balance < realPay {
			return errors.New("余额不足")
		}
		// 增加项目支付金额
		err = tx.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", req.ProjectID).
			Updates(map[string]interface{}{"payment_amount": gorm.Expr("payment_amount + ?", req.Amount)}).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
			return err
		}
		// 旧：更新专项任务收益
		// err = tx.Model(&gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", req.TaskId).Updates(gorm_model.YoungeeTaskInfo{
		// 	TaskReward:     req.Amount,
		// 	SettleAmount:   req.Amount,
		// 	AllPayment:     req.Amount,
		// 	RealPayment:    req.Amount,
		// 	SettleStatus:   2,
		// 	WithdrawStatus: 2,
		// }).Error
		// if err != nil {
		// 	logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
		// 	return err
		// }
		// 新：创建专项任务收益，更新任务阶段
		updateTaskData := gorm_model.YoungeeTaskInfo{
			TaskReward:   req.Amount,
			SettleAmount: req.Amount,
			AllPayment:   req.Amount,
			RealPayment:  req.Amount,
			TaskID:       req.TaskId,
			SettleStatus: 2,
		}
		_, err = db.UpdateTask(ctx, updateTaskData, tx)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
			return err
		}
		var productInfo gorm_model.YounggeeProduct
		if err = json.Unmarshal([]byte(projectInfo.ProductSnap), &productInfo); err != nil {
			fmt.Println("Error:", err)
			return err
		}
		var productPhotoStruct []gorm_model.YounggeeProductPhoto
		if err = json.Unmarshal([]byte(projectInfo.ProductPhotoSnap), &productPhotoStruct); err != nil {
			fmt.Println("Error:", err)
			return err
		}
		var mainPhoto = ""
		for _, w := range productPhotoStruct {
			if w.Symbol == 1 {
				mainPhoto = w.PhotoUrl
			}
		}
		t := time.Now()
		income := gorm_model.YounggeeTalentIncome{
			TalentID:       task.TalentID,
			ProjectID:      task.ProjectID,
			TaskID:         task.TaskID,
			Type:           1,
			BrandName:      productInfo.BrandName,
			TaskName:       projectInfo.ProjectName,
			PhotoUrl:       mainPhoto,
			Income:         strconv.FormatFloat(req.Amount, 'f', 10, 32),
			IncomeType:     1,
			WithdrawStatus: 1,
			IncomeAt:       &t,
			WithdrawAt:     nil,
		}
		err = db.CreateIncome(ctx, income, tx)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
			return err
		}

		// 扣除企业账户余额
		err = tx.Model(&gorm_model.Enterprise{}).Where("enterprise_id = ?", req.EnterPriseId).
			Updates(map[string]interface{}{"balance": gorm.Expr("balance - ?", realPay), "available_balance": gorm.Expr("available_balance - ?", realPay),
				"updated_at": time.Now()}).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
			return err
		}
		talentId := ""
		err = tx.Model(&gorm_model.YoungeeTaskInfo{}).Select("talent_id").Where("task_id = ?", req.TaskId).Find(&talentId).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
			return err
		}
		// 增加达人收益
		err = tx.Model(&gorm_model.YoungeeTalentInfo{}).Where("id = ?", talentId).
			Updates(map[string]interface{}{"income": gorm.Expr("income + ?", req.Amount), "canwithdraw": gorm.Expr("canwithdraw + ?", req.Amount)}).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[projectPay service] call SpecialSettlePay error,err:%+v", err)
			return err
		}
		return nil
	})
	return err
}
