package mallmanage

import (
	"errors"
	"fmt"
	"github.com/codinl/go-logger"
	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog/log"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/tools/app"
	"net/http"
)

// GoodsOrderList 查询商城订单列表
// @Summary 查询商城订单列表
// @Tags 订单管理
// @Produce json
// @Accept json
// @Param request body models.GoodsOrderListReq true "查询商城订单列表"
// @Success 200 {object} app.Response "{"code": 200, "data": { "total": 4, "pageIndex":0, "total_page":10, "list":{} }}"
// @Router /api/v1/mall/goods/order/list [post]
func GoodsOrderList(c *gin.Context) {
	req := &models.GoodsOrderListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	sysUser, err := models.GetSysUserByCtx(c)
	if err != nil {
		logger.Errorf("err:%#v", err)
		app.Error(c, http.StatusInternalServerError, errors.New("order list  err"), "获取订单列表失败")
		return
	}
	if sysUser.StoreId != 13 && sysUser.StoreId != 0 {
		logger.Errorf("err:%#v", err)
		app.Error(c, http.StatusInternalServerError, errors.New("order list  err"), "没有权限")
		return
	}
	orderList, exportUrl, totalCount, err := req.OrderList()
	if err != nil {
		logger.Errorf("err:%#v", err)
		msg := "获取订单列表失败"
		app.Error(c, http.StatusInternalServerError, errors.New("order list  err"), msg)
		return
	}
	ret := map[string]interface{}{
		"total":      totalCount,
		"list":       orderList,
		"page_index": req.PageIdx,
		"page_size":  req.PageSize,
		"export_url": exportUrl,
	}
	app.OK(c, ret, "")
}

func GoodsOrderDetail(c *gin.Context) {
	req := &models.GoodsOrderDetailReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	orderDetail, err := req.OrderDetail()
	if err != nil {
		logger.Errorf("err:%#v", err)
		msg := "获取订单详情失败"
		app.Error(c, http.StatusInternalServerError, errors.New("order detail  err"), msg)
		return
	}

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

func GoodsOrderDeliver(c *gin.Context) {
	req := &models.GoodsOrderDeliverReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	sysUser, err := models.GetSysUserByCtx(c)
	if err != nil {
		log.Error().Msgf("get sys user err:%#v", err)
		app.Error(c, http.StatusInternalServerError, errors.New("order detail  err"), "订单发货失败")
		return
	}

	// todo 暂时使用用户有效门店，待后续产品梳理流程后再修改
	//req.DeliverStoreId = sysUser.StoreId
	var storeId int
	storeInfo, _ := models.GetUserEffectiveStore(uint32(sysUser.UserId))
	if storeInfo == nil {
		var stores []models.Store
		err = orm.Eloquent.Table("store").Find(&stores).Error
		if err != nil {
			app.Error(c, http.StatusInternalServerError, errors.New("store is null"), "门店id为空")
			return
		}
		storeId = int(stores[0].ID)
	} else {
		storeId = storeInfo[0].StoreID
	}

	req.DeliverStoreId = uint32(storeId)

	orderDetail, err := req.OrderDeliver()
	if err != nil {
		logger.Errorf("err:%#v", err)
		msg := "订单发货失败"
		app.Error(c, http.StatusInternalServerError, errors.New("order detail  err"), msg)
		return
	}

	app.OK(c, orderDetail, "订单发货成功")
}

func GoodsOrderRefundSendReceive(c *gin.Context) {
	req := &models.GoodsOrderRefundSendReceiveReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	sysUser, err := models.GetSysUserByCtx(c)
	if err != nil {
		log.Error().Msgf("get sys user err:%#v", err)
		app.Error(c, http.StatusInternalServerError, errors.New("order detail  err"), "订单发货失败")
		return
	}
	req.SysUser = *sysUser

	err = req.Receive()
	if err != nil {
		logger.Errorf("err:%#v", err)
		app.Error(c, http.StatusInternalServerError, errors.New("order detail  err"),
			fmt.Sprintf("退货失败：%s", err.Error()))
		return
	}

	app.OK(c, nil, "订单退货成功")
}

// MallUserVmRecord 用户积分记录
// @Summary 用户积分记录
// @Tags 数据统计, V1.2.0
// @Produce json
// @Accept json
// @Param request body models.MallUserVmRecordReq true "用户积分记录模型"
// @Success 200 {object} models.MallUserVmRecordResp
// @Router /api/v1/mall/goods/user/vm_record [post]
func MallUserVmRecord(c *gin.Context) {
	req := &models.MallUserVmRecordReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	orderList, totalCount, err := req.MallUserVmRecordList()
	if err != nil {
		logger.Errorf("err:%#v", err)
		msg := "获取用户积分记录列表失败"
		app.Error(c, http.StatusInternalServerError, errors.New("order detail  err"), msg)
		return
	}

	ret := models.MallUserVmRecordResp{
		Count:     totalCount,
		List:      orderList,
		PageIndex: req.PageIdx,
		PageSize:  req.PageSize,
	}

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