package com.iformall.service.impl;

import com.alibaba.fastjson.JSONObject;
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.enums.EnumMsgModel;
import com.iformall.enums.EnumMsgSendStatus;
import com.iformall.enums.EnumVerifyCode;
import com.iformall.mapper.*;
import com.iformall.service.WxMsgValidationcodeService;
import com.iformall.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
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;

    @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.selectByPrimaryKey(id);
    }

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

            wxMsgValidationcodeMapper.insertSelective(record);
        } else {
            wxMsgValidationcodeMapper.updateByPrimaryKeySelective(record);
        }
    }

    @Override
    public void deleteById(Long id) {
        wxMsgValidationcodeMapper.deleteByPrimaryKey(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.getCode(),ErrorCode.MSG_REPEAT_SEND.getMessage());


        //2、根据tenantid查询出商场名称作为签名
        /*WxMall wxMall = new WxMall();
        wxMall.setTenantId(wxMsgValidationcode.getTenantId());
        List<WxMall> wxmallist = wxMallMapper.findList(wxMall);*/


        //3、从短信配置中查询密钥 bid 等信息
        WxMsgConfig wxMsgConfig = new WxMsgConfig();
        wxMsgConfig.setTenantId(wxMsgValidationcode.getTenantId());
        List<WxMsgConfig> wxMsgConfigs = wxMsgConfigMapper.findList(wxMsgConfig);
        if (wxMsgConfigs.size() == 0)  new ResultData(ErrorCode.MSG_SEND_ERROR.getCode(),"发送失败");
        wxMsgConfig = wxMsgConfigs.get(0);

        WxMsgValidationcodeModel wxMsgValidationcodeModel = new WxMsgValidationcodeModel();
        wxMsgValidationcodeModel.setTenantId(wxMsgConfig.getTenantId());
        wxMsgValidationcodeModel.setType(EnumMsgModel.VALIDATION_CODE.getCode());
        wxMsgValidationcodeModel = wxMsgValidationcodeModelMapper.findList(wxMsgValidationcodeModel).get(0);
        wxMsgValidationcode.setSignature(wxMsgValidationcodeModel.getSignature());


        String secret = wxMsgConfig.getSecret();
        String bid = wxMsgConfig.getBid();
        String publickey = wxMsgConfig.getPublickey();
        //验证码
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String phone = wxMsgValidationcode.getPhone();
        String signature = wxMsgValidationcode.getSignature();
        //内容
        String msg = wxMsgValidationcodeModel.getContent().replace("{s6}", String.valueOf(code));
        wxMsgValidationcode.setCode(String.valueOf(code));
        wxMsgValidationcode.setMsg(msg);
        String notifyUrl = wxMsgConfig.getNotifyurl();
        Integer modelId = wxMsgValidationcodeModel.getModelId();
        String result = WiwideUtil.sendMsg(secret, bid, publickey, phone, signature, msg, notifyUrl, EnumVerifyCode.YES.getCode().toString(), modelId);
        JSONObject jsonObjectResult = JSONObject.parseObject(result);
        String ret = jsonObjectResult.get("ret").toString();
        String batchNo = jsonObjectResult.get("data").toString();
        if (ret.equals("1")) {
            final IdWorker idWorker = IdWorker.get();
            wxMsgValidationcode.setId(idWorker.nextId());
            long currentTime = System.currentTimeMillis() ;
            Date createtime=new Date(currentTime);
            Integer minutes = wxMsgValidationcodeModel.getMinutes();
            currentTime +=minutes*60*1000;
            Date expiredate=new Date(currentTime);
            wxMsgValidationcode.setExpiretime(expiredate);
            wxMsgValidationcode.setCreatetime(createtime);
            wxMsgValidationcodeMapper.insertSelective(wxMsgValidationcode);
            addMsgCallback(wxMsgValidationcode,batchNo);
            return new ResultData(Result.SUCCESS,"发送成功");
        }
        return new ResultData(ErrorCode.MSG_SEND_ERROR.getCode(),"发送失败");

    }

    @Override
    public void addMsgCallback(WxMsgValidationcode wxmsg, String batchNo){
        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());
        wxMsgCallbackMapper.insertSelective(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);

    }


}
