package purchasemanage

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

// ErpPurchaseChangeCreate 采购换机-新增
// @Summary 采购换机-新增
// @Tags 采购换机, V1.4.5
// @Produce json
// @Accept json
// @Param request body models.ErpPurchaseChangeCreateReq true "采购换机-新增模型"
// @Success 200 {object} models.ErpPurchaseChangeOrder
// @Router /api/v1/erp_purchase/change/create [post]
func ErpPurchaseChangeCreate(c *gin.Context) {
	req := new(model.ErpPurchaseChangeCreateReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.Error("ShouldBindJSON err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误"+err.Error())
		return
	}
	sysUser, err := model.GetSysUserByCtx(c)
	if err != nil {
		logger.Error("sys user err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	// 检验参数
	err = model.CheckCreateErpPurchaseChangeOrderParam(req)
	if err != nil {
		logger.Error("CheckCreateErpPurchaseOrderParam err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, err.Error())
		return
	}

	if len(req.Commodities) == 0 {
		logger.Error("erp purchase change commodities is nil")
		app.Error(c, http.StatusInternalServerError, err, "操作失败：未添加商品")
		return
	}

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

	purchaseOrder, err := model.CreateErpPurchaseChangeOrder(req, sysUser)
	if err != nil {
		logger.Error("CreateErpPurchaseOrder err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "新增失败:"+err.Error())
		return
	}

	purchaseOrder.Commodities = req.Commodities

	app.OK(c, purchaseOrder, "")
	return
}

// ErpPurchaseChangeEdit 采购换机-编辑
// @Summary 采购换机-编辑
// @Tags 采购换机, V1.4.5
// @Produce json
// @Accept json
// @Param request body models.ErpPurchaseChangeEditReq true "采购换机-编辑模型"
// @Success 200 {object} models.ErpPurchaseChangeOrder
// @Router /api/v1/erp_purchase/change/edit [post]
func ErpPurchaseChangeEdit(c *gin.Context) {
	req := new(model.ErpPurchaseChangeEditReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.Error("ShouldBindJSON err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误"+err.Error())
		return
	}

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

	// 检验参数
	err = model.CheckEditErpPurchaseChangeOrderParam(req)
	if err != nil {
		logger.Error("CheckEditErpPurchaseChangeOrderParam err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, err.Error())
		return
	}

	if len(req.Commodities) == 0 {
		logger.Error("erp purchase change commodities is nil")
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

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

	// 更新订单信息
	purchaseOrder, err := model.EditErpPurchaseChangeOrder(req, sysUser)
	if err != nil {
		logger.Error("EditErpPurchaseChangeOrder err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "编辑失败:"+err.Error())
		return
	}

	purchaseOrder.Commodities = req.Commodities
	app.OK(c, purchaseOrder, "")
	return
}

// ErpPurchaseChangeList 采购换机-列表
// @Summary 采购换机-列表
// @Tags 采购换机, V1.4.5
// @Produce json
// @Accept json
// @Param request body models.ErpPurchaseChangeOrderListReq true "采购换机列表模型"
// @Success 200 {object} models.ErpPurchaseChangeOrderListResp
// @Router /api/v1/erp_purchase/change/list [post]
func ErpPurchaseChangeList(c *gin.Context) {
	req := &model.ErpPurchaseChangeOrderListReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.Error("ShouldBindJSON err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	resp, err := req.List(c)
	if err != nil {
		logger.Error("ErpPurchaseChangeList err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "获取失败"+err.Error())
		return
	}

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

// ErpPurchaseChangeDelete 采购换机-删除
// @Summary 采购换机-删除
// @Tags 采购换机, V1.4.5
// @Produce json
// @Accept json
// @Param request body models.ErpPurchaseChangeDeleteReq true "采购换机-删除模型"
// @Success 200 {object} app.Response
// @Router /api/v1/erp_purchase/change/delete [post]
func ErpPurchaseChangeDelete(c *gin.Context) {
	var req = new(model.ErpPurchaseChangeDeleteReq)
	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
	}

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

	var erpPurchaseChangeOrder model.ErpPurchaseChangeOrder
	err = orm.Eloquent.Table("erp_purchase_change_order").Where("serial_number = ?", req.SerialNumber).Find(&erpPurchaseChangeOrder).Error
	if err != nil {
		logger.Error("order err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "删除失败:"+err.Error())
		return
	}

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

	if erpPurchaseChangeOrder.SerialNumber == "" {
		logger.Error("order is null")
		app.Error(c, http.StatusInternalServerError, err, "删除失败:订单不存在")
		return
	}

	// 仅待审核订单可删除
	if erpPurchaseChangeOrder.State != model.ErpPurchaseChangeOrderUnAudit {
		logger.Error("order err, erpPurchaseChangeOrder.State is:", logger.Field("erpPurchaseChangeOrder.State", erpPurchaseChangeOrder.State))
		app.Error(c, http.StatusInternalServerError, err, "删除失败:仅待审核订单可删除")
		return
	}

	begin := orm.Eloquent.Begin()
	// 1-删除采购订单表
	err = begin.Delete(erpPurchaseChangeOrder).Error
	if err != nil {
		begin.Rollback()
		logger.Error("order delete1 err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "删除失败:"+err.Error())
		return
	}

	// 2-删除采购订单商品表
	var commodities []model.ErpPurchaseChangeCommodity
	err = orm.Eloquent.Table("erp_purchase_change_commodity").Where("change_order_id = ?", erpPurchaseChangeOrder.ID).Find(&commodities).Error
	if err != nil {
		logger.Error("query erp_purchase_change_commodity err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "删除失败:"+err.Error())
		return
	}

	if len(commodities) != 0 {
		err = begin.Delete(&commodities).Error
		if err != nil {
			begin.Rollback()
			logger.Error("更新商品订单信息-删除 error")
			app.Error(c, http.StatusInternalServerError, err, "删除失败:"+err.Error())
			return
		}
	}

	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Error("commit err:", logger.Field("err", err))
		return
	}

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

// ErpPurchaseChangeAudit 采购换机-审核
// @Summary 采购换机-审核
// @Tags 采购换机, V1.4.5
// @Produce json
// @Accept json
// @Param request body models.ErpPurchaseChangeAuditReq true "采购换机-审核模型"
// @Success 200 {object} app.Response
// @Router /api/v1/erp_purchase/change/audit [post]
func ErpPurchaseChangeAudit(c *gin.Context) {
	var req = new(model.ErpPurchaseChangeAuditReq)
	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
	}

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

	var erpPurchaseChangeOrder model.ErpPurchaseChangeOrder
	err = orm.Eloquent.Table("erp_purchase_change_order").Where("serial_number = ?", req.SerialNumber).
		Find(&erpPurchaseChangeOrder).Error
	if err != nil {
		logger.Error("order err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "审核失败:"+err.Error())
		return
	}

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

	begin := orm.Eloquent.Begin()
	// 判断入参state：1-审核，2-取消审核
	orderState := 0
	switch req.State {
	case 1: // 1-审核：待审核状态可以审核
		if erpPurchaseChangeOrder.State == model.ErpPurchaseChangeOrderUnAudit {
			orderState = model.ErpPurchaseChangeOrderFinished
		} else {
			app.OK(c, nil, "订单已审核")
			return
		}
	case 2: // 2-取消审核：取消后对应的退库或入库
		if erpPurchaseChangeOrder.State == model.ErpPurchaseChangeOrderUnAudit {
			app.OK(c, nil, "订单已取消审核")
			return
		}
		if model.IsMonthEndClosed(*erpPurchaseChangeOrder.AuditTime) {
			app.Error(c, http.StatusInternalServerError, errors.New("反审核失败，财务已月结"),
				"反审核失败，财务已月结")
			return
		}

		orderState = model.ErpPurchaseChangeOrderUnAudit
	default:
		logger.Error("order err, req.State is:", logger.Field("req.State", req.State))
		app.Error(c, http.StatusInternalServerError, err, "审核失败:参数有误")
		return
	}

	// 更新库存信息
	// 审核：旧机器出库、新机器入库
	// 反审核：旧机器入库、新机器出库
	err = model.AuditChangeOrder(begin, erpPurchaseChangeOrder, req.State)
	if err != nil {
		begin.Rollback()
		app.Error(c, http.StatusInternalServerError, err, "审核失败:"+err.Error())
		return
	}

	err = begin.Table("erp_purchase_change_order").Where("id = ?", erpPurchaseChangeOrder.ID).
		Updates(map[string]interface{}{
			"state":        orderState,
			"auditor_id":   sysUser.UserId,
			"audit_time":   time.Now(),
			"auditor_name": sysUser.NickName,
		}).Error
	if err != nil {
		begin.Rollback()
		logger.Error("update erp_purchase_change_order err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "审核失败:"+err.Error())
		return
	}

	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("commit err:", err)
		app.Error(c, http.StatusInternalServerError, err, "审核失败")
		return
	}

	app.OK(c, nil, "操作成功")
	return
}
