package com.hzs.third.sms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.sale.ext.SaOrderItemsExt;
import com.hzs.common.domain.third.sms.TSmsRecord;
import com.hzs.common.domain.third.sms.TSmsTemplate;
import com.hzs.common.domain.third.sms.ext.TSmsRecordExt;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.order.ISaOrderServiceApi;
import com.hzs.third.sms.mapper.TSmsRecordMapper;
import com.hzs.third.sms.param.SmsCreateParam;
import com.hzs.third.sms.param.SmsRecordQueryParam;
import com.hzs.third.sms.service.ITSmsRecordService;
import com.hzs.third.sms.service.ITSmsTemplateService;
import com.hzs.third.sms.util.SmsUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 短信发送记录 服务实现类
 */
@Service
public class TSmsRecordServiceImpl extends ServiceImpl<TSmsRecordMapper, TSmsRecord> implements ITSmsRecordService {

    @Autowired
    private ITSmsTemplateService itSmsTemplateService;

    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    ISaOrderServiceApi iSaOrderServiceApi;

    @Override
    public List<TSmsRecordExt> queryList(SmsRecordQueryParam param, Integer pkCountry) {
        return baseMapper.queryList(param, pkCountry);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String pageSms(SmsCreateParam param, Long userId, Integer pkCountry) {
        TSmsTemplate smsTemplate = itSmsTemplateService.getById(param.getTemplateId());
        if (null == smsTemplate) {
            return "短信模板不存在";
        }
        if (EYesNo.NO.getIntValue() == smsTemplate.getEnable()) {
            return "短信模板禁止使用";
        }
        // 模板编号
        String templateCode = smsTemplate.getTemplateCode();
        // 发送内容
        String templateContent = smsTemplate.getTemplateContent();

        ESmsTemplate eSmsTemplate = ESmsTemplate.getEnumsByCode(templateCode);
        if (null != eSmsTemplate) {
            // 短信枚举存在
            if (!eSmsTemplate.isCreate()) {
                return "该短信模板不能手动发送";
            }
        }

        // 需要入库的短信记录列表
        List<TSmsRecord> smsRecordList = new ArrayList<>();

        // 发送范围
        Integer sendScope = param.getSendScope();
        // 发送方式
        Integer sendType = param.getSendType();
        // 发送时间
        Date sendTime = param.getSendTime();
        // 参数列表
        List<String> paramList = param.getParamList();

        // 短信枚举存在，则需要判断使用哪种方式
        if (ESmsSendScope.MEMBER.getValue() == sendScope) {
            // 指定会员
            List<Long> pkMemberList = param.getMemberList();
            if (CollectionUtil.isNotEmpty(pkMemberList)) {
                // 根据传入的会员ID查询会员信息
                List<CuMemberExt> cuMemberList = iMemberServiceApi.findMemberByMemberId(pkMemberList, pkCountry).getData();

                // 预置会员短信模板，参数使用固定值进行填
                if (SmsUtil.getMemberTemplateList().contains(smsTemplate.getTemplateCode())) {
                    // 预置模板，可以进行处理
                    // 目前会员短信没有预置模板
                } else {
                    // 非预置模板
                    for (CuMemberExt cuMember : cuMemberList) {
                        // 发送内容
                        String content;
                        if (CollectionUtil.isNotEmpty(paramList)) {
                            // 传入参数列表
                            content = String.format(templateContent, paramList.toArray());
                        } else {
                            // 非传入参数列表，默认使用会员编号做为填充参数
                            content = String.format(templateContent, cuMember.getMemberCode());
                        }

                        smsRecordList.add(this.createRecord(
                                smsTemplate.getPkId(), cuMember.getPkId(), cuMember.getPhone(),
                                content, sendScope, sendType, sendTime, userId, pkCountry
                        ));
                    }
                }
            }
        } else if (ESmsSendScope.ORDER.getValue() == sendScope) {
            // 指定订单
            List<Long> orderIdList = param.getOrderList();
            if (CollectionUtil.isNotEmpty(orderIdList)) {
                // 根据传入的订单ID查询订单信息
                List<SaOrderItemsExt> saOrderList = iSaOrderServiceApi.queryOrderItemsListByOrderId(orderIdList, pkCountry).getData();

                // 预置订单短信模板，参数使用固定值进行填
                if (SmsUtil.getOrderTemplateList().contains(smsTemplate.getTemplateCode())) {
                    // 预置模板，可以进行处理
                    for (SaOrderItemsExt saOrder : saOrderList) {
                        // 发送内容
                        String content = templateContent;
                        if (CollectionUtil.isNotEmpty(paramList)) {
                            // 传入参数列表
                            content = String.format(templateContent, paramList.toArray());
                        } else {
                            // 非传入参数列表，默认使用快递单号做为填充参数
                            if (smsTemplate.getParamNum() == 1) {
                                content = String.format(templateContent, saOrder.getLogisticsCode());
                            }
                        }

                        smsRecordList.add(this.createRecord(
                                smsTemplate.getPkId(), saOrder.getPkMember(), saOrder.getRecPhone(),
                                content, sendScope, sendType, sendTime, userId, pkCountry
                        ));
                    }
                } else {
                    // 非预置模板
                    for (SaOrderItemsExt saOrder : saOrderList) {
                        // 发送内容
                        String content = templateContent;
                        if (CollectionUtil.isNotEmpty(paramList)) {
                            // 传入参数列表
                            content = String.format(templateContent, paramList.toArray());
                        } else {
                            // 非传入参数列表，默认使用快递单号做为填充参数
                            if (smsTemplate.getParamNum() == 1) {
                                content = String.format(templateContent, saOrder.getLogisticsCode());
                            } else if (smsTemplate.getParamNum() == 2) {
                                content = String.format(templateContent, saOrder.getOrderCode(), saOrder.getLogisticsCode());
                            }
                        }

                        smsRecordList.add(this.createRecord(
                                smsTemplate.getPkId(), saOrder.getPkMember(), saOrder.getRecPhone(),
                                content, sendScope, sendType, sendTime, userId, pkCountry
                        ));
                    }
                }
            }
        } else {
            // 自定义手机号
            String phones = param.getPhones();
            if (StringUtils.isNotEmpty(phones)) {
                // 处理传入手机号
                String[] phoneArr = phones.replaceAll("；", ";").split(";");

                // 自定义手机号，不区分短信模板
                for (String phone : phoneArr) {
                    // 发送内容
                    String content = templateContent;
                    if (CollectionUtil.isNotEmpty(paramList)) {
                        // 传入参数列表
                        content = String.format(templateContent, paramList.toArray());
                    }

                    smsRecordList.add(this.createRecord(
                            smsTemplate.getPkId(), null, phone,
                            content, sendScope, sendType, sendTime, userId, pkCountry
                    ));
                }
            }
        }

        if (StringUtils.isNotEmpty(smsRecordList)) {
            // 有发送数据，则进行处理
            if (ESmsSendType.IMMEDIATELY.getValue() == sendType) {
                // 立即发送
                Date nowDate = new Date();

                // 目前单现程推送，后续如果发送慢可以考虑多线程处理
                smsRecordList.forEach((tSmsRecord -> {
                    // 已发送
                    tSmsRecord.setSendStatus(ESmsSendStatus.SEND.getValue());
                    tSmsRecord.setSendTime(nowDate);
                    if (null == SmsUtil.sendSms(tSmsRecord.getPhone(), tSmsRecord.getContent())) {
                        // 发送成功
                        tSmsRecord.setSendResult(ESmsSendResult.SUCCESS.getValue());
                    } else {
                        // 发送失败
                        tSmsRecord.setSendResult(ESmsSendResult.FAIL.getValue());
                    }
                }));
            }
            baseMapper.insertBatch(smsRecordList);
        }
        return null;
    }

    /**
     * 创建短信记录
     *
     * @param templateId 模板ID
     * @param pkMember   接收用户ID
     * @param phone      发送手机号
     * @param content    发送内容
     * @param sendScope  发送范围 -- ESmsSendScope
     * @param sendType   发送类型 -- ESmsSendType
     * @param sendTime   发送时间
     * @param userId     操作用户ID
     * @param pkCountry  所属国家
     * @return
     */
    private TSmsRecord createRecord(Integer templateId, Long pkMember, String phone,
                                    String content, Integer sendScope, Integer sendType,
                                    Date sendTime, Long userId, Integer pkCountry) {
        TSmsRecord tSmsRecord = new TSmsRecord();
        tSmsRecord.setPkSmsTemplate(templateId);
        tSmsRecord.setPkMember(pkMember);
        tSmsRecord.setPhone(phone);
        tSmsRecord.setContent(content);
        tSmsRecord.setSendScope(sendScope);
        tSmsRecord.setSendType(sendType);
        tSmsRecord.setSendStatus(ESmsSendStatus.NOT_SEND.getValue());
        tSmsRecord.setSendResult(ESmsSendResult.NOT_SEND.getValue());
        tSmsRecord.setSendTime(sendTime);
        tSmsRecord.setPkCreator(userId);
        tSmsRecord.setPkCountry(pkCountry);
        return tSmsRecord;
    }

}
