package logic

import (
	"micro-bundle/internal/dao"
	"micro-bundle/internal/model"
	"micro-bundle/pb/bundle"
	"micro-bundle/pkg/app"
	"micro-bundle/pkg/utils"

	"github.com/jinzhu/copier"
)

func CreateOrderRecord(req *bundle.OrderRecord) (res *bundle.CommonResponse, err error) {
	res = new(bundle.CommonResponse)
	orderRecord := new(model.BundleOrderRecords)
	_ = copier.CopyWithOption(&orderRecord, req, copier.Option{DeepCopy: true})
	orderRecord.UUID = app.ModuleClients.SfNode.Generate().Base64()
	orderRecord.OrderNo = utils.GetOrderNo()
	orderRecord.BundleUUID = req.BundleUuid
	orderRecord.ValueAddBundleUUID = req.ValueAddBundleUuid
	orderRecord.FinancialConfirmation = model.ConfirmationNotConfirmed

	res, err = dao.CreateOrderRecord(orderRecord)
	return
}

func UpdateOrderRecord(req *bundle.OrderRecord) (res *bundle.CommonResponse, err error) {
	res = new(bundle.CommonResponse)
	orderRecord := new(model.BundleOrderRecords)
	_ = copier.CopyWithOption(&orderRecord, req, copier.Option{DeepCopy: true})
	orderRecord.UUID = req.Uuid
	orderRecord.BundleUUID = req.BundleUuid
	res, err = dao.UpdateOrderRecord(orderRecord)
	return
}

func UpdateOrderRecordByOrderNo(req *bundle.OrderRecord) (res *bundle.CommonResponse, err error) {
	res = new(bundle.CommonResponse)
	orderRecord := new(model.BundleOrderRecords)
	_ = copier.CopyWithOption(&orderRecord, req, copier.Option{DeepCopy: true})
	orderRecord.UUID = req.Uuid
	orderRecord.BundleUUID = req.BundleUuid
	res, err = dao.UpdateOrderRecordByOrderNO(orderRecord)
	return
}

func OrderRecordsList(req *bundle.OrderRecordsRequest) (res *bundle.OrderRecordsResponse, err error) {
	res = new(bundle.OrderRecordsResponse)
	res, err = dao.OrderRecordsList(req)
	return
}

func OrderRecordsDetail(req *bundle.OrderRecordsDetailRequest) (res *bundle.OrderRecordsDetailResponse, err error) {
	res = new(bundle.OrderRecordsDetailResponse)
	res.OrderRecord = new(bundle.OrderRecord)
	res.OrderRecord, err = dao.OrderRecordDetail(req)
	if err != nil {
		res.Msg = err.Error()
	}
	return
}

func UpdateFinancialConfirmationStatus(req *bundle.FinancialConfirmationRequest) (res *bundle.CommonResponse, err error) {
	res = new(bundle.CommonResponse)
	err = app.ModuleClients.BundleDB.Model(&model.BundleOrderRecords{}).Where("order_no = ?", req.OrderNo).Update("financial_confirmation", model.ConfirmationConfirmed).Error
	if err != nil {
		res.Msg = "更新财务确认状态失败"
		return res, err
	}
	res.Msg = "更新财务确认状态成功"
	return
}