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.*;
import com.iformall.mapper.*;
import com.iformall.mq.MqBaseProducer;
import com.iformall.service.WxCUserTagsService;
import com.iformall.service.WxMsgService;
import com.iformall.utils.DateUtils;
import com.iformall.utils.WiwideUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @author gongbiao
 */
@Service
public class WxMsgServiceImpl implements WxMsgService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxMsgMapper wxMsgMapper;

    @Autowired
    WxMsgConfigMapper wxMsgConfigMapper;

    @Autowired
    WxCUserTagsService wxCUserTagsService;

    @Autowired
    WxCUserBasicInfoMapper wxCUserBasicInfoMapper;

    @Autowired
    WxMsgCallbackMapper wxMsgCallbackMapper;

    @Autowired
    WxMsgModelMapper wxMsgModelMapper;

    @Autowired
    MqBaseProducer mqBaseProducer;

    @Override
    public PageInfo<WxMsg> listAsPage(WxMsg record, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        List<WxMsg> templist = wxMsgMapper.findList(record);
        for (WxMsg temp : templist) {

            Map<String, String> params = new HashMap<>();
            params.put("msgId", temp.getId().toString());
            params.put("status", "1");
            int success = wxMsgCallbackMapper.queryMsgSendTotal(params);
            params.put("status", "0");
            int error = wxMsgCallbackMapper.queryMsgSendTotal(params);
            temp.setSuccessNumber(success);
            temp.setErrorNumber(error);
        }

        PageInfo<WxMsg> pageInfo = new PageInfo<>(templist);
        return pageInfo;
    }

    @Override
    public WxMsg getById(Long id) {

        WxMsg wxMsg = wxMsgMapper.selectByPrimaryKey(id);
        Map<String, String> params = new HashMap<>();
        params.put("msgId", wxMsg.getId().toString());
        params.put("status", "1");
        int success = wxMsgCallbackMapper.queryMsgSendTotal(params);
        params.put("status", "0");
        int error = wxMsgCallbackMapper.queryMsgSendTotal(params);
        wxMsg.setSuccessNumber(success);
        wxMsg.setErrorNumber(error);

        return wxMsg;
    }

    @Async
    @Override
    public ResultData saveOrUpdate(WxMsg wxMsg, WxMsgConfig wxMsgConfig) {

        //新增记录
        if (wxMsg.getId() == null) {
            //草稿
            if (wxMsg.getStatus().equals(EnumMsgStatus.MSG_STATUS_DRAFT.getCode())) {
                final IdWorker idWorker = IdWorker.get();
                wxMsg.setId(idWorker.nextId());
                wxMsg.setCreatetime(new Date());
                wxMsgMapper.insertSelective(wxMsg);
                return new ResultData(Result.SUCCESS, "已保存到草稿箱");

            }

            //是否立即发送
            if (wxMsg.getIsright().equals(EnumMsgSend.MSG_SEND_IMMEDIATELY.getCode())) {
                wxMsg.setStatus(EnumMsgStatus.MSG_STATUS_SENDED.getCode());
                if (wxMsg.getExpectSendNumber().intValue() > 1000) {
                    batchSendMsg(wxMsg, wxMsgConfig, null);
                } else {
                    //sendmsg(wxMsg, wxMsgConfig, null);
                    wxMsg.setWxMsgConfig(wxMsgConfig);
                    wxMsg.setCouponInject(null);
                    wxMsg.setMsgType(EnumMsgRecordType.SMS_CALLBACK.getCode());
                    mqBaseProducer.sendMessage(wxMsg, EnumMsgMqTopic.DEFAULT.getCode(),EnumMsgMqTag.DEFAULT.getCode(),null);
                }
                return new ResultData(Result.SUCCESS, "短信已发送");
            } else {
                wxMsg.setStatus(EnumMsgStatus.MSG_STATUS_NOT_SEND.getCode());
                final IdWorker idWorker = IdWorker.get();
                long id = idWorker.nextId();
                wxMsg.setId(id);
                wxMsg.setCreatetime(new Date());
                wxMsgMapper.insertSelective(wxMsg);
                return new ResultData(Result.SUCCESS, "短信会在预设时间发送", id);
            }

        } else {
            //草稿
            if (wxMsg.getStatus().equals(EnumMsgStatus.MSG_STATUS_DRAFT.getCode())) {
                wxMsgMapper.updateByPrimaryKeySelective(wxMsg);
                return new ResultData(Result.SUCCESS, "已保存到草稿箱");
            }

            //是否立即发送
            if (wxMsg.getIsright().equals(EnumMsgSend.MSG_SEND_IMMEDIATELY.getCode())) {
                wxMsg.setStatus(EnumMsgStatus.MSG_STATUS_SENDED.getCode());
                if (wxMsg.getExpectSendNumber().intValue() > 1000) {
                    batchSendMsg(wxMsg, wxMsgConfig, null);
                } else {
                    //sendmsg(wxMsg, wxMsgConfig, null);
                    wxMsg.setWxMsgConfig(wxMsgConfig);
                    wxMsg.setMsgType(EnumMsgRecordType.SMS_CALLBACK.getCode());
                    mqBaseProducer.sendMessage(wxMsg, EnumMsgMqTopic.DEFAULT.getCode(),EnumMsgMqTag.DEFAULT.getCode(),EnumMsgMqKey.DEFAULT.getCode());
                }
                return new ResultData(Result.SUCCESS, "短信已发送");
            } else {
                //定时
                wxMsg.setStatus(EnumMsgStatus.MSG_STATUS_NOT_SEND.getCode());
                wxMsgMapper.updateByPrimaryKeySelective(wxMsg);
                return new ResultData(Result.SUCCESS, "短信会在预设时间发送");
            }

        }
    }

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

    @Async
    @Override
    public void sendMsgFromCouponInject(WxMsg wxmsg, WxMsgConfig wxMsgConfig, WxCouponInject couponInject) {
        batchSendMsg(wxmsg, wxMsgConfig, couponInject);
    }


    public void batchSendMsg(WxMsg wxMsg, WxMsgConfig wxMsgConfig, WxCouponInject couponInject) {

        String[] split = wxMsg.getPhones().split(",");
        int length = split.length;
        int extra = length % 1000;
        int extracount = extra > 0 ? (length / 1000 + 1) : (length / 1000);
        int index = extracount - 1;
        for (int i = 0; i < extracount; i++) {
            if (extra > 0 && i == index) {
                List<String> phoneList = Arrays.asList(split).subList(i * 1000, length);
                String phones = StringUtils.join(phoneList, ",");
                wxMsg.setPhones(phones);
                wxMsg.setExpectSendNumber(extra);
                //sendmsg(wxMsg, wxMsgConfig, couponInject);
                wxMsg.setWxMsgConfig(wxMsgConfig);
                wxMsg.setCouponInject(couponInject);
                wxMsg.setMsgType(EnumMsgRecordType.SMS_CALLBACK.getCode());
                mqBaseProducer.sendMessage(wxMsg, EnumMsgMqTopic.DEFAULT.getCode(),EnumMsgMqTag.DEFAULT.getCode(),EnumMsgMqKey.DEFAULT.getCode());
            } else {
                List<String> phoneList = Arrays.asList(split).subList(i * 1000, (i + 1) * 1000);
                String phones = StringUtils.join(phoneList, ",");
                wxMsg.setExpectSendNumber(1000);
                wxMsg.setPhones(phones);
                //sendmsg(wxMsg, wxMsgConfig, couponInject);
                wxMsg.setWxMsgConfig(wxMsgConfig);
                wxMsg.setCouponInject(couponInject);
                wxMsg.setMsgType(EnumMsgRecordType.SMS_CALLBACK.getCode());
                mqBaseProducer.sendMessage(wxMsg, EnumMsgMqTopic.DEFAULT.getCode(),EnumMsgMqTag.DEFAULT.getCode(),EnumMsgMqKey.DEFAULT.getCode());
            }
        }
    }

//    @Deprecated
//    public ResultData sendmsg(WxMsg record, WxMsgConfig wxMsgConfig, WxCouponInject couponInject) {
//        logger.info("发送短信开始...");
//        logger.info("couponInject:" + couponInject);
//        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.selectByPrimaryKey(record.getModelId());
//        Integer modelId = null;
//        if (wxMsgModel != null) {
//            modelId = wxMsgModel.getModelId();
//        }
//        logger.info("=============迈外迪API开始调用");
//        String result = WiwideUtil.sendMsg(secret, bid, publickey, phone, signature, msg, notifyUrl, EnumVerifyCode.NO.getCode().toString(), modelId);
//        logger.info("=============迈外迪API返回结果：" + result);
//        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());
//        } else {
//            record.setSendstatus(EnumMsgSendStatus.MSG_SEND_FAIL.getCode());
//        }
//
//        final IdWorker idWorker = IdWorker.get();
//        long id = idWorker.nextId();
//        WxMsg wxMsg = new WxMsg();
//        wxMsg.setTenantId(record.getTenantId());
//        wxMsg.setModelId(record.getModelId());
//        wxMsg.setMsg(record.getMsg());
//        wxMsg.setExpectSendNumber(record.getExpectSendNumber());
//        wxMsg.setPhones(record.getPhones());
//        wxMsg.setSignature(record.getSignature());
//        wxMsg.setIsright(record.getIsright());
//        wxMsg.setName(record.getName());
//        wxMsg.setSendstatus(record.getSendstatus());
//        wxMsg.setLabel(record.getLabel());
//        wxMsg.setStatus(record.getStatus());
//        wxMsg.setWay(record.getWay());
//        wxMsg.setId(id);
//        String systemTime = DateUtils.getSystemTime("yyyy-MM-dd HH:mm:ss");
//        wxMsg.setSendtime(systemTime);
//        wxMsg.setCreatetime(DateUtils.stringToDate(systemTime, "yyyy-MM-dd HH:mm:ss"));
//        //精准投放
//        if (couponInject != null) {
//            wxMsg.setCouponInjectId(couponInject.getId());
//        }
//        wxMsgMapper.insertSelective(wxMsg);
//
//        logger.info("发送短信结束...");
//        if (ret.equals(EnumMsgSendStatus.MSG_SEND_SUCCESS.getCode().toString())) {
//            addMsgCallback(wxMsg, batchNo);
//            return new ResultData(Result.SUCCESS, "短信发送中，您可在短信明细中查看发送状态", id);
//        } else {
//            return new ResultData(ErrorCode.MSG_SEND_INTERFACE_ERROR.getCode(),
//                    ErrorCode.MSG_SEND_INTERFACE_ERROR.getMessage() + ":" + resultMsg);
//        }
//
//    }

    @Override
    public void addMsgCallback(WxMsg wxmsg, String batchNo) {
        logger.info("营销短信发送时主动添加回调记录开始...");
        String phones = wxmsg.getPhones();
        String[] split = phones.split(",");
        final IdWorker idWorker = IdWorker.get();
        for (String phone : split) {
            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_SENDING.getCode());
            wxMsgCallback.setStatusMsg(EnumMsgSendStatus.MSG_SENDING.getMessage());
            wxMsgCallback.setCreatetime(new Date());
            wxMsgCallbackMapper.insertSelective(wxMsgCallback);
        }
        logger.info("营销短信发送时主动添加回调记录结束...");

    }


}
