/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.feesapi.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.feesapi.bmgl.entity.BmCbpq;
import com.tofly.feesapi.bmgl.service.BmCbpqService;
import com.tofly.feesapi.common.core.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.common.core.dto.Order;
import com.tofly.feesapi.common.enums.SmsMessageFsztTypeEnum;
import com.tofly.feesapi.common.util.GuidGenerator;

import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.sms.entity.SmsMessage;
import com.tofly.feesapi.sms.entity.SmsTxlx;
import com.tofly.feesapi.sms.entity.dto.SmsMessageDto;
import com.tofly.feesapi.sms.entity.dto.SendTxlxMessageDto;
import com.tofly.feesapi.sms.entity.dto.SmsMessageYhxxDto;
import com.tofly.feesapi.sms.entity.vo.SmsMessageVo;
import com.tofly.feesapi.sms.entity.vo.SmsMessageYhxxVo;
import com.tofly.feesapi.sms.service.ISmsMessageService;
import com.tofly.feesapi.sms.service.ISmsTxlxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tofly.feesapi.sms.mapper.SmsMessageMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * 短信消息
 *
 * @author sunjian
 * @date Fri Nov 08 00:00:00 CST 2024
 */
@Service("smsMessageService")
public class SmsMessageServiceImpl extends ServiceImpl<SmsMessageMapper, SmsMessage> implements ISmsMessageService {

    @Autowired
    private ISmsTxlxService iSmsTxlxService;
    @Autowired
    private BmCbpqService cbpqService;
    @Autowired
    private ISmsTxlxService smsTxlxService;

    //验证电话号码正则表达式
    private static final String PHONE_NUMBER_REGEX =
            "^(?:(?:\\+|00)86|86)?1(?:[3-9]\\d{9})$";
    private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile(PHONE_NUMBER_REGEX);

    /**
     * 自定义分页查询
     *
     * @param page
     * @param smsmessageDto
     * @return
     */
    @Override
    public Page<SmsMessageVo> getSmsMessagePage(Page page, SmsMessageDto smsmessageDto) {
        List<OrderItem> orderItems = page.orders();
        if (!orderItems.isEmpty()) {
            orderItems = orderItems.stream().map(item -> {
                if (item.getColumn().equals("yhbh")) {
                    OrderItem order = new OrderItem();
                    order.setColumn("a.yhbh");
                    order.setAsc(item.isAsc());
                    return order;
                }
                return item;
            }).collect(Collectors.toList());
            page.setOrders(orderItems);
        }
        else {
            orderItems.add(new OrderItem("scsj", false));
            orderItems.add(new OrderItem("a.yhbh", true));
        }
        return this.baseMapper.getPage(page, smsmessageDto);
    }

    /**
     * 重新发送短信
     *
     * @param ids 短信ids字符串
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone<Object> reSendByIds(String ids) {
        ResultRespone<Object> rest = new ResultRespone<>();
        if (!StringUtil.isEmpty(ids)) {
            List<String> idList = Arrays.asList(ids.split(","));
            for (String smsid : idList) {
                SmsMessage entity = new SmsMessage();
                entity.setId(smsid);
                entity.setFszt("0");
                entity.setSLock("0");
                entity.setBz("");
                if (!this.updateById(entity)) {
                    log.error("重新发送短信失败，参数:ids = " + ids);
                    rest.setMessage("发送短信失败!");
                    rest.setCode(-1);
                }
            }
        } else {
            log.error("重新发送短信失败异常:ids不能为空！");
            rest.setCode(-1);
            rest.setMessage("ids不能为空！");
        }
        return rest;
    }

    /**
     * 自定义发送短信
     *
     * @param phone   电话号码
     * @param content 短信内容
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone<Object> customizeSendMessage(String phone, String content) {
        ResultRespone<Object> rest = new ResultRespone<>();
        if (null != phone) {
            if (!PHONE_NUMBER_PATTERN.matcher(phone).matches()) {
                rest.setCode(-1);
                rest.setMessage("电话号码不符合规则！");
            }
            if (null != content) {
                if (content.length() < 1000) {
                    SmsMessage smsMessage = new SmsMessage();
                    smsMessage.setId(UUID.randomUUID().toString());
                    smsMessage.setLxdh(phone);
                    smsMessage.setFszt("0");
                    smsMessage.setSLock("0");
                    smsMessage.setTxlx("2");//临时短信模板
                    smsMessage.setScsj(new Date());
                    smsMessage.setTxnr(content);
                    smsMessage.setCzryxm(SecurityUtils.getUser().getRealName());
                    smsMessage.setCzrybm(SecurityUtils.getUserId().toString());
                    this.save(smsMessage);
                } else {
                    rest.setCode(-1);
                    rest.setMessage("短信内容太长！");
                }
            } else {
                rest.setCode(-1);
                rest.setMessage("短信内容不能为空！");
            }
        } else {
            rest.setCode(-1);
            rest.setMessage("电话号码不能为空！");
        }
        return rest;
    }

    /**
     * 获取短信信息用户列表
     *
     * @param page 分页参数
     * @param dto  传入参数
     * @return
     */
    public Page<SmsMessageYhxxVo> getSmsMessageYhxxVoList(Page page, SmsMessageYhxxDto dto) {
        return baseMapper.getSmsMessageYhxxVoList(page, dto);
    }

    /**
     * 获取短信信息用户列表（包含欠费）
     *
     * @param page 分页参数
     * @param dto  传入参数
     * @return
     */
    public Page<SmsMessageYhxxVo> getSmsMessageYhqfxxVoList(Page page, SmsMessageYhxxDto dto) {
        return baseMapper.getSmsMessageYhqfxxVoList(page, dto);
    }

    /**
     * 获取预付费短信信息用户列表（预付费金额小于10元）
     *
     * @param page 分页参数
     * @param dto  传入参数
     * @return
     */
    public Page<SmsMessageYhxxVo> getSmsMessageyffVoPage(Page page, SmsMessageYhxxDto dto) {
        if (StringUtil.isEmpty(dto.getUserId())) {
            dto.setUserId(SecurityUtils.getUserId().toString());
        }
        return baseMapper.getSmsMessageyffVo(page, dto);
    }


    /**
     * 批量发送自定义短信
     *
     * @param dto 条件参数(按照勾选发送，需要传入yhbhs)
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone<Object> batchSendMessageYhxx(SmsMessageYhxxDto dto) {
        ResultRespone<Object> rest = new ResultRespone<>();
        //自定义短信发送列表 不分页 只有用户信息没有欠费信息
        List<SmsMessageYhxxVo> smsMessageYhxxVoList = baseMapper.getSmsMessageYhxxVoList(dto);
        ArrayList<SmsMessage> smsMessagelist = new ArrayList<>();
        String lsh = GuidGenerator.getGuid();
        for (SmsMessageYhxxVo smsmessageyhxxvo : smsMessageYhxxVoList) {
            SmsMessage smsMessage = JSONObject.parseObject(JSON.toJSONString(smsmessageyhxxvo), SmsMessage.class);
            smsMessage.setId(GuidGenerator.getGuid());
            smsMessage.setLsh(lsh);
            smsMessage.setTxnr(dto.getDxnr());
            smsMessage.setScsj(new Date());
            smsMessage.setFszt("0");
            smsMessage.setSLock("0");
            smsMessagelist.add(smsMessage);
        }
        saveBatch(smsMessagelist);
        rest.setMessage("添加到待发送短信列表成功！");
        rest.setCode(1);
        return rest;
    }

    /**
     * 批量发送模板短信
     *
     * @param dto 条件参数条件参数(按照勾选发送，需要传入yhbhs)
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone<Object> batchSendMessageYhqfxx(SmsMessageYhxxDto dto) {
        if (StringUtil.isEmpty(dto.getUserId())) {
            dto.setUserId(SecurityUtils.getUserId().toString());
        }
        ResultRespone<Object> rest = new ResultRespone<>();
        //模板短信发送列表（一般为欠费催缴模板） 不分页 包含欠费信息用户信息
        List<SmsMessageYhxxVo> smsMessageYhqfxxVoList = null;
        if (dto.getTxlx().equals("9")) {
            smsMessageYhqfxxVoList = baseMapper.getSmsMessageYhqfxxVoList(dto);
        } else if (dto.getTxlx().equals("10")) {
            smsMessageYhqfxxVoList = baseMapper.getSmsMessageyffVo(dto);
        }

        List<BmCbpq> cbpqList = cbpqService.list();
        SmsTxlx smsTxlx = iSmsTxlxService.list().stream().filter(item -> item.getCode().equals(dto.getTxlx())).findFirst().orElse(null);
        ArrayList<SmsMessage> smsMessagelist = new ArrayList<>();
        String lsh = GuidGenerator.getGuid();
        String dwdh = "";
        String mbbh = "";
        for (SmsMessageYhxxVo smsmessageyhqfxxvo : smsMessageYhqfxxVoList) {
            SmsMessage smsMessage = JSONObject.parseObject(JSON.toJSONString(smsmessageyhqfxxvo), SmsMessage.class);

            BmCbpq cbpq = cbpqList.stream().filter(item -> item.getCbpqbm().equals(smsmessageyhqfxxvo.getSscbpq().toString()))
                    .findFirst().orElse(null);

            if (StringUtil.isNotNull(cbpq)) {
                dwdh = cbpq.getLxdh();
            }

            if (StringUtil.isNotNull(smsTxlx)) {
                mbbh = smsTxlx.getMbbh();
            }

            smsMessage.setTxlx(dto.getTxlx());
            smsMessage.setId(GuidGenerator.getGuid());
            smsMessage.setLsh(lsh);
            smsMessage.setScsj(new Date());
            smsMessage.setFszt("0");
            smsMessage.setSLock("0");
            smsMessage.setQf(smsmessageyhqfxxvo.getQfje());
            //  smsMessage.setTxnr(ConvertDxnr(dto.getDxnr(), smsMessage));
            smsMessage.setTxnr(dto.getDxnr());
            smsMessage.setParams(retParams(dto.getTxlx(), smsmessageyhqfxxvo, dwdh));
            smsMessage.setMbbh(mbbh);
            smsMessagelist.add(smsMessage);

        }
        saveBatch(smsMessagelist);
        rest.setMessage("添加到待发送短信列表成功！");
        rest.setCode(1);
        return rest;
    }

    private String retParams(String txlx, SmsMessageYhxxVo smsmessageyhqfxxvo, String dwdh) {
        String retValue = "";
        switch (txlx) {
            case "9"://欠费催缴
                retValue = smsmessageyhqfxxvo.getYhbh() + "," + smsmessageyhqfxxvo.getQfje() + "," + dwdh;
                break;
            case "10"://余额不足
                retValue = smsmessageyhqfxxvo.getYhbh() + "," + smsmessageyhqfxxvo.getNbsyje() + ",10," + dwdh;
                break;
        }
        return retValue;
    }


    /**
     * 转换短信内容
     *
     * @param dxnr
     * @param entity
     * @return
     */
    public String ConvertDxnr(String dxnr, SmsMessage entity) {
        String strFormat = dxnr;
        strFormat = strFormat.replace("{yhbh}", entity.getYhbh());
        strFormat = strFormat.replace("{yhxm}", entity.getYhxm());
        strFormat = strFormat.replace("{yhdz}", entity.getYhdz());
        strFormat = strFormat.replace("{lxdh}", entity.getLxdh());
        strFormat = strFormat.replace("{qf}", new DecimalFormat("#.##").format(entity.getQf()));
        strFormat = strFormat.replace("{txnr}", null == entity.getTxnr() ? "" : entity.getTxnr());
        strFormat = strFormat.replace("{date}", new SimpleDateFormat("yyyy/MM/dd").format(entity.getScsj()));
        return strFormat;
    }

    /**
     * 转换视图
     *
     * @param infoList
     * @return
     */
    public List<SmsMessageVo> viewConversion(List<SmsMessage> infoList) {
        if (CollectionUtils.isEmpty(infoList)) {
            return Collections.emptyList();
        }
        List<SmsTxlx> smsTxlxList = iSmsTxlxService.list();
        List<SmsMessageVo> infoVoList = new ArrayList<>();
        infoList.forEach(info -> {
            SmsMessageVo baseInfo = JSONObject.parseObject(JSON.toJSONString(info), SmsMessageVo.class);

            if (null != info.getFszt()) {
                baseInfo.setFsztName(SmsMessageFsztTypeEnum.getCodeForValue(info.getFszt()));
            }
            if (null != info.getTxlx()) {
                SmsTxlx smsTxlx = smsTxlxList.stream()
                        .filter(item -> item.getCode().equals(info.getTxlx())).findFirst().orElse(null);
                if (StringUtil.isNotNull(smsTxlx)) {
                    baseInfo.setTxlxName(smsTxlx.getName());
                }
            }

            infoVoList.add(baseInfo);
        });
        return infoVoList;
    }

    /**
     * 发送模板短信
     *
     * @param dto 条件参数条件参数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultRespone<Object> SendTxlxMessage(SendTxlxMessageDto dto) {
        ResultRespone<Object> rest = new ResultRespone<>();

        SmsMessage smsMessage = new SmsMessage();
        smsMessage.setId(GuidGenerator.getGuid());
        smsMessage.setLsh(dto.getLsbh());
        smsMessage.setScsj(new Date());
        smsMessage.setFszt("0");
        smsMessage.setSLock("0");
        smsMessage.setTxnr(dto.getDxnr());
        smsMessage.setLxdh(dto.getLxdh());
        smsMessage.setTxlx(dto.getTxlx());

        this.save(smsMessage);
        rest.setMessage("添加到待发送短信列表成功！");
        rest.setCode(1);
        return rest;
    }
}
