package erpordermanage

import (
	"errors"
	"github.com/gin-gonic/gin"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/logger"
	"go-admin/tools"
	"go-admin/tools/app"
	"gorm.io/gorm"
	"net/http"
	"time"
)

// CreateOrUpdateBusinessSummary 创建或更新每日经营数据
// @Summary 创建或更新每日经营数据
// @Tags 商场检查
// @Produce json
// @Accept json
// @Param request body models.CreateBusinessSummaryRequest true "每日经营数据模型"
// @Success 200 {object} app.Response
// @Router /api/v1/erp_order/business/create [post]
func CreateOrUpdateBusinessSummary(c *gin.Context) {
	var req models.CreateBusinessSummaryRequest

	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, 400, err, err.Error())
		return
	}

	err := tools.Validate(req)
	if err != nil {
		app.Error(c, 400, err, err.Error())
		return
	}

	summaryDate, err := time.Parse("2006-01-02", req.Date)
	if err != nil {
		app.Error(c, 400, err, "日期格式不正确，应为 YYYY-MM-DD")
		return
	}

	var existing models.DailyBusinessSummary
	err = orm.Eloquent.
		Where("date = ? AND store_id = ?", req.Date, req.StoreID).
		First(&existing).Error

	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 不存在，新增
			newRecord := models.DailyBusinessSummary{
				Date:         summaryDate,
				StoreID:      req.StoreID,
				SalesAmount:  req.SalesAmount,
				PromotionFee: req.PromotionFee,
				SalesProfit:  req.SalesProfit,
				StaffProfit:  req.StaffProfit,
				Count:        req.Count,
			}
			if err := orm.Eloquent.Create(&newRecord).Error; err != nil {
				app.Error(c, 500, err, "创建失败")
				return
			}
			app.OK(c, newRecord, "创建成功")
			return
		} else {
			// 其他错误
			app.Error(c, 500, err, "查询失败")
			return
		}
	}

	// 存在，更新
	updateMap := map[string]interface{}{
		"sales_amount":  req.SalesAmount,
		"promotion_fee": req.PromotionFee,
		"sales_profit":  req.SalesProfit,
		"staff_profit":  req.StaffProfit,
		"count":         req.Count,
	}

	if err := orm.Eloquent.Model(&existing).
		Updates(updateMap).Error; err != nil {
		app.Error(c, 500, err, "更新失败")
		return
	}

	app.OK(c, existing, "更新成功")
}

// ListBusinessSummary 获取每日经营数据列表（
// @Summary 获取每日经营数据列表
// @Tags 商场检查
// @Accept json
// @Produce json
// @Param request body models.BusinessSummaryListRequest true "获取每日经营数据列表请求参数"
// @Success 200 {object} models.BusinessSummaryListResp
// @Router /api/v1/erp_order/business/list [post]
func ListBusinessSummary(c *gin.Context) {
	var req = new(models.BusinessSummaryListRequest)
	if err := c.ShouldBindJSON(&req); err != nil {
		app.Error(c, 400, err, "参数错误")
		return
	}

	resp, err := models.QueryListBusinessSummary(req, c)
	if err != nil {
		logger.Error("QueryListBusinessSummary err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败:"+err.Error())
		return
	}

	app.OK(c, resp, "ok")
}

// ListStoreManageData 查询门店经营汇总数据
// @Summary 查询门店经营汇总数据
// @Tags 商场检查
// @Produce json
// @Accept json
// @Param request body models.MarketStoreSalesDataReq true "查询门店经营数据模型"
// @Success 200 {object} models.MarketStoreSalesDataResp
// @Router /api/v1/erp_order/business/summary_data [post]
func ListStoreManageData(c *gin.Context) {
	var req = new(models.MarketStoreSalesDataReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.Error("ShouldBindJSON err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, "参数错误:"+err.Error())
		return
	}

	err := tools.Validate(req) //必填参数校验
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	resp, err := models.QueryDailyBusinessSummaryData(req, c)
	if err != nil {
		logger.Error("QueryDailyBusinessSummaryData err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败:"+err.Error())
		return
	}

	app.OK(c, resp, "")
}
