package com.iformall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.*;
import com.iformall.domain.po.msg.WxMsgRecord;
import com.iformall.enums.*;
import com.iformall.mapper.*;
import com.iformall.mq.MqBaseProducer;
import com.iformall.service.WxMsgValidationcodeService;
import com.iformall.utils.DateUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WxMsgValidationcodeServiceImpl implements WxMsgValidationcodeService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxMsgValidationcodeMapper wxMsgValidationcodeMapper;

    @Autowired
    WxMsgConfigMapper wxMsgConfigMapper;

    @Autowired
    WxMallMapper wxMallMapper;

    @Autowired
    WxMsgValidationcodeModelMapper wxMsgValidationcodeModelMapper;

    @Autowired
    WxMerchantBUserMapper wxMerchantBUserMapper;

    @Autowired
    WxMerchantMapper wxMerchantMapper;

    @Autowired
    WxMsgCallbackMapper wxMsgCallbackMapper;

    @Autowired
    MqBaseProducer mqBaseProducer;

    @Override
    public PageInfo<WxMsgValidationcode> listAsPage(WxMsgValidationcode record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxMsgValidationcodeMapper.findList(record));
    }

    @Override
    public WxMsgValidationcode getById(Long id) {
        return wxMsgValidationcodeMapper.selectById(id);
    }

    @Override
    public void saveOrUpdate(WxMsgValidationcode record) {
        if (record.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());

            wxMsgValidationcodeMapper.insert(record);
        } else {
            wxMsgValidationcodeMapper.updateById(record);
        }
    }

    @Override
    public void deleteById(Long id) {
        wxMsgValidationcodeMapper.deleteById(id);
    }


    @Override
    public ResultData sendvalidationcode(WxMsgValidationcode wxMsgValidationcode) {
        //1、查看是否存在未过期的短信,有返回成功 没有继续
        List<WxMsgValidationcode> wxmsgvalidationcodelist = wxMsgValidationcodeMapper.findList(wxMsgValidationcode);
        Date currentdate = new Date();
        wxmsgvalidationcodelist = wxmsgvalidationcodelist.stream().filter(validationcode ->
                validationcode.getExpiretime().after(currentdate)).collect(Collectors.toList());
        if (wxmsgvalidationcodelist.size() > 0) {
            return new ResultData(ErrorCode.MSG_REPEAT_SEND);
        }
        //2 判断是否已超过3条
        String systemTime = DateUtils.getSystemTime("yyyy-MM-dd");
        wxMsgValidationcode.setCreatetimeStr(systemTime);
        List<WxMsgValidationcode> list = wxMsgValidationcodeMapper.findList(wxMsgValidationcode);
        if (list.size() == 3) {
            return new ResultData(ErrorCode.MSG_SEND_ERROR.getCode(), "验证码发送超限");
        }

        //验证码
        int code = (int) ((Math.random() * 9 + 1) * 100000);

        //给发起人发送驳回消息
        Map<String,String> msgReplaceMap = new HashedMap();
        msgReplaceMap.put("s6",String.valueOf(code));
        WxMsgRecord wxMsgRecord = new WxMsgRecord();
        wxMsgRecord.setMsgType(EnumMsgRecordType.SMS.getCode());
        wxMsgRecord.setModelType(EnumMsgModel.VALIDATION_CODE.getCode());
        wxMsgRecord.setReceiver(wxMsgValidationcode.getPhone());
        wxMsgRecord.setTenantId(wxMsgValidationcode.getTenantId());
        wxMsgRecord.setDynamicContentMap(msgReplaceMap);
        mqBaseProducer.sendMessage(wxMsgRecord, EnumMsgMqTopic.DEFAULT.getCode(),EnumMsgMqTag.DEFAULT.getCode(),EnumMsgMqKey.DEFAULT.getCode());
        return new ResultData(Result.SUCCESS,"发送成功");
    }

    @Override
    public void addMsgCallback(WxMsgValidationcode wxmsg, String batchNo, String id) {
        logger.info("验证码发送时主动添加回调记录开始...");
        String phone = wxmsg.getPhone();
        final IdWorker idWorker = IdWorker.get();
        WxMsgCallback wxMsgCallback = new WxMsgCallback();
        wxMsgCallback.setId(idWorker.nextId());
        wxMsgCallback.setPhone(phone);
        wxMsgCallback.setTenantId(wxmsg.getTenantId());
        wxMsgCallback.setBatchNo(batchNo);
        wxMsgCallback.setMsgId(wxmsg.getId());
        wxMsgCallback.setStatus(EnumMsgSendStatus.MSG_SEND_FAIL.getCode());
        wxMsgCallback.setCreatetime(new Date());
        if (StringUtils.isNotEmpty(id)) {
            wxMsgCallback.setBusinessId(Long.parseLong(id));
        }
        wxMsgCallbackMapper.insert(wxMsgCallback);
        logger.info("验证码发送时主动添加回调记录结束...");
    }

    @Override
    public ResultData hasvalidationcode(WxMsgValidationcode record) {


        List<WxMsgValidationcode> wxmsgvalidationcodelist = wxMsgValidationcodeMapper.findList(record);
        Date currentdate = new Date();
        wxmsgvalidationcodelist = wxmsgvalidationcodelist.stream().filter(validationcode ->
                validationcode.getExpiretime().after(currentdate)).collect(Collectors.toList());
        if(wxmsgvalidationcodelist.size()>0) return new ResultData(Result.SUCCESS,"验证码存在",true);

        return new ResultData(Result.ERROR,"验证码不存在或过期",false);

    }


}
