package decision

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"
	"gorm.io/gorm"
	"net/http"
	"time"
)

// ErpMonthEndClosingList 财务月结-列表
// @Summary 财务月结-列表
// @Tags 决策中心，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.ErpMonthEndClosingListReq true "财务月结-列表模型"
// @Success 200 {object} models.ErpMonthEndClosingListResp
// @Router /api/v1/decision/month_end_closing/list [post]
func ErpMonthEndClosingList(c *gin.Context) {
	req := new(model.ErpMonthEndClosingListReq)
	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
	}

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

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

// ErpMonthEndClosingCreate 财务月结-新增
// @Summary 财务月结-新增
// @Tags 决策中心，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.ErpMonthEndClosingCreateReq true "财务月结-新增模型"
// @Success 200 {object} app.Response
// @Router /api/v1/decision/month_end_closing/create [post]
func ErpMonthEndClosingCreate(c *gin.Context) {
	req := new(model.ErpMonthEndClosingCreateReq)
	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
	}

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

	err = model.CreateErpMonthEndClosing(req, c)
	if err != nil {
		logger.Error("CreateErpMarketingCoupon err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, err.Error())
		return
	}

	app.OK(c, nil, "新增成功")
	return
}

// ErpMonthEndClosingAudit 财务月结-审核
// @Summary 财务月结-审核
// @Tags 决策中心，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.ErpMonthEndClosingAuditReq true "财务月结-审核模型"
// @Success 200 {object} app.Response
// @Router /api/v1/decision/month_end_closing/audit [post]
func ErpMonthEndClosingAudit(c *gin.Context) {
	req := new(model.ErpMonthEndClosingAuditReq)
	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
	}

	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 erpMonthEndOrder model.ErpMonthEndClosing
	err = orm.Eloquent.Table("erp_month_end_closing").Where("serial_number = ?", req.SerialNumber).
		Find(&erpMonthEndOrder).Error
	if err != nil {
		logger.Error("order err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "审核失败:"+err.Error())
		return
	}

	// 判断入参state：1-审核，2-取消审核
	orderState := 0
	switch req.State {
	case 1: // 1-审核：待审核状态可以审核
		if erpMonthEndOrder.State == model.ErpMonthEndClosingUnAudit {
			orderState = model.ErpMonthEndClosingAudited
		} else {
			app.OK(c, nil, "订单已审核")
			return
		}
	case 2: // 2-取消审核：不能跨月取消，如：2024/08，2024/09都已经审核，则2024/08不能取消审核，除非2024/09先取消审核
		if erpMonthEndOrder.State == model.ErpMonthEndClosingUnAudit {
			app.OK(c, nil, "订单已取消审核")
			return
		}

		// 检查是否存在跨月已审核记录
		var laterAuditCount int64
		err = orm.Eloquent.Table("erp_month_end_closing").
			Where("state = ? AND closing_start_date > ?", model.ErpMonthEndClosingAudited, erpMonthEndOrder.ClosingEndDate).
			Count(&laterAuditCount).Error
		if err != nil {
			logger.Error("check later audits err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, "取消审核失败:"+err.Error())
			return
		}
		if laterAuditCount > 0 {
			app.Error(c, http.StatusForbidden, nil, "存在更晚月份已审核记录，无法取消审核")
			return
		}

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

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

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

// ErpMonthEndClosingEdit 财务月结-编辑
// @Summary 财务月结-编辑
// @Tags 决策中心，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.ErpMonthEndClosingEditReq true "财务月结-编辑模型"
// @Success 200 {object} models.ErpMonthEndClosing
// @Router /api/v1/decision/month_end_closing/edit [post]
func ErpMonthEndClosingEdit(c *gin.Context) {
	req := new(model.ErpMonthEndClosingEditReq)
	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
	}

	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
	}

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

	app.OK(c, monthEndClosingOrder, "success")
}

// ErpMonthEndClosingDelete 财务月结-删除
// @Summary 财务月结-删除
// @Tags 决策中心，V1.4.0
// @Produce json
// @Accept json
// @Param request body models.ErpMonthEndClosingDeleteReq true "财务月结-删除模型"
// @Success 200 {object} app.Response
// @Router /api/v1/decision/month_end_closing/delete [post]
func ErpMonthEndClosingDelete(c *gin.Context) {
	var req = new(model.ErpMonthEndClosingDeleteReq)
	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
	}

	err = model.DeleteErpMonthEndClosing(req)
	if err != nil {
		logger.Error("DeleteErpMonthEndClosing err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, err.Error())
		return
	}

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

// ErpMonthEndClosingDate 财务月结-获取开始日期
// @Summary 财务月结-获取开始日期
// @Tags 决策中心，V1.4.0
// @Produce json
// @Accept json
// @Success 200 {object} models.ErpMonthEndClosingDateResp
// @Router /api/v1/decision/month_end_closing/start_date [get]
func ErpMonthEndClosingDate(c *gin.Context) {
	var latestClosing model.ErpMonthEndClosing
	err := orm.Eloquent.Table("erp_month_end_closing").
		Where("state = ?", model.ErpMonthEndClosingAudited).
		Order("closing_end_date DESC").
		First(&latestClosing).Error

	var startDate *time.Time
	if errors.Is(err, gorm.ErrRecordNotFound) {
		// 如果没有已审核记录，startDate 返回 nil
		startDate = nil
	} else if err != nil {
		// 数据库查询出错，返回错误响应
		logger.Error("query latest closing err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "获取开始日期失败")
		return
	} else {
		// 如果存在已审核记录，则取最晚的 ClosingEndDate 加 1 天
		nextDate := latestClosing.ClosingEndDate.AddDate(0, 0, 1)
		startDate = &nextDate
	}

	resp := model.ErpMonthEndClosingDateResp{}
	if startDate != nil {
		resp.StartDate = startDate.Format(model.DateTimeFormat)
	}

	app.OK(c, resp, "获取成功")
	return
}
