package contract

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"hongze/fms_api/controller/resp"
	"hongze/fms_api/global"
	"hongze/fms_api/models/fms"
	"hongze/fms_api/utils"
	"time"
)

type PaymentController struct{}

// UpdatePaymentPayType
// @Title 修改付款方式
// @Description 修改付款方式
// @Param	request  body  fms.UpdatePaymentPayTypeReq  true "type json string"
// @Success 200 string "操作成功"
// @router /contract/payment/update_pay_type [post]
func (ct *PaymentController) UpdatePaymentPayType(c *gin.Context) {
	req := new(fms.UpdatePaymentPayTypeReq)
	err := c.ShouldBind(&req)
	if err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
			return
		}
		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
		return
	}

	ob := new(fms.ContractInvoice)
	item, e := ob.Fetch(req.ContractPaymentId)
	if e != nil {
		if e == utils.ErrNoRow {
			resp.Fail("到款登记不存在或已被删除", c)
			return
		}
		resp.FailMsg("获取到款登记失败", "Err:"+e.Error(), c)
		return
	}

	nowTime := time.Now().Local()
	item.PayType = req.PayType
	item.ModifyTime = nowTime
	updateCols := []string{"PayType", "ModifyTime"}
	if e = item.Update(updateCols); e != nil {
		resp.FailMsg("操作失败", "更新到款登记失败, Err:"+e.Error(), c)
		return
	}
	resp.Ok("操作成功", c)
}

// DistributePaymentServiceAmount
// @Title 分配套餐金额
// @Description 分配套餐金额
// @Param	request  body  fms.DistributePaymentServiceAmountReq  true "type json string"
// @Success 200 string "操作成功"
// @router /contract/payment/distribute_service_amount [post]
func (ct *PaymentController) DistributePaymentServiceAmount(c *gin.Context) {
	req := new(fms.DistributePaymentServiceAmountReq)
	err := c.ShouldBind(&req)
	if err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			resp.FailData("参数解析失败", "Err:"+err.Error(), c)
			return
		}
		resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
		return
	}

	addList := make([]*fms.ContractPaymentServiceAmount, 0)
	for i := range req.List {
		if req.List[i].Amount <= 0 {
			continue
		}
		if req.List[i].ServiceTemplateId <= 0 {
			resp.Fail("套餐信息有误", c)
			return
		}
		v := &fms.ContractPaymentServiceAmount{
			ContractRegisterId: req.ContractRegisterId,
			ContractPaymentId:  req.ContractPaymentId,
			ServiceTemplatePid: req.List[i].ServiceTemplatePid,
			ServiceTemplateId:  req.List[i].ServiceTemplateId,
			Amount:             req.List[i].Amount,
		}
		v.Set()
		addList = append(addList, v)
	}
	if e := fms.CreatePaymentServiceAmount(req.ContractRegisterId, req.ContractPaymentId, addList); e != nil {
		resp.FailMsg("操作失败", "新增到款套餐金额失败, Err: "+e.Error(), c)
		return
	}
	resp.Ok("操作成功", c)
}