package repair

import (
	"errors"
	"fmt"
	"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"
)

// CreateRepair 新增维修订单
// @Summary 新增维修订单
// @Tags 维修管理，V1.4.6
// @Produce json
// @Accept json
// @Param request body models.RepairCreateReq true "新增维修订单模型"
// @Success 200 {object} models.RepairRecord
// @Router /api/v1/repair/create [post]
func CreateRepair(c *gin.Context) {
	var req = new(model.RepairCreateReq)
	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
	}

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

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

	app.OK(c, repairOrder, "维修单创建成功")
}

// EditRepair 编辑维修订单
// @Summary 编辑维修订单
// @Tags 维修管理，V1.4.6
// @Produce json
// @Accept json
// @Param request body models.RepairEditReq true "编辑维修订单模型"
// @Success 200 {object} models.RepairRecord
// @Router /api/v1/repair/edit [post]
func EditRepair(c *gin.Context) {
	var req = new(model.RepairEditReq)
	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
	}

	if len(req.Commodities) == 0 {
		logger.Error("repair 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
		}
	}

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

	repairOrder.Commodities = req.Commodities
	app.OK(c, repairOrder, "维修单编辑成功")
	return
}

// DeleteRepair 删除维修订单
// @Summary 删除维修订单
// @Tags 维修管理，V1.4.6
// @Produce json
// @Accept json
// @Param request body models.ErpRepairDeleteReq true "删除维修订单模型"
// @Success 200 {object} app.Response
// @Router /api/v1/repair/delete [post]
func DeleteRepair(c *gin.Context) {
	var req = new(model.ErpRepairDeleteReq)
	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 repairOrder model.RepairRecord
	err = orm.Eloquent.Table("repair_record").Where("serial_number = ?", req.SerialNumber).Find(&repairOrder).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(repairOrder.StoreId, sysUser) {
			app.Error(c, http.StatusInternalServerError, errors.New("操作失败：您没有该门店权限"), "操作失败：您没有该门店权限")
			return
		}
	}

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

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

	begin := orm.Eloquent.Begin()
	// 1-删除维修订单表
	err = begin.Delete(repairOrder).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.RepairRecordCommodity
	err = orm.Eloquent.Table("repair_record_commodity").Where("repair_record_id = ?", repairOrder.ID).Find(&commodities).Error
	if err != nil {
		logger.Error("query erp_purchase_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
}

// OrderList 查询维修订单列表
// @Summary 查询维修订单列表
// @Tags 维修管理，V1.4.6
// @Produce json
// @Accept json
// @Param request body models.ErpRepairOrderListReq true "查询维修订单列表模型"
// @Success 200 {object} models.ErpRepairOrderListResp
// @Router /api/v1/repair/list [post]
func OrderList(c *gin.Context) {
	req := &model.ErpRepairOrderListReq{}
	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("ErpPurchaseList err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "获取失败"+err.Error())
		return
	}

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

// OrderDetail 查询维修订单详情
// @Summary 查询维修订单详情
// @Tags 维修管理，V1.4.6
// @Produce json
// @Accept json
// @Param request body models.ErpRepairDetailReq true "查询维修订单详情模型"
// @Success 200 {object} models.RepairRecord
// @Router /api/v1/repair/detail [post]
func OrderDetail(c *gin.Context) {
	req := new(model.ErpRepairDetailReq)
	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
	}

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

	var repairOrder model.RepairRecord
	err = orm.Eloquent.Table("repair_record").Where("serial_number = ?", req.SerialNumber).Find(&repairOrder).Error
	if err != nil {
		logger.Error("repair_record err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, "获取失败")
		return
	}
	if repairOrder.ID == 0 {
		logger.Error("repair_record err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, fmt.Sprintf("未查询到维修订单[%s]", req.SerialNumber))
		return
	}
	// 校验入参门店是否包含在用户所有门店中，是否过期
	if !(tools.GetRoleName(c) == "admin" || tools.GetRoleName(c) == "系统管理员") {
		sysUser, err := model.GetSysUserByCtx(c)
		if err != nil {
			logger.Error("sys user err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, "操作失败")
			return
		}

		if !model.CheckUserStore(repairOrder.StoreId, sysUser) {
			app.Error(c, http.StatusInternalServerError, errors.New("操作失败：您没有该门店权限"), "操作失败：您没有该门店权限")
			return
		}
	}

	// 校验时间，如果为01-01-01 08:05，则赋值为空
	if repairOrder.MakerTime != nil && repairOrder.MakerTime.IsZero() {
		repairOrder.MakerTime = nil
	}

	if repairOrder.AuditTime != nil && repairOrder.AuditTime.IsZero() {
		repairOrder.AuditTime = nil
	}

	if repairOrder.SendTime != nil && repairOrder.SendTime.IsZero() {
		repairOrder.SendTime = nil
	}

	if repairOrder.CompletedTime != nil && repairOrder.CompletedTime.IsZero() {
		repairOrder.CompletedTime = nil
	}

	var repairCommodities []model.RepairRecordCommodity
	err = orm.Eloquent.Table("repair_record_commodity").Where("repair_record_id = ?", repairOrder.ID).
		Find(&repairCommodities).Error
	if err != nil {
		logger.Error("repair_record_commodity err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, "获取失败")
		return
	}

	// 添加商品名称
	for i, item := range repairCommodities {
		erpCommodity, _ := model.GetCommodity(item.CommodityId)
		repairCommodities[i].CommodityName = erpCommodity.Name
	}
	repairOrder.Commodities = repairCommodities

	// 添加门店名称
	store, _ := model.GetStore(repairOrder.StoreId)
	repairOrder.StoreName = store.Name

	// 添加维修单位名称
	supplier, _ := model.GetSupplierById(repairOrder.RepairUnitId)
	repairOrder.RepairUnitName = supplier.Name

	app.OK(c, repairOrder, "查询成功")
	return
}

// AuditRepair 审核维修订单
// @Summary 审核维修订单
// @Tags 维修管理，V1.4.6
// @Produce json
// @Accept json
// @Param request body models.ErpRepairAuditReq true "审核维修订单模型"
// @Success 200 {object} app.Response
// @Router /api/v1/repair/audit [post]
func AuditRepair(c *gin.Context) {
	var req = new(model.ErpRepairAuditReq)
	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 repairOrder model.RepairRecord
	err = orm.Eloquent.Table("repair_record").Where("serial_number = ?", req.SerialNumber).Find(&repairOrder).Error
	if err != nil {
		logger.Error("repair_record err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, "获取失败")
		return
	}
	if repairOrder.ID == 0 {
		logger.Error("repair_record err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, fmt.Sprintf("未查询到维修订单[%s]", req.SerialNumber))
		return
	}

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

	// 判断入参state：1-审核，2-取消审核
	orderState := 0
	switch req.State {
	case 1: // 1-审核：待审核状态可以审核
		if repairOrder.State == model.ErpRepairOrderUnAudit {
			orderState = model.ErpRepairOrderWaitRepair
		} else {
			app.OK(c, nil, "订单已审核")
			return
		}
	case 2: // 2-取消审核：4-已终止不能取消，1/2/3其他正常取消
		if repairOrder.State == model.ErpRepairOrderUnAudit {
			app.OK(c, nil, "订单已取消审核")
			return
		} else if repairOrder.State == model.ErpRepairOrderFinished {
			logger.Error("order err, repairOrder.State is:", logger.Field("repairOrder.State", repairOrder.State))
			app.Error(c, http.StatusInternalServerError, err, "取消审核失败:[已完成]订单不能取消")
			return
		} else {
			orderState = model.ErpPurchaseOrderUnAudit
		}
	default:
		logger.Error("order err, req.State is:", logger.Field("req.State", req.State))
		app.Error(c, http.StatusInternalServerError, err, "审核失败:参数有误")
		return
	}

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

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

// SendRepair 维修订单送修
// @Summary 维修订单送修
// @Tags 维修管理，V1.4.6
// @Produce json
// @Accept json
// @Param request body models.ErpRepairSendReq true "维修订单送修模型"
// @Success 200 {object} app.Response
// @Router /api/v1/repair/send [post]
func SendRepair(c *gin.Context) {
	req := &model.ErpRepairSendReq{}
	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
	}

	supplier, err := model.GetSupplierById(req.RepairUnitId)
	if err != nil || supplier.ID == 0 {
		app.Error(c, http.StatusBadRequest, err, "未查询到送修单位信息")
		return
	}

	err = model.SendToRepair(req, c)
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "操作失败:"+err.Error())
		return
	}

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

// CompleteRepair 维修订单完成
// @Summary 维修订单完成
// @Tags 维修管理，V1.4.6
// @Produce json
// @Accept json
// @Param request body models.ErpRepairCompleteReq true "维修订单完成模型"
// @Success 200 {object} app.Response
// @Router /api/v1/repair/complete [post]
func CompleteRepair(c *gin.Context) {
	req := &model.ErpRepairCompleteReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		//logger.Error(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.CompleteRepairOrder(req, c)
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "操作失败:"+err.Error())
		return
	}

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

// OrderDetailReport 维修明细
// @Summary 维修明细
// @Tags 维修管理，V1.4.6
// @Produce json
// @Accept json
// @Param request body models.ErpRepairDetailReportReq true "维修明细模型"
// @Success 200 {object} models.ErpRepairDetailReportResp
// @Router /api/v1/repair/detail_report [post]
func OrderDetailReport(c *gin.Context) {
	req := &model.ErpRepairDetailReportReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		//logger.Error(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
	}

	resp, err := model.RepairDetailReport(req, c)
	if err != nil {
		app.Error(c, http.StatusInternalServerError, err, "操作失败:"+err.Error())
		return
	}

	app.OK(c, resp, "查询成功")
	return
}
