package account

import (
	"errors"
	"mtp20access/global"
	"mtp20access/model/account/request"
	"mtp20access/model/common/response"
	signService "mtp20access/service/sign"
	"mtp20access/utils"
	"net/http"
	"net/url"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// QueryUserESignRecord 查询用户电子签记录表
// @Summary  查询用户电子签记录表
// @Security ApiKeyAuth
// @accept   application/json
// @Produce  application/json
// @Success  200 {object} response.Response{data=[]account.Useresignrecord,msg=string} "出参"
// @Router   /Account/QueryUserESignRecord [get]
// @Tags     账户服务
func QueryUserESignRecord(c *gin.Context) {
	g := utils.GinUtils{C: c}

	// 获取请求账号信息
	claims := g.GetClaims()
	if g.Err != nil {
		return
	}

	if rsp, err := signService.QueryUserESignRecord(claims.UserID); err == nil {
		response.OkWithDetailed(rsp, "查询成功", g.C)
	} else {
		global.M2A_LOG.Error(err.Error(), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
	}
}

// AddUser 实名认证添加用户
// @Summary  实名认证添加用户
// @Security ApiKeyAuth
// @accept   application/json
// @Produce  application/json
// @Param    data body     request.AddUserReq            true "入参"
// @Success  200  {object} response.Response{msg=string} "出参"
// @Router   /Account/AddUser [post]
// @Tags     账户服务
func AddUser(c *gin.Context) {
	g := utils.GinUtils{C: c}
	r := request.AddUserReq{}
	g.BindJsonReq(&r)
	if g.Err != nil {
		return
	}

	// 获取请求账号信息
	claims := g.GetClaims()
	if g.Err != nil {
		return
	}

	if err := signService.AddUser(r, claims.UserID); err == nil {
		response.Ok(g.C)
	} else {
		global.M2A_LOG.Error(err.Error(), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
	}
}

// CreateContractAndAddSigner 上传待签署文件和添加签署方
// @Summary  上传待签署文件和添加签署方
// @Security ApiKeyAuth
// @accept   application/json
// @Produce  application/json
// @Param    data body     request.CreateContractAndAddSignerReq     true "入参"
// @Success  200  {object} response.Response{data=string,msg=string} "出参"
// @Router   /Account/CreateContractAndAddSigner [post]
// @Tags     账户服务
func CreateContractAndAddSigner(c *gin.Context) {
	g := utils.GinUtils{C: c}
	r := request.CreateContractAndAddSignerReq{}
	g.BindJsonReq(&r)
	if g.Err != nil {
		return
	}

	// 获取请求账号信息
	claims := g.GetClaims()
	if g.Err != nil {
		return
	}

	if rsp, err := signService.CreateContractAndAddSigner(r, claims.UserID); err == nil {
		response.OkWithDetailed(rsp, "操作成功", g.C)
	} else {
		global.M2A_LOG.Error(err.Error(), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
	}
}

// SignCompleted 提交实名认证
// @Summary  提交实名认证
// @Security ApiKeyAuth
// @accept   application/json
// @Produce  application/json
// @Success  200 {object} response.Response{msg=string} "出参"
// @Router   /Account/SignCompleted [post]
// @Tags     账户服务
func SignCompleted(c *gin.Context) {
	g := utils.GinUtils{C: c}

	// 获取请求账号信息
	claims := g.GetClaims()
	if g.Err != nil {
		return
	}

	if err := signService.SignCompleted(claims.UserID); err == nil {
		response.OkWithMessage("提交成功", g.C)
	} else {
		global.M2A_LOG.Error(err.Error(), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
	}
}

// 爱签合同签署完成后异步通知 POST
func HandleASignCompleted(c *gin.Context) {
	g := utils.GinUtils{C: c}

	// global.M2A_LOG.Info("[HandleASignCompleted] 接收爱签爱签合同签署完成后异步通知", zap.Any("url", g.C.Request.URL))

	action, ok := g.C.GetPostForm("action")
	if !ok {
		err := errors.New("[HandleASignCompleted] 获取action失败")
		response.FailWithMessage(err.Error(), c)
		return
	}
	contractNo, ok := g.C.GetPostForm("contractNo")
	if !ok {
		err := errors.New("[HandleASignCompleted] 获取contractNo失败")
		response.FailWithMessage(err.Error(), c)
		return
	}
	status, ok := g.C.GetPostForm("status")
	if !ok {
		err := errors.New("[HandleASignCompleted] 获取status失败")
		response.FailWithMessage(err.Error(), c)
		return
	}

	if action == "signCompleted" {
		if err := signService.HandleASignCompleted(contractNo, status); err == nil {
			g.C.String(http.StatusOK, "%s", "ok")
		} else {
			global.M2A_LOG.Error(err.Error(), zap.Error(err))
			response.FailWithMessage(err.Error(), c)
		}
	} else {
		err := errors.New("[HandleASignCompleted] 暂不支持的action")
		response.FailWithMessage(err.Error(), c)
	}
}

// WillFace 个人意愿核身认证
// @Summary  个人意愿核身认证
// @Security ApiKeyAuth
// @accept   application/json
// @Produce  application/json
// @Param    data body     request.WillFaceReq                       true "入参"
// @Success  200  {object} response.Response{data=string,msg=string} "出参"
// @Router   /Account/WillFace [post]
// @Tags     账户服务
func WillFace(c *gin.Context) {
	g := utils.GinUtils{C: c}
	r := request.WillFaceReq{}
	g.BindJsonReq(&r)
	if g.Err != nil {
		return
	}

	// 获取请求账号信息
	claims := g.GetClaims()
	if g.Err != nil {
		return
	}

	if rsp, err := signService.WillFace(r, claims.UserID); err == nil {
		response.OkWithDetailed(rsp, "操作成功", g.C)
	} else {
		global.M2A_LOG.Error(err.Error(), zap.Error(err))
		response.FailWithMessage(err.Error(), c)
	}
}

// 爱签个人意愿核身认证接口异步通知 GET
func HandleWillFace(c *gin.Context) {
	g := utils.GinUtils{C: c}

	global.M2A_LOG.Info("[HandleWillFace] 接收爱签个人意愿核身认证接口异步通知", zap.Any("url", g.C.Request.URL))

	sign := g.C.Query("sign")
	result := g.C.Query("result")
	msg := g.C.Query("msg")
	recordId := g.C.Query("recordId")
	if sign == "" || result == "" || msg == "" || recordId == "" {
		g.C.String(http.StatusOK, "提交信息失败，请关闭此页面稍后重试")
		return
	}

	if result != "1" {
		// 认证失败
		t, _ := url.QueryUnescape(msg)
		if t == "" {
			t = "提交信息失败，请关闭此页面稍后重试."
		}
		g.C.String(http.StatusOK, t)
		return
	}

	if err := signService.HandleWillFace(sign, result, msg, recordId); err == nil {
		g.C.String(http.StatusOK, "提交信息成功，请关闭此页面")
	} else {
		global.M2A_LOG.Error(err.Error(), zap.Error(err))
		// response.FailWithMessage(err.Error(), c)
		g.C.String(http.StatusOK, "提交信息失败，请关闭此页面稍后重试")
	}
}
