package cn.axzo.msg.center.notices.service.impl;

import cn.axzo.basics.common.exception.ServiceException;
import cn.axzo.msg.center.api.MNSNoticesApi;
import cn.axzo.msg.center.api.request.MnsCodeStatusReq;
import cn.axzo.msg.center.api.request.MnsCreateTemplateRequestReq;
import cn.axzo.msg.center.api.request.MnsQueryTemplateReq;
import cn.axzo.msg.center.api.request.MnsSendCodeV2Req;
import cn.axzo.msg.center.api.request.SendMessageRequestDto;
import cn.axzo.msg.center.api.response.MnsCodeStatusRes;
import cn.axzo.msg.center.api.response.MnsQueryTemplateRes;
import cn.axzo.msg.center.api.response.MnsSendCodeRes;
import cn.axzo.msg.center.api.response.Page;
import cn.axzo.msg.center.common.utils.BeanConvertUtils;
import cn.axzo.msg.center.notices.common.enums.ReturnCodeEnum;
import cn.axzo.msg.center.notices.manager.api.dto.request.MnsRequestDto;
import cn.axzo.msg.center.notices.manager.api.dto.request.plat.CreateTemplateRequestDto;
import cn.axzo.msg.center.notices.manager.api.dto.request.plat.QueryTemplateRequestDto;
import cn.axzo.msg.center.notices.manager.api.dto.response.plat.QueryTemplateResponseDto;
import cn.axzo.msg.center.notices.service.SmsService;
import cn.axzo.msg.center.notices.service.api.MessageService;
import cn.axzo.msg.center.notices.service.api.PlatService;
import cn.axzo.msg.center.notices.service.request.CodeStatusReq;
import cn.axzo.msg.center.notices.service.request.SendCodeV2Req;
import cn.axzo.msg.center.notices.service.response.CodeStatusRes;
import cn.axzo.msg.center.notices.service.response.SendCodeRes;
import cn.azxo.framework.common.model.CommonResponse;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Service
@Slf4j
@RestController
public class MNSNoticesApiImpl implements MNSNoticesApi {

    private static final String LOG_PREFIX = "[MNSNoticesApi]";

    @Resource
    private SmsService smsService;
    @Resource
    private PlatService platService;

    /**
     * 手机正则
     */
    private Pattern phonePattern = Pattern.compile("^[1]\\d{10}$");

    @Resource
    private MessageService messageService;

    @Override
    public CommonResponse<Void> sendMessage(@RequestBody @Valid SendMessageRequestDto request) {
        MnsRequestDto mnsRequestDto=new MnsRequestDto();
        BeanUtils.copyProperties(request, mnsRequestDto);
        log.info("request value={},mnsRequestDto value={}", JSONUtil.toJsonStr(request),JSONUtil.toJsonStr(mnsRequestDto));
        try {
            mnsRequestDto.setInternalObj(MnsType.BIZ);
            messageService.sendMessage(mnsRequestDto);
            return CommonResponse.success();
        } catch (Exception e) {
            log.warn("{}#sendMessage broke out some exception", LOG_PREFIX, e);
            Integer errCode = e instanceof ServiceException ? ((ServiceException)e).getErrorCode() :
                    ReturnCodeEnum.SYSTEM_ERROR.getCode();
            return CommonResponse.error(errCode, e.getMessage());
        }
    }

    @Override
    public CommonResponse<MnsSendCodeRes> sendCodeV2(@RequestBody @Valid MnsSendCodeV2Req req) {
        if (!phonePattern.matcher(req.getPhone()).matches()) {
            throw new ServiceException("手机号格式不正确");
        }
        SendCodeV2Req request=new SendCodeV2Req();
        BeanUtils.copyProperties(req,request);
        SendCodeRes temp = smsService.sendPhoneCodeV2(request);
        MnsSendCodeRes result=new MnsSendCodeRes();
        if(temp == null){
            return CommonResponse.success(result);
        }
        BeanUtils.copyProperties(temp,result);
        return CommonResponse.success(result);
    }

    @Override
    public CommonResponse<MnsCodeStatusRes> getPhoneCodeStatus(@RequestBody @Valid MnsCodeStatusReq req) {
        CodeStatusReq request=new CodeStatusReq();
        BeanUtils.copyProperties(req,request);
        try {
            CodeStatusRes phoneCodeStatus = smsService.getPhoneCodeStatus(request);
            MnsCodeStatusRes result=new MnsCodeStatusRes();
            BeanUtils.copyProperties(phoneCodeStatus,result);
            return CommonResponse.success(result);
        } catch (Exception e) {
            log.warn("{}#getPhoneCodeStatus broke out some exception", LOG_PREFIX, e);
            Integer errCode = e instanceof ServiceException ? ((ServiceException)e).getErrorCode() :
                    ReturnCodeEnum.SYSTEM_ERROR.getCode();
            return CommonResponse.error(errCode, e.getMessage());
        }
    }

    @Override
    public CommonResponse<Object> createTemplate(MnsCreateTemplateRequestReq request) {
        CreateTemplateRequestDto templateDto = BeanConvertUtils.copyBean(request, CreateTemplateRequestDto.class);
        platService.createTemplate(templateDto);
        return CommonResponse.success();
    }

    @Override
    public CommonResponse<MnsQueryTemplateRes> getByTemplateNo(String templateNo) {
        QueryTemplateResponseDto templateRes = platService.getByTemplateNo(templateNo);
        if(templateRes == null){
            return CommonResponse.success(null);
        }
        MnsQueryTemplateRes queryTemplate = BeanConvertUtils.copyBean(templateRes, MnsQueryTemplateRes.class);
        return CommonResponse.success(queryTemplate);
    }

    @Override
    public CommonResponse<Page<MnsQueryTemplateRes>> list(MnsQueryTemplateReq request) {
        QueryTemplateRequestDto req = BeanConvertUtils.copyBean(request, QueryTemplateRequestDto.class);
        cn.axzo.msg.center.notices.common.lang.Page<QueryTemplateResponseDto> templatePage = platService.list(req);
        if(templatePage == null){
            return CommonResponse.success(null);
        }
        Page<MnsQueryTemplateRes> result = convert2MnsQueryTemplateRes(templatePage);
        return CommonResponse.success(result);
    }

    /**
     * 转换成MnsQueryTemplateRes
     * @param templatePage
     * @return
     */
    private Page<MnsQueryTemplateRes> convert2MnsQueryTemplateRes(cn.axzo.msg.center.notices.common.lang.Page<QueryTemplateResponseDto> templatePage){
        List<MnsQueryTemplateRes> templateList=new ArrayList<>();
        for (QueryTemplateResponseDto item : templatePage.getList()) {
            MnsQueryTemplateRes templateRes = BeanConvertUtils.copyBean(item, MnsQueryTemplateRes.class);
            templateList.add(templateRes);
        }
        Page<MnsQueryTemplateRes> result=new Page<>();
        result.setList(templateList);
        result.setTotalElements(templatePage.getTotalElements());
        result.setPageNum(templatePage.getPageNum());
        result.setPageSize(templatePage.getPageSize());
        log.info("before templatePage value={},after result value={}",JSONUtil.toJsonStr(templatePage),JSONUtil.toJsonStr(result));
        return result;
    }

    @Override
    public CommonResponse<Object> delete(String templateNo) {
        platService.delete(templateNo);
        return CommonResponse.success();
    }
}
