package seal

import (
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	contractService "hongze/hz_crm_api/services/contract"
	"hongze/hz_crm_api/services/seal"
	"path"
	"strconv"
)

// 用印管理
type SealController struct {
	controllers.BaseAuthController
}

// 上传签回附件
// @Title 上传签回附件
// @Description 上传签回附件
// @Param	request	body request.SealUploadCheckBackFileReq true "type json string"
// @Success 200 上传成功
// @router /uploadCheckBackFile [post]
func (this *SealController) UploadCheckBackFile() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser is Empty"
		br.Ret = 408
		return
	}

	sealIdStr := this.Ctx.Request.Form.Get("SealId")
	if sealIdStr == "" {
		br.Msg = "用印ID丢失！"
		br.ErrMsg = "用印ID丢失！"
		return
	}
	sealId, err := strconv.Atoi(sealIdStr)
	if err != nil {
		br.Msg = "用印ID异常！"
		br.ErrMsg = "用印ID异常，Err:" + err.Error()
		return
	}
	fileMulti, h, err := this.GetFile("file")
	if err != nil {
		br.Msg = "获取资源信息失败"
		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
		return
	}
	// 用印ID
	if sealId <= 0 {
		br.Msg = "请传入用印编号！"
		br.ErrMsg = "请传入用印编号"
		return
	}
	ext := path.Ext(h.Filename)
	sealInfo, err := seal.UploadCheckBackFileFromSeal(sealId, ext, fileMulti, sysUser)
	if err != nil {
		br.Msg = "更新签回附件失败！"
		br.ErrMsg = "更新签回附件失败，Err:" + err.Error()
		return
	}
	// 如果是系统合同，那么需要去更新系统的签回附件
	if sealInfo.ContractId > 0 {
		err = contractService.UploadCheckBackFileFromSeal(sealInfo.ContractId, sealInfo.CheckBackFileUrl, sysUser)
		if err != nil {
			br.Msg = "更新系统合同状态失败！"
			br.ErrMsg = "更新系统合同状态失败，Err:" + err.Error()
			return
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "上传成功"
}
