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.WxMallApplyMapper;
import com.iformall.mapper.WxMsgConfigMapper;
import com.iformall.mapper.WxMsgValidationcodeMapper;
import com.iformall.mapper.WxMsgValidationcodeModelMapper;
import com.iformall.mq.MqBaseProducer;
import com.iformall.service.WxMallApplyService;
import org.apache.commons.collections.map.HashedMap;
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 WxMallApplyServiceImpl implements WxMallApplyService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    WxMallApplyMapper wxMallApplyMapper;

    @Autowired
    WxMsgValidationcodeMapper wxMsgValidationcodeMapper;

    @Autowired
    WxMsgConfigMapper wxMsgConfigMapper;

    @Autowired
    WxMsgValidationcodeModelMapper wxMsgValidationcodeModelMapper;

    @Autowired
    private MqBaseProducer mqBaseProducer;

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

    @Override
    public WxMallApply getById(String id) {
        return wxMallApplyMapper.selectById(id);
    }

    @Override
    public ResultData saveOrUpdate(WxMallApply record) {

        WxMsgValidationcode wxMsgValidationcode = new WxMsgValidationcode();
        wxMsgValidationcode.setTenantId("1");
        wxMsgValidationcode.setCode(record.getVerifyCode());
        wxMsgValidationcode.setPhone(record.getPhone());
        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_VERIFY_CODE_NOT_FOUND.getCode(),ErrorCode.MSG_VERIFY_CODE_NOT_FOUND.getMessage(),true);

        if (record.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            record.setApplyDate(new Date());
            wxMallApplyMapper.insert(record);
        } else {
            wxMallApplyMapper.updateById(record);
        }
        return new ResultData(200,"操作成功",true);
    }

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

        //3、从短信配置中查询密钥 bid 等信息
//        WxMsgConfig wxMsgConfig = new WxMsgConfig();
//        wxMsgConfig.setTenantId(wxMsgValidationcode.getTenantId());
//        List<WxMsgConfig> wxMsgConfigs = wxMsgConfigMapper.findList(wxMsgConfig);
//        if (wxMsgConfigs.size() == 0)  new ResultData(500,"发送失败");
//        wxMsgConfig = wxMsgConfigs.get(0);
//
//        WxMsgValidationcodeModel wxMsgValidationcodeModel = new WxMsgValidationcodeModel();
//        wxMsgValidationcodeModel.setTenantId(wxMsgConfig.getTenantId());
//        wxMsgValidationcodeModel.setType(wxMsgValidationcode.getType());
//        wxMsgValidationcodeModel.setName("验证码");
//        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();
//
//        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.insert(wxMsgValidationcode);
//            return new ResultData(Result.SUCCESS,"发送成功");
//        }

        //验证码
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        WxMsgRecord wxMsgRecord = new WxMsgRecord();
        wxMsgRecord.setMsgType(EnumMsgRecordType.SMS.getCode());
        wxMsgRecord.setModelType(wxMsgValidationcode.getType());
        wxMsgRecord.setReceiver(wxMsgValidationcode.getPhone());
        wxMsgRecord.setTenantId(wxMsgValidationcode.getTenantId());
        Map<String,String> map = new HashedMap();
        map.put("s6",String.valueOf(code));
        wxMsgRecord.setDynamicContentMap(map);
        mqBaseProducer.sendMessage(wxMsgRecord, EnumMsgMqTopic.DEFAULT.getCode(), EnumMsgMqTag.DEFAULT.getCode(), EnumMsgMqKey.DEFAULT.getCode());

        return new ResultData(Result.SUCCESS,"发送成功");
    }


}
