package com.tofly.xrtygis.custom.service.messge.impl;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.util.StringUtil;
import com.tofly.xrtygis.commons.Constant;
import com.tofly.xrtygis.custom.entity.gs.NoteSearch;
import com.tofly.xrtygis.custom.entity.message.SendMessage;
import com.tofly.xrtygis.custom.mapper.SendMessageMapper;
import com.tofly.xrtygis.custom.service.messge.SendMessageService;
import com.tofly.xrtygis.custom.util.DateTimeUtil;
import com.tofly.xrtygis.entity.Rxsmsmessage;
import com.tofly.xrtygis.entity.Rxsmstxlx;
import com.tofly.xrtygis.entity.vo.UserWaterMeterInfoVo;
import com.tofly.xrtygis.exception.BusinessException;
import com.tofly.xrtygis.service.RxsmstxlxService;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 发送短信
 *
 * @author zev
 */
@Service("sendMessageService")
public class SenMessageServiceImpl implements SendMessageService {
    private static final String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$";
    private static final Pattern PATTERN_REGEX_MOBILE_SIMPLE = Pattern.compile(REGEX_MOBILE_SIMPLE);
    @Autowired
    private SendMessageMapper sendMessageMapper;
    @Autowired
    private RxsmstxlxService rxsmstxlxService;

    @Override
    public Boolean sendMessage(SendMessage msg) {
        // 校验传入短信对象参数
        String lxdh = msg.getLxdh();
        String txlx = msg.getTxlx();
        String txnr = msg.getTxnr();
        if (StringUtils.isEmpty(lxdh)) {
            throw new BusinessException(Constant.SEND_MESSAGE_PHONE_NULL_CODE, Constant.SEND_MESSAGE_PHONE_NULL);
        }
        boolean mobilePhone = isMobilePhone(lxdh);
        if (!mobilePhone) {
            throw new BusinessException(Constant.SEND_MESSAGE_PHONE_CHECK_CODE, Constant.SEND_MESSAGE_PHONE_CHECK);
        }
        if (StringUtils.isEmpty(txlx)) {
            throw new BusinessException(Constant.SEND_MESSAGE_TXLX_CHECK_CODE, Constant.SEND_MESSAGE_TXLX_CHECK);
        }
        if (StringUtils.isEmpty(txnr)) {
            throw new BusinessException(Constant.SEND_MESSAGE_TXNR_CHECK_CODE, Constant.SEND_MESSAGE_TXNR_CHECK);
        }

        // 校验内容特殊字符
        Integer num = sendMessageMapper.checkSpecialCharacters(txnr);
        if (0 < num) {
            throw new BusinessException(Constant.SEND_MESSAGE_TXNR_ERROR_CHECK_CODE,Constant.SEND_MESSAGE_TXNR_ERROR_CHECK);
        }
        msg.setScsj(new Date());
        msg.setSLock("0");
        msg.setFszt("0");
        msg.setYhbh("");
        msg.setYhxm("");
        msg.setYhdz("");
        String uuid = IdUtil.randomUUID();
        String id = IdUtil.simpleUUID();
        msg.setLsh(uuid);
        msg.setId(id);
        Integer integer = sendMessageMapper.saveMessage(msg);
        return true;
    }

    @Override
    public Map<String, Long> getNoteNum() {
        return sendMessageMapper.getNoteNum();
    }

    @Override
    public Page<SendMessage> getMessagePage(Page page, NoteSearch noteSearch){
        String state = noteSearch.getState();
        String inputContent = noteSearch.getInputContent();
        Date start = noteSearch.getStartTime();
        Date end = noteSearch.getEndTime();
        return sendMessageMapper.getMessagePage(page, state, inputContent, start, end);
    }
    @Override
    public Boolean sendTemplateMessage(String yhbhs,Long tempId){
        // 获取对应模板数据
        Rxsmstxlx temp = rxsmstxlxService.getById(tempId);
        if(null==temp){
            throw new BusinessException(Constant.SEND_MESSAGE_TXNR_ERROR_TEMP_CODE,Constant.SEND_MESSAGE_TXNR_ERROR_TEMP);
        }

        List<UserWaterMeterInfoVo> yxUserList = sendMessageMapper.getYxUserList(yhbhs);
        //存放需要替换的变量以及值
        String dateTime = DateTimeUtil.getLocalDateTime(LocalDateTime.now(), DateTimeUtil.FULL_FORMAT);
        Map<String, String> replaceMap = new HashMap<>(12);
        //存电话号码以及模板转换后的文本短信信息
        List<SendMessage> sendMessageList = new ArrayList<>();
        if (StringUtil.isNotNull(yxUserList)) {
            yxUserList.forEach(k -> {
                SendMessage sendMessage = new SendMessage();
                sendMessage.setLxdh(k.getContactNumber());
                sendMessage.setYhbh(k.getUserCode());
                sendMessage.setYhxm(k.getUserName());
                sendMessage.setYhdz(k.getUserAddress());
                //需要的替换的变量，如把 ${YHXM} 替换
                replaceMap.put("YHXM", k.getUserName());
                replaceMap.put("YHDZ", k.getUserAddress());
                replaceMap.put("LXDH", k.getContactNumber());
                replaceMap.put("YHBH", k.getUserCode());
                replaceMap.put("TIME", dateTime);
                //这个是commons-text依赖中的
                StringSubstitutor sub = new StringSubstitutor(replaceMap);
                //替换模板文字中的变变量
                String sendContent = sub.replace(temp.getDxnrgs());
                sendMessage.setTxlx("4");
                sendMessage.setTxnr(sendContent);
                sendMessageList.add(sendMessage);
            });
            sendMessageList.forEach(info->{
                this.sendMessage(info);
            });

        }
        return true;
    }

    public static boolean isMobilePhone(String str) {
        return isMatch(PATTERN_REGEX_MOBILE_SIMPLE, str);
    }

    public static boolean isMatch(Pattern pattern, String str) {
        return !StringUtils.isEmpty(str) && pattern.matcher(str).matches();
    }




}
