package admin_agent

import (
	"context"
	"fmt"

	"jnc-server/app/main/api/internal/svc"
	"jnc-server/app/main/api/internal/types"
	"jnc-server/common/xerr"
	"jnc-server/pkg/lzkit/crypto"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	"github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AdminSendAgentComplaintNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminSendAgentComplaintNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminSendAgentComplaintNotifyLogic {
	return &AdminSendAgentComplaintNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminSendAgentComplaintNotifyLogic) AdminSendAgentComplaintNotify(req *types.AdminSendAgentComplaintNotifyReq) (resp *types.AdminSendAgentComplaintNotifyResp, err error) {
	// 1. 查询代理信息
	agent, err := l.svcCtx.AgentModel.FindOne(l.ctx, req.AgentId)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询代理信息失败: %v", err)
	}

	// 2. 解密手机号
	mobile, err := crypto.DecryptMobile(agent.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解密手机号失败: %v", err)
	}

	// 3. 发送短信
	smsResp, err := l.sendSmsRequest(mobile, req.UserName)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "发送短信失败: %v", err)
	}

	// 4. 检查发送结果
	if *smsResp.Body.Code != "OK" {
		return &types.AdminSendAgentComplaintNotifyResp{
			Success: false,
			Message: fmt.Sprintf("短信发送失败: %s", *smsResp.Body.Message),
		}, nil
	}

	resp = &types.AdminSendAgentComplaintNotifyResp{
		Success: true,
		Message: "投诉通知发送成功",
	}
	return
}

// CreateClient 创建阿里云短信客户端
func (l *AdminSendAgentComplaintNotifyLogic) CreateClient() (*dysmsapi.Client, error) {
	config := &openapi.Config{
		AccessKeyId:     &l.svcCtx.Config.VerifyCode.AccessKeyID,
		AccessKeySecret: &l.svcCtx.Config.VerifyCode.AccessKeySecret,
	}
	config.Endpoint = tea.String(l.svcCtx.Config.VerifyCode.EndpointURL)
	return dysmsapi.NewClient(config)
}

// sendSmsRequest 发送投诉通知短信请求
func (l *AdminSendAgentComplaintNotifyLogic) sendSmsRequest(mobile, userName string) (*dysmsapi.SendSmsResponse, error) {
	// 初始化阿里云短信客户端
	cli, err := l.CreateClient()
	if err != nil {
		return nil, err
	}

	request := &dysmsapi.SendSmsRequest{
		SignName:      tea.String(l.svcCtx.Config.VerifyCode.SignName),
		TemplateCode:  tea.String(l.svcCtx.Config.VerifyCode.ComplaintTemplate),
		PhoneNumbers:  tea.String(mobile),
		TemplateParam: tea.String(fmt.Sprintf("{\"name\":\"%s\"}", userName)),
	}
	runtime := &service.RuntimeOptions{}
	return cli.SendSmsWithOptions(request, runtime)
}
