package stockmanage

import (
	"errors"
	"fmt"
	"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"
	"net/http"
	"time"
)

// GameCardGoodsStockInfoList 查询小程序租卡库存列表
// @Summary 查询小程序租卡库存列表
// @Tags 租卡系统-库存管理
// @Produce json
// @Accept json
// @Param request body models.GameCardGoodsStockListReq true "查询小程序租卡库存列表"
// @Success 200 {object} models.GameCardGoodsStockListResp
// @Router /api/v1/stock/list [post]
func GameCardGoodsStockInfoList(c *gin.Context) {
	req := &models.GameCardGoodsStockListReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	resp, err := req.List(c)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	//ret := map[string]interface{}{
	//	"count":      count,
	//	"list":       list,
	//	"pageIndex":  req.PageIndex,
	//	"total_page": req.PageSize,
	//}
	app.OK(c, resp, "")
}

// GameCardGoodsStockOutInfoList 出库明细
// @Summary 出库明细
// @Tags 租卡系统-库存管理
// @Produce json
// @Accept json
// @Param request body models.GameCardGoodsStockOutInfoListReq true "出库明细模型"
// @Success 200 {object} models.GameCardGoodsStockOutInfoListResp
// @Router /api/v1/stock/out_list [post]
func GameCardGoodsStockOutInfoList(c *gin.Context) {
	req := &models.GameCardGoodsStockOutInfoListReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	resp, err := req.List(c)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

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

func GameCardGoodsStockCardList(c *gin.Context) {
	req := &models.GameCardGoodsStockCardListReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":      count,
		"list":       list,
		"pageIndex":  req.Page,
		"total_page": req.PageSize,
	}
	app.OK(c, ret, "")
}

func GameCardGoodsStockAdds(c *gin.Context) {
	req := struct {
		Cards []models.GameCardGoods `json:"cards"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	cardGoods := &models.GameCardGoods{}
	for i, _ := range req.Cards {
		req.Cards[i].CardType = models.GameCardGoodsTypeCommon
		req.Cards[i].ShareProfitType = 1
	}
	err := cardGoods.Adds(req.Cards)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "入库失败")
		return
	}

	app.OK(c, nil, "入库成功")
}

// GameCardGoodsStockDels 游戏卡出库
// @Summary 游戏卡出库
// @Tags 租卡系统-库存管理
// @Produce json
// @Accept json
// @Param request body models.GameCardGoodsStockDelsReq true "游戏卡出库模型"
// @Success 200 {object} app.Response
// @Router /api/v1/stock/card/dels [post]
func GameCardGoodsStockDels(c *gin.Context) {
	req := &models.GameCardGoodsStockDelsReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	cardGoods := &models.GameCardGoods{}
	err := cardGoods.Dels(req.SerialNumberList, c)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "删除失败:"+err.Error())
		return
	}

	app.OK(c, nil, "删除库存成功")
}

func ExportDataGameCardGoodsStock(c *gin.Context) {
	req := struct {
		StoreId uint32 `json:"store_id"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	goodsStock := models.ExportGoodsStock(req.StoreId)
	//cardGoods := &models.GameCardGoods{}
	//err := cardGoods.Adds(req.Cards)
	//if err != nil {
	//	logger.Errorf("err:",logger.Field("err",err))
	//	app.Error(c, http.StatusInternalServerError, err, "入库失败")
	//	return
	//}

	ret := &map[string]interface{}{
		"goods_stock_url": goodsStock,
	}
	app.OK(c, ret, "数据导出成功")
}

// 1.创建调拨任务
func CannibalizeTaskCreate(c *gin.Context) {
	req := struct {
		FromStoreId uint32 `json:"from_store_id"`
		ToStoreId   uint32 `json:"to_store_id"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	if req.FromStoreId == 0 || req.ToStoreId == 0 {
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	sysUser, err := models.GetSysUserByCtx(c)
	if err != nil {
		logger.Error("sys user err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	// 校验入参门店是否包含在用户所有门店中，是否过期
	if !(tools.GetRoleName(c) == "admin" || tools.GetRoleName(c) == "系统管理员") {
		if !models.CheckUserStore(req.FromStoreId, sysUser) {
			app.Error(c, http.StatusInternalServerError, errors.New("操作失败：您没有该门店权限"),
				"操作失败：您没有该门店权限")
			return
		}
	}

	task := &models.CannibalizeStockTask{
		FromStoreId: req.FromStoreId,
		ToStoreId:   req.ToStoreId,
		TaskId:      uint32(time.Now().Unix()),
		Count:       0,
		Status:      models.CannibalizeTaskStatusNotImportGoods,
		MakerId:     uint32(sysUser.UserId),
		MakerName:   sysUser.NickName,
	}
	err = orm.Eloquent.Create(task).Error
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "创建调拨任务错误")
		return
	}

	app.OK(c, nil, "创建调拨任务成功")
}

// 2.导入调拨卡
func CannibalizeTaskImportGameCardGoods(c *gin.Context) {
	req := struct {
		CannibalizeStockTaskId uint32   `json:"cannibalize_stock_task_id"`
		SerialNumberList       []string `json:"serial_number_list"` // 编号
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	unImportGoods, err := models.CannibalizeTaskImportGoods(req.CannibalizeStockTaskId, req.SerialNumberList)
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "导入调拨卡错误")
	}
	if unImportGoods > 0 {
		app.OK(c, nil, fmt.Sprintf("有 %d 个卡未导入", unImportGoods))
		return
	}

	app.OK(c, nil, "导入调拨卡成功")
}

// 3.确认发货
func CannibalizeTaskDeliverGoods(c *gin.Context) {
	req := struct {
		CannibalizeStockTaskId uint32 `json:"cannibalize_stock_task_id"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := models.CannibalizeDeliverGoods(req.CannibalizeStockTaskId)
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "发货错误")
	}

	app.OK(c, nil, "发货成功")
}

// 4.确认入库
func CannibalizeTaskPutInStorage(c *gin.Context) {
	req := struct {
		CannibalizeStockTaskId uint32 `json:"cannibalize_stock_task_id"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := models.CannibalizePutInStorage(req.CannibalizeStockTaskId)
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "发货错误")
	}

	app.OK(c, nil, "发货成功")
}

// CannibalizeTaskList 查询游戏卡库存调拨
// @Summary 查询游戏卡库存调拨
// @Tags 租卡系统-库存管理
// @Produce json
// @Accept json
// @Param request body models.CannibalizeTaskListReq true "查询游戏卡库存调拨"
// @Success 200 {object} models.CannibalizeTaskListResp
// @Router /api/v1/stock/cannibalize_task/list [post]
func CannibalizeTaskList(c *gin.Context) {
	req := models.CannibalizeTaskListReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	resp, err := req.GetCannibalizeTaskList(c)
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "任务列表错误")
		return
	}

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

// CannibalizeTaskDetail 查询游戏卡库存调拨明细
// @Summary 查询游戏卡库存调拨明细
// @Tags 租卡系统-库存管理
// @Produce json
// @Accept json
// @Param request body models.CannibalizeTaskDetailReq true "查询游戏卡库存调拨明细"
// @Success 200 {object} models.CannibalizeTaskDetailResp
// @Router /api/v1/stock/cannibalize_task/detail [post]
func CannibalizeTaskDetail(c *gin.Context) {
	req := models.CannibalizeTaskDetailReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	resp, err := req.GetCannibalizeTaskDetail(c)
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询游戏卡库存调拨明细错误")
		return
	}

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

// 6.调拨任务卡列表
func CannibalizeTaskGameCardGoodsList(c *gin.Context) {
	req := models.CannibalizeTaskGameCardGoodsListReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	resp, err := req.GetCannibalizeTaskGameCardGoodsList()
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "任务列表错误")
		return
	}

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

func CannibalizeTaskDel(c *gin.Context) {
	req := struct {
		CannibalizeStockTaskId uint32 `json:"cannibalize_stock_task_id"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	err := models.CannibalizeTaskDel(req.CannibalizeStockTaskId)
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "改任务状态不能删除")
	}

	app.OK(c, nil, "发货成功")
}
