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.WxMsg;
import com.iformall.enums.EnumMsgSendStatus;
import com.iformall.enums.EnumMsgStatus;
import com.iformall.enums.EnumVerifyCode;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.*;
import com.iformall.service.WxMsgLimitService;
import com.iformall.service.msg.MsgSendService;
import com.iformall.service.WxMsgService;
import com.iformall.service.WxMsgValidationcodeService;
import com.iformall.utils.DateUtils;
import com.iformall.utils.WiwideUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * @author luozukai
 * 业务短信发送实现
 */
@Service
public class SendCallBackSmsServiceImpl 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;
    @Autowired
    private WxMsgModelMapper wxMsgModelMapper;
    @Autowired
    private WxMsgMapper wxMsgMapper;
    @Autowired
    private WxMsgService wxMsgService;

    @Autowired
    private WxMsgLimitService wxMsgLimitService;


    @Override
    public void send(BaseMsg baseMsg) throws Exception{
        WxMsg record = (WxMsg)baseMsg;

        WxMsgConfig wxMsgConfig = record.getWxMsgConfig();
        if(wxMsgConfig == null){
            wxMsgConfig = new WxMsgConfig();
            wxMsgConfig.setTenantId(record.getTenantId());
            List<WxMsgConfig> wxMsgConfigs = wxMsgConfigMapper.findList(wxMsgConfig);
            if (wxMsgConfigs.size() == 0) {
                throw new MallinkException(ErrorCode.MSG_CONFIG_NOT_FOUND);
            }
            wxMsgConfig = wxMsgConfigs.get(0);
            if (wxMsgConfig.getRemains() == 0) {
                throw new MallinkException(ErrorCode.MSG_SUM_ZERO);
            }
            if (wxMsgConfig.getRemains() < record.getExpectSendNumber()) {
                throw new MallinkException(ErrorCode.MSG_SUM_INSUFFICENT);
            }
            if(wxMsgConfig.getRemains() <=0l){
                throw new MallinkException(ErrorCode.MSG_CONFIG_ACCOUNT);
            }
        }
        WxCouponInject couponInject = record.getCouponInject();

        String secret = wxMsgConfig.getSecret();
        String bid = wxMsgConfig.getBid();
        String publickey = wxMsgConfig.getPublickey();

        String phone = record.getPhones();
        String signature = record.getSignature();
        String msg = record.getMsg();
        String notifyUrl = wxMsgConfig.getNotifyurl();
        WxMsgModel wxMsgModel = wxMsgModelMapper.selectById(record.getModelId());
        Integer modelId = null;
        if (wxMsgModel != null) {
            modelId = wxMsgModel.getModelId();
        }
        /*
        // 检查是否超限
        WxMsgLimit msgLimit = new WxMsgLimit();
        msgLimit.setTenantId(record.getTenantId());
        msgLimit.setType(EnumMsgLimitType.SMS_SALE.getCode());
        msgLimit.setLimitId(phone);
        if(wxMsgLimitService.checkIsLimit(msgLimit)) {
            logger.error("用户短信超限：" + phone);
            return;
        }
        */

        String result = WiwideUtil.sendMsg(secret, bid, publickey, phone, signature, msg, notifyUrl, EnumVerifyCode.NO.getCode().toString(), modelId);
        JSONObject jsonObjectResult = JSONObject.parseObject(result);
        String ret = jsonObjectResult.get("ret").toString();
        String batchNo = jsonObjectResult.get("data").toString();
        //String resultMsg = jsonObjectResult.get("msg").toString();
        record.setReturnResult(jsonObjectResult.toJSONString());

        if (ret.equals(EnumMsgSendStatus.MSG_SEND_SUCCESS.getCode().toString())) {
            record.setSendstatus(EnumMsgSendStatus.MSG_SEND_SUCCESS.getCode());
            //扣减剩余条数
            wxMsgConfig.setRemains(1l);
            wxMsgConfigMapper.updateRemains(wxMsgConfig);
        } else {
            record.setSendstatus(EnumMsgSendStatus.MSG_SEND_FAIL.getCode());
        }

        if(record.getId() == null){
            final IdWorker idWorker = IdWorker.get();
            long id = idWorker.nextId();
            record.setId(id);
            String systemTime = DateUtils.getSystemTime("yyyy-MM-dd HH:mm:ss");
            record.setSendtime(systemTime);
            record.setCreatetime(DateUtils.stringToDate(systemTime, "yyyy-MM-dd HH:mm:ss"));
            //精准投放
            if (couponInject != null) {
                record.setCouponInjectId(couponInject.getId());
            }
            wxMsgMapper.insert(record);
        }

        if (ret.equals(EnumMsgSendStatus.MSG_SEND_SUCCESS.getCode().toString())) {
            wxMsgService.addMsgCallback(record, batchNo);
            //wx_msg改为已发送
            record.setStatus(EnumMsgStatus.MSG_STATUS_SENDED.getCode());
            wxMsgMapper.updateById(record);
        } else {
            logger.error("发送:{},运营商返回失败:{}",phone,result);
            wxMsgMapper.updateById(record);
            throw new MallinkException(1001,"运营商返回失败:"+result);
        }
    }


}
