package com.iformall.service.msg.impl;

import com.alibaba.fastjson.JSONObject;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.domain.po.*;
import com.iformall.domain.po.msg.BaseMsg;
import com.iformall.domain.po.msg.WxMsgRecord;
import com.iformall.enums.EnumMsgOpen;
import com.iformall.enums.EnumVerifyCode;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxMsgConfigMapper;
import com.iformall.mapper.WxMsgValidationcodeMapper;
import com.iformall.mapper.WxMsgValidationcodeModelMapper;
import com.iformall.service.msg.MsgSendService;
import com.iformall.service.WxMsgValidationcodeService;
import com.iformall.utils.WiwideUtil;
import org.apache.commons.collections.CollectionUtils;
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;

/**
 * @author luozukai
 * 短信发送实现
 */
@Service
public class SendSmsServiceImpl implements MsgSendService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxMsgConfigMapper wxMsgConfigMapper;
    @Autowired
    private WxMsgValidationcodeModelMapper wxMsgValidationcodeModelMapper;
    @Autowired
    private WxMsgValidationcodeMapper wxMsgValidationcodeMapper;
    @Autowired
    private WxMsgValidationcodeService wxMsgValidationcodeService;

    @Override
    public void send(BaseMsg baseMsg) throws Exception{
        WxMsgRecord record = (WxMsgRecord)baseMsg;
        WxMsgValidationcode wxMsgValidationcode = new WxMsgValidationcode();
        wxMsgValidationcode.setPhone(record.getReceiver());
        wxMsgValidationcode.setTenantId(record.getTenantId());
        wxMsgValidationcode.setType(record.getModelType());

        //3、从短信配置中查询密钥 bid 等信息
        WxMsgConfig wxMsgConfig = new WxMsgConfig();
        wxMsgConfig.setTenantId(record.getTenantId());
        List<WxMsgConfig> wxMsgConfigs = wxMsgConfigMapper.findList(wxMsgConfig);
        if(CollectionUtils.isEmpty(wxMsgConfigs)){
            throw new MallinkException(ErrorCode.MSG_CONFIG_NOT_FOUND);
        }
        wxMsgConfig = wxMsgConfigs.get(0);
        if (wxMsgConfig.getRemains() <= 0L) {
            throw new MallinkException(ErrorCode.MSG_CONFIG_ACCOUNT);
        }

        WxMsgValidationcodeModel wxMsgValidationcodeModel = new WxMsgValidationcodeModel();
        wxMsgValidationcodeModel.setTenantId(record.getTenantId());
        wxMsgValidationcodeModel.setType(record.getModelType());
        wxMsgValidationcodeModel.setOpen(EnumMsgOpen.OPEN.getCode());
        List<WxMsgValidationcodeModel> modelList = wxMsgValidationcodeModelMapper.findList(wxMsgValidationcodeModel);
        if(CollectionUtils.isEmpty(modelList)){
            throw new MallinkException(ErrorCode.MSG_MODEL_NOT_FOUND);
        }

        wxMsgValidationcodeModel = wxMsgValidationcodeModelMapper.findList(wxMsgValidationcodeModel).get(0);

        String secret = wxMsgConfig.getSecret();
        String bid = wxMsgConfig.getBid();
        String publickey = wxMsgConfig.getPublickey();
        String phone = record.getReceiver();
        String signature = wxMsgValidationcodeModel.getSignature();
        wxMsgValidationcode.setSignature(signature);
        //替换内容
        String msg = wxMsgValidationcodeModel.getContent();
        for (Map.Entry<String, String> entry : record.getDynamicContentMap().entrySet()) {
            msg = msg.replace("{"+entry.getKey()+"}", entry.getValue());
        }
        wxMsgValidationcode.setMsg(msg);
        if(record.getDynamicContentMap() !=null) {
            wxMsgValidationcode.setCode(record.getDynamicContentMap().get("s6"));
        }

        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);
            wxMsgValidationcode.setCreatetime(createtime);
            Integer minutes = wxMsgValidationcodeModel.getMinutes();
            if(minutes >0) {
                currentTime += minutes * 60 * 1000;
                Date expiredate = new Date(currentTime);
                wxMsgValidationcode.setExpiretime(expiredate);
            }
            wxMsgValidationcodeMapper.insert(wxMsgValidationcode);
            String id = record.getDynamicContentMap().get("id");
            wxMsgValidationcodeService.addMsgCallback(wxMsgValidationcode, batchNo, id);
            //扣减剩余条数
            wxMsgConfig.setRemains(1L);
            wxMsgConfigMapper.updateRemains(wxMsgConfig);
        }else{
            throw new MallinkException(1001,"运营商返回失败:"+result);
        }
    }


}
