package com.ho.flow.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.util.AliSendSmsUtils;
import com.ho.common.tools.util.PageResult;
import com.ho.common.tools.util.PageUtils;
import com.ho.flow.entity.SendSmsConfig;
import com.ho.flow.mapper.SendSmsConfigMapper;
import com.ho.flow.service.SendSmsConfigService;
import com.ho.flow.vo.req.SendSmsConfig.SendSmsConfigQueryReq;
import com.ho.flow.vo.resp.SendSmsConfig.SendSmsConfigRsp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SendSmsConfigImpl implements SendSmsConfigService {

    @Autowired
    SendSmsConfigMapper sendSmsConfigMapper;

    @Override
    public PageResult<SendSmsConfigRsp> getPageList(SendSmsConfigQueryReq vo) {
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<SendSmsConfigRsp> sendSmsConfigs = sendSmsConfigMapper.selectList(vo);
        sendSmsConfigs.stream().forEach(i -> i.setLevelList((i.getAlarmLevel() == null || i.getAlarmLevel().isEmpty()) ? new ArrayList<>() : Arrays.asList(i.getAlarmLevel().split(","))));
        return PageUtils.getPageResult(new PageInfo<>(sendSmsConfigs));
    }

    @Override
    public List<SendSmsConfigRsp> getList(SendSmsConfigQueryReq vo) {
        List<SendSmsConfigRsp> sendSmsConfigs = sendSmsConfigMapper.selectList(vo);
        return sendSmsConfigs;
    }

    @Override
    public void insertList(List<SendSmsConfig> list) {
        for (SendSmsConfig sendSmsConfig : list) {
            //1）是否立即发送（默认是）（isSendNow）、延迟发送时间（下拉选择）(delayTime 延迟时间)  "是否立即发送:是1否2  默认是1"
            if (sendSmsConfig.getIsSendNow() == null) {
                sendSmsConfig.setIsSendNow(CommonConstant.ONE);
            }
            //2）当是否立即发送选择为否时，延迟发送时间必须选择，否则延迟发送时间默认存0）
            if (CommonConstant.TWO.equals(sendSmsConfig.getIsSendNow())) {
                if (sendSmsConfig.getDelayData() == null) {
                    sendSmsConfig.setDelayData(CommonConstant.ZERO);
                }
            }
        }
        sendSmsConfigMapper.insertList(list);
    }

    @Override
    public int updateById(SendSmsConfig vo) {
        //判断是否为延迟发送
        if (CommonConstant.TWO.equals(vo.getIsSendNow())) {
            //是的情况下，查看延长时间是否为空，为空的情况下默认存0
            if (vo.getDelayData() == null) {
                vo.setDelayData(CommonConstant.ZERO);
            }
        }
        return sendSmsConfigMapper.updateById(vo);
    }

    @Override
    public int updateByUserId(SendSmsConfig vo) {
        int count = sendSmsConfigMapper.updateByUserId(vo);
        return count;
    }

    @Override
    public int deleteList(List<Integer> ids) {
        return sendSmsConfigMapper.deleteBatch(ids);
    }

    @Override
    public void sendSms(SendSmsConfigQueryReq vo) {
     /*   JSONObject jsonObject = new JSONObject();
        jsonObject.put(CommonConstant.SMS.SITE_NAME, "浙江慈溪");
        jsonObject.put(CommonConstant.SMS.CONTENT, "111111");
        vo.setParam(jsonObject);*/
        List<SendSmsConfigRsp> list = sendSmsConfigMapper.selectList(vo);
        if (null == list || list.isEmpty()) {
            return;
        }
        Map<Integer, List<SendSmsConfigRsp>> collect = list.stream().collect(Collectors.groupingBy(SendSmsConfigRsp::getIsSendNow));
        //筛选延迟发送的筛选条件 是否立即发送:是1否2  默认是1
        List<SendSmsConfigRsp> sendSmsConfigs = collect.get(CommonConstant.ONE);//立即发送
        List<SendSmsConfigRsp> delaySMSList = collect.get(CommonConstant.TWO);//延迟发送
        if (null != delaySMSList) {
            log.info("delay send message,{}",vo.getParam().toJSONString());
            getDelaySMS(delaySMSList, vo.getParam());
        }
        if (sendSmsConfigs == null) {
            return;
        }
        if (sendSmsConfigs != null || !sendSmsConfigs.isEmpty()) {
            log.info("common send message,{}",vo.getParam().toJSONString());
            for (SendSmsConfigRsp s : sendSmsConfigs) {
                try {
                    JSONObject param = vo.getParam();
                    param.put(CommonConstant.SMS.NAME, s.getRealName());
                    AliSendSmsUtils.sendMessage(vo.getParam().toJSONString(), s.getPhone());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("sendSms :{}", e.getMessage());
                }
            }
        }
    }

    public void getDelaySMS(List<SendSmsConfigRsp> list, JSONObject params) {
        list.sort(((o1, o2) -> {
            //从小到大
            return o1.getDelayData() - o2.getDelayData();//此处定义比较规则，o2.age-o1.age即为从大到小
        }));
        for (SendSmsConfigRsp sendSmsConfigRsp : list) {
            long milliseconds = TimeUnit.MINUTES.toMillis(sendSmsConfigRsp.getDelayData());
            Timer t = new Timer();
            t.schedule(new TimerTask() {
                @Override
                public void run() {
                    try {
                        JSONObject param = params;
                        param.put(CommonConstant.SMS.NAME, sendSmsConfigRsp.getRealName());
                        AliSendSmsUtils.sendMessage(params.toJSONString(), sendSmsConfigRsp.getPhone());
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("sendSms :{}", e.getMessage());
                    }

                }
            }, milliseconds);
        }
    }
}
