package com.zd.chemical.util;

import cn.hutool.json.JSONUtil;
import com.esms.MOMsg;
import com.esms.MessageData;
import com.esms.PostMsg;
import com.esms.common.entity.Account;
import com.esms.common.entity.GsmsResponse;
import com.esms.common.entity.MTPack;
import com.zd.chemical.domain.SydSmsLog;
import com.zd.chemical.service.ISydSmsLogService;
import com.zd.common.core.domain.R;
import com.zd.common.core.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Component
public class SmsSydUtil {

    private MTPack mtPack;

    // 证号 djjx
    // 登录密码 6B1aQety
    // 发送密码 yfhzfGSJ
    private Account account = new Account("djjx", "yfhzfGSJ");

    @Value("${sms-syd.ip}")
    private String SMS_IP="192.168.32.153";;
    @Value("${sms-syd.down-port:8090}")
    public int DOWN_PORT;
    @Value("${sms-syd.up-port:8188}")
    public int UP_PORT;

    // 8090  下发端口   8188 拉取状态报告和上行
    private PostMsg DOWN_PM = new PostMsg(SMS_IP, DOWN_PORT);
    private PostMsg UP_PM = new PostMsg(SMS_IP, UP_PORT);

    private static Map<Integer, String> DOWN_MAP;

    @Autowired
    private ISydSmsLogService sydSmsLogService;

    SmsSydUtil(){
        DOWN_MAP = new HashMap<>();
        DOWN_MAP.put(0 , "成功");
        DOWN_MAP.put(-1 , "账号无效，或者账号停用、过期等。");
        DOWN_MAP.put(-2 , "参数无效");
        DOWN_MAP.put(-3 , "连接不上服务器");
        DOWN_MAP.put(-6 , "用户名密码错误");
        DOWN_MAP.put(-11 , "单次提交号码数量超过系统限制");
        DOWN_MAP.put(-12 , "超过发送量限制");
        DOWN_MAP.put(-13 , "账号没有发送权限");
        DOWN_MAP.put(-99 , "系统内部错误");
        DOWN_MAP.put(-100 , "其它错误");

    }

    private MTPack buildDefaultSMSPack() {
        if(this.mtPack == null){
            this.mtPack = new MTPack();
            mtPack.setSendType(MTPack.SendType.MASS);
            mtPack.setMsgType(MTPack.MsgType.SMS);
            mtPack.setBizType(1);
        }
        return this.mtPack;
    }

    /**
     * 四医大平台发送短信
     * @param content 发送内容
     * @param purpose 短信用途 1 化学品告警，2 登录，3 开锁，4 气瓶告警，5 预案告警
     * @param phones  手机号
     * @return 发送结果
     */
    public R sendSydSms(@NotNull String content, @NotNull Integer purpose, Long lockApplyId, @NotNull String... phones) throws Exception {
        UUID uuid = UUID.randomUUID();
        R r = singleTicketMsgId(content, uuid, phones);

        for (String phone : phones) {
            SydSmsLog sydSmsLog = new SydSmsLog();
            sydSmsLog.setContent(content);
            sydSmsLog.setPhone(phone);
            sydSmsLog.setPurpose(purpose);
            sydSmsLog.setStatus(Integer.parseInt(r.getData() + ""));
            sydSmsLog.setCreateTime(DateUtils.getNowDate());
            sydSmsLog.setUuid(uuid.toString());
            sydSmsLog.setLockApplyId(lockApplyId);
            sydSmsLog.setReply(0);

            sydSmsLogService.insertSydSmsLog(sydSmsLog);
        }

        return r;
    }

    public void queryUplinkResult(){
        try {
            doGetMos();
        } catch (Exception e) {
            log.error("定时获取上行数据发生异常！");
        }
    }


    /**
     * 短信下发范例 每个话单，一个扩展码
     */
    private synchronized R singleTicketMsgId(@NotNull String content, UUID uuid, @NotNull String... phones) throws Exception {

        MTPack pack = buildDefaultSMSPack();

        // 批次号
        pack.setBatchID(uuid);

        log.info("四医大短信下发参数：UUID，" + pack.getBatchID() + "手机号：" + JSONUtil.toJsonStr(phones) + "，内容：" + content);

        List<MessageData> msgs = new ArrayList<>();
        for (String phone : phones) {
            msgs.add(MessageData.getInstance(phone, content));
        }
        pack.setMsgs(msgs);

        GsmsResponse resp = DOWN_PM.post(account, pack);
        log.info("四医大短信下发返回结果：" + resp.toString());
        if(resp.getResult() == 0){

            return R.ok(resp.getResult()+"", DOWN_MAP.get(resp.getResult()));
        }else {
            return R.fail(resp.getResult()+"", DOWN_MAP.get(resp.getResult()));
        }
    }


    /**
     * 获取上行信息
     *
     */
    private void doGetMos() throws Exception {
        SydSmsLog sydSmsLog = new SydSmsLog();

        sydSmsLog.setStatus(0);
        sydSmsLog.setReply(0);
        List<SydSmsLog> list = sydSmsLogService.selectSydSmsLogList(sydSmsLog);

        // TODO 测试原因，咱注释掉
        /*if(list.size() == 0){
            return;
        }*/

        MOMsg[] mos = UP_PM.getMOMsgs(account, 10);

        if (mos != null) {

            List<MOMsg> mosList = Stream.of(mos).collect(Collectors.toList());
            log.info("四医大短信上行查询结果：" + JSONUtil.toJsonStr(mosList));

            Date now = DateUtils.getNowDate();
            for (SydSmsLog smsLog : list) {
                for (int i = 0; i < mosList.size(); i++) {
                    if(smsLog.getPhone().equals(mosList.get(i).getPhone())){

                        smsLog.setReply(1);
                        smsLog.setUpdateTime(now);
                        smsLog.setReplyContent(mosList.get(i).getContent());
                        sydSmsLogService.updateSydSmsLog(smsLog);
                        mosList.remove(i);
                        break;
                    }
                }
            }

            if(mosList.size() > 0){
                log.info("四医大短信上行查询遗漏数据：" + JSONUtil.toJsonStr(mosList));
            }

        }
    }

}
