package com.slodon.b2b2c.model.member.advich;

import com.alibaba.fastjson.JSONObject;
import com.gexin.fastjson.JSON;
import com.maxmind.db.CHMCache;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Location;
import com.maxmind.geoip2.record.Subdivision;
import com.slodon.b2b2c.core.config.DomainUrlUtil;
import com.slodon.b2b2c.core.constant.*;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.sms.SmsRequest;
import com.slodon.b2b2c.core.sms.SmsResponse;
import com.slodon.b2b2c.core.util.*;
import com.slodon.b2b2c.dao.read.member.MemberEnquiryReadMapper;
import com.slodon.b2b2c.dao.write.system.EnquiryWriteMapper;
import com.slodon.b2b2c.enums.StatsTimeType;
import com.slodon.b2b2c.goods.pojo.Goods;
import com.slodon.b2b2c.member.example.MemberEnquiryExample;
import com.slodon.b2b2c.member.pojo.Member;
import com.slodon.b2b2c.member.pojo.MemberEnquiry;
import com.slodon.b2b2c.model.goods.GoodsModel;
import com.slodon.b2b2c.model.msg.MsgSendModel;
import com.slodon.b2b2c.model.msg.StoreTplModel;
import com.slodon.b2b2c.model.seller.VendorModel;
import com.slodon.b2b2c.msg.pojo.StoreTpl;
import com.slodon.b2b2c.seller.example.EnquiryReceiveMailSettingExample;
import com.slodon.b2b2c.seller.pojo.EnquiryReceiveMailSetting;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.sms.DySmsSender;
import com.slodon.b2b2c.sms.TencentSmsSender;
import com.slodon.b2b2c.sms.YunPianSmsSender;
import com.slodon.b2b2c.sms.base.SmsSender;
import com.slodon.b2b2c.statistics.example.StoreDayExample;
import com.slodon.b2b2c.statistics.example.StoreHourExample;
import com.slodon.b2b2c.statistics.example.StoreMonthExample;
import com.slodon.b2b2c.system.dto.CountryAreaApiDto;
import com.slodon.b2b2c.system.dto.EnquiryAddDTO;
import com.slodon.b2b2c.system.example.AdminEnquiryReceiveMailSettingExample;
import com.slodon.b2b2c.system.example.EnquiryExample;
import com.slodon.b2b2c.system.pojo.AdminEnquiryReceiveMailSetting;
import com.slodon.b2b2c.system.pojo.Enquiry;
import com.slodon.b2b2c.vo.member.MemberEnquiryVO;
import com.slodon.b2b2c.vo.statistics.ScreenEnquiryDistribution;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author cyan
 */
@Component
@Slf4j
public class MemberEnquiryModel {

    private static DatabaseReader reader = null;

    @Resource
    private EnquiryWriteMapper enquiryWriteMapper;
    @Resource
    private MemberEnquiryReadMapper memberEnquiryReadMapper;
    @Value("${geoip.static.city.mmdb}")
    private String geoipCityMmdb;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private StoreTplModel storeTplModel;
    @Resource
    private VendorModel vendorModel;
    @Resource
    private EnquiryReceiverMailSettingModel enquiryReceiverMailSettingModel;
    @Resource
    private GoodsModel goodsModel;
    @Resource
    private MsgSendModel msgSendModel;
    @Resource
    private AdminEnquiryReceiverMailSettingModel adminEnquiryReceiverMailSettingModel;

    /**
     * 获取数据库实例
     *
     * @param cityMmdb 可配的geoip城市静态数据库
     * @return
     */
    public DatabaseReader getDatabaseReader(String cityMmdb) {
        if (null == reader) {
            File database = new File(cityMmdb);
            try {
                reader = new DatabaseReader.Builder(database).withCache(new CHMCache()).build();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return reader;
    }

    /**
     * 根据ip解析国家/区域
     *
     * @param ip
     * @return 国家区域api对象
     */
    public CountryAreaApiDto getCountryAndAreaByIp(String ip) {
        CountryAreaApiDto dto = new CountryAreaApiDto();
        try {
            DatabaseReader reader = getDatabaseReader(geoipCityMmdb);
            InetAddress ipAddress = InetAddress.getByName(ip);
            CityResponse response = reader.city(ipAddress);
            //国家
            Country country = response.getCountry();
            dto.setCountryZhCN(country.getNames().get("zh-CN"));
            if ("香港".equals(country.getNames().get("zh-CN"))) {
                dto.setCountryZhCN("中国香港");
            }
            if ("台湾".equals(country.getNames().get("zh-CN"))) {
                dto.setCountryZhCN("中国台湾");
            }
            if ("中华民国".equals(country.getNames().get("zh-CN"))) {
                dto.setCountryZhCN("中国台湾");
            }
            if ("澳门".equals(country.getNames().get("zh-CN"))) {
                dto.setCountryZhCN("中国澳门");
            }
            dto.setCountryIsoCode(country.getIsoCode());
            //城市
            City city = response.getCity();
            dto.setCityZhCN(city.getNames().get("zh-CN"));

            //省份
            Subdivision subdivision = response.getMostSpecificSubdivision();
            dto.setSubdivisionIsoCode(subdivision.getIsoCode());
            dto.setSubdivisionZhCN(subdivision.getNames().get("zh-CN"));
            Location location = response.getLocation();
            location.getTimeZone();
            if (!StringUtil.isEmpty(location.getTimeZone())) {
                dto.setTimeZone(location.getTimeZone());
            }
            dto.setLatitude(location.getLatitude());
            dto.setLongitude(location.getLongitude());
            dto.setCityIsoCode(StringUtil.isEmpty(city.getName()) ? subdivision.getNames().get("en") : city.getName());
        } catch (IOException | GeoIp2Exception e) {
            e.printStackTrace();
        }
        return dto;
    }

    /**
     * 根据ip获取时区
     *
     * @param ip
     * @return 时区
     */
    public String getTimeZone(String ip) {
        String timeZero = "";
        try {
            DatabaseReader reader = getDatabaseReader(geoipCityMmdb);
            InetAddress ipAddress = InetAddress.getByName(ip);
            CityResponse response = reader.city(ipAddress);
            Location location = response.getLocation();
            timeZero = location.getTimeZone();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据ip获取时区异常", e);
        }
        return timeZero;
    }

    /**
     * 根据ip获取当地时区时间
     *
     * @param ip
     * @return
     */
    public Date getLocalhostTime(String ip, Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATE_FORMAT_FIVE);
        String timeZone = getTimeZone(ip);
        if (StringUtil.isEmpty(timeZone)) {
            timeZone = "Asia/Shanghai";
        }
        sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
        String dateStr = sdf.format(date);
        Date res = new Date();
        try {
            res = DateUtil.getFormatDate(dateStr, DateUtil.DATE_FORMAT_FIVE);
        } catch (Exception e) {
            log.error("根据ip获取当地时区时间", e);
        }
        return res;
    }

    /**
     * 新增询盘
     *
     * @param enquiryAddDTO
     * @return
     */
    public Integer saveEnquiry(HttpServletRequest request, EnquiryAddDTO enquiryAddDTO) throws Exception {
        Member member = UserUtil.getUser(request, Member.class);
        Enquiry enquiry = new Enquiry();
        PropertyUtils.copyProperties(enquiry, enquiryAddDTO);
        enquiry.setEmail(!StringUtil.isEmpty(enquiryAddDTO.getEmail()) ? enquiryAddDTO.getEmail() : "");
        enquiry.setCompany(!StringUtil.isEmpty(enquiryAddDTO.getCompany()) ? enquiryAddDTO.getCompany() : "");
        enquiry.setPhone(!StringUtil.isEmpty(enquiryAddDTO.getPhone()) ? enquiryAddDTO.getPhone() : "");
        enquiry.setPhoneCode(!StringUtil.isEmpty(enquiryAddDTO.getPhoneCode()) ? enquiryAddDTO.getPhoneCode() : "");
        enquiry.setCountry(!StringUtil.isEmpty(enquiryAddDTO.getCountry()) ? enquiryAddDTO.getCountry() : "");
        enquiry.setStatus(EnquiryConst.ENQUIRY_NEW);
        enquiry.setIp(WebUtil.getRealIp(request));
//        enquiry.setIp("146.23.24.105");
//        CountryAreaApiDto countryAreaApiDto = getCountryAndAreaByIp(enquiry.getIp());
//        enquiry.setCountry(countryAreaApiDto.getCountryZhCN());
//        enquiry.setRegion(countryAreaApiDto.getSubdivisionZhCN());
        enquiry.setCreateTime(new Date());
//        enquiry.setCreateTime(getLocalhostTime(enquiry.getIp(), new Date()));
        enquiry.setCreateUid(member.getMemberId());
        enquiry.setValidStatus(EnquiryConst.ENQUIRY_VALID);
        if (EnquiryConst.ENQUIRY_ITEM_TYPE_GOODS.equals(enquiry.getItemType())) {
            Goods goods = goodsModel.getStoreInfoByGoodsId(enquiry.getItemId());
            if (goods != null) {
                enquiry.setStoreId(goods.getStoreId());
            }
        }

        if (EnquiryConst.ENQUIRY_ITEM_TYPE_SHOP.equals(enquiry.getItemType())) {
            enquiry.setStoreId(enquiry.getItemId());
        }

        if (EnquiryConst.ENQUIRY_ITEM_TYPE_MALL.equals(enquiry.getItemType())) {
            enquiry.setStoreId(0L);
        }
        int count = enquiryWriteMapper.insert(enquiry);
        AssertUtil.notNullOrZero(count, "询盘保存失败，请重试");
        //发送询盘邮件
        sendEnquiryEmail(enquiry);
        //发送询盘短信通知
        sendEnquirySms(enquiry);
        return count;
    }

    /**
     * @param example 查询条件信息
     * @param pager   分页信息
     */
    public List<MemberEnquiry> getEnquiryList(MemberEnquiryExample example, PagerInfo pager) {
        List<MemberEnquiry> enquiryList;
        if (pager != null) {
            pager.setRowsCount(memberEnquiryReadMapper.countByExample(example));
            enquiryList = memberEnquiryReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
        } else {
            enquiryList = memberEnquiryReadMapper.listByExample(example);
        }
        return enquiryList;
    }

    /**
     * 获取询盘趋势
     *
     * @param timeType
     * @param start
     * @param end
     * @param storeId
     * @return
     */
    public List<MemberEnquiry> getSellerEnquiryTrendList(StatsTimeType timeType, Date start, Date end,String webSite, Long storeId) throws Exception {
        List<MemberEnquiry> enquiryList = new ArrayList<>();
        log.info("timeType:{}", timeType);
        switch (timeType) {
            case HOUR:
                enquiryList = getSellerEnquryHoursInfo(start, end,webSite, storeId);
                break;
            case DAY:
                enquiryList = getSellerEnquryDaysInfo(start, end, webSite, storeId);
                break;
            case WEEK:
                enquiryList = getSellerEnquryDaysInfo(start, end, webSite, storeId);
                break;
            case MONTH:
                enquiryList = getSellerEnquryDaysInfo(start, end, webSite, storeId);
                break;
            case YEAR:
                enquiryList = getSellerEnquryDaysInfo(start, end, webSite, storeId);
                break;
        }
        return enquiryList;
    }

    /**
     * 每天询盘趋势
     *
     * @param start
     * @param end
     * @param storeId
     * @return
     * @throws Exception
     */
    private List<MemberEnquiry> getSellerEnquryDaysInfo(Date start, Date end,String webSite, Long storeId) throws Exception {
        Map<String, MemberEnquiry> enquiryMap = new HashMap<>();
        List<MemberEnquiry> enquiryList = memberEnquiryReadMapper.getSellerEnquiryTrendByTime(start, end, webSite, storeId);
        enquiryList.forEach(c -> {
            enquiryMap.put(c.getEnquiryDay(), c);
        });
        List<String> enquiryDays = enquiryList.stream().map(MemberEnquiry::getEnquiryDay).collect(Collectors.toList());
        List<MemberEnquiry> newLineList = new ArrayList<>();
        List<String> dateList = DateUtil.getBetweenDates(start, end);
        for (String s : dateList) {
            MemberEnquiry enquiry = new MemberEnquiry();
            if (enquiryDays.contains(s)) {
                enquiry = enquiryMap.get(s);
            } else {
                MemberEnquiry enquiry2 = new MemberEnquiry();
                enquiry2.setEnquiryDay(s);
                enquiry2.setEnquiryNum(0);
                enquiry = enquiry2;
            }
            newLineList.add(enquiry);
        }
        return newLineList;
    }

    /**
     * 每小时询盘趋势
     *
     * @param start
     * @param end
     * @param webSite
     * @param storeId
     * @return
     */
    private List<MemberEnquiry> getSellerEnquryHoursInfo(Date start, Date end, String webSite, Long storeId) {
        List<MemberEnquiry> enquiryHoursList = memberEnquiryReadMapper.getSellerEnquiryTrendByHour(start, end, webSite, storeId);

        Map<String, MemberEnquiry> enquiryMap = new HashMap<>();
        enquiryHoursList.forEach(c -> {
            enquiryMap.put(c.getEnquiryDay(), c);
        });
        List<String> enquiryHours = enquiryHoursList.stream().map(MemberEnquiry::getEnquiryDay).collect(Collectors.toList());

        List<MemberEnquiry> newLineList = new ArrayList<>();
        List<String> hourList = new LinkedList<>();
        List<LocalTime> tmpList = Stream.iterate(LocalTime.of(0, 0), seed ->
                seed.plusMinutes(60)).limit(24).collect(Collectors.toList());
        tmpList.forEach(k -> hourList.add(k.toString()));

        for (String hour : hourList) {
            MemberEnquiry enquiry = new MemberEnquiry();
            if (enquiryHours.contains(hour)) {
                enquiry = enquiryMap.get(hour);
            } else {
                MemberEnquiry enquiry2 = new MemberEnquiry();
                enquiry2.setEnquiryDay(hour);
                enquiry2.setEnquiryNum(0);
                enquiry = enquiry2;
            }
            newLineList.add(enquiry);
        }
        return newLineList;
    }

    /**
     * 获取询盘趋势
     *
     * @param timeType
     * @param start
     * @param end
     * @return
     */
    public List<MemberEnquiry> getAdminEnquiryTrendList(StatsTimeType timeType, Date start, Date end,String webSite) throws Exception {
        List<MemberEnquiry> enquiryList = new ArrayList<>();
        log.info("timeType:{}", timeType);
        switch (timeType) {
            case HOUR:
                enquiryList = getAdminEnquryHoursInfo(start, end, webSite);
                break;
            case DAY:
                enquiryList = getAdminEnquryDaysInfo(start, end, webSite);
                break;
            case WEEK:
                enquiryList = getAdminEnquryDaysInfo(start, end, webSite);
                break;
            case MONTH:
                enquiryList = getAdminEnquryDaysInfo(start, end, webSite);
                break;
            case YEAR:
                enquiryList = getAdminEnquryDaysInfo(start, end, webSite);
                break;
        }
        return enquiryList;
    }

    /**
     * 每天询盘趋势
     *
     * @param start
     * @param end
     * @return
     * @throws Exception
     */
    private List<MemberEnquiry> getAdminEnquryDaysInfo(Date start, Date end,String webSite) throws Exception {
        Map<String, MemberEnquiry> enquiryMap = new HashMap<>();
        List<MemberEnquiry> enquiryList = memberEnquiryReadMapper.getAdminEnquiryTrendByTime(start, end, webSite);
        enquiryList.forEach(c -> {
            enquiryMap.put(c.getEnquiryDay(), c);
        });
        List<String> enquiryDays = enquiryList.stream().map(MemberEnquiry::getEnquiryDay).collect(Collectors.toList());
        List<MemberEnquiry> newLineList = new ArrayList<>();
        List<String> dateList = DateUtil.getBetweenDates(start, end);
        for (String s : dateList) {
            MemberEnquiry enquiry = new MemberEnquiry();
            if (enquiryDays.contains(s)) {
                enquiry = enquiryMap.get(s);
            } else {
                MemberEnquiry enquiry2 = new MemberEnquiry();
                enquiry2.setEnquiryDay(s);
                enquiry2.setEnquiryNum(0);
                enquiry = enquiry2;
            }
            newLineList.add(enquiry);
        }
        return newLineList;
    }

    /**
     * 每小时询盘趋势
     *
     * @param start
     * @param end
     * @return
     */
    private List<MemberEnquiry> getAdminEnquryHoursInfo(Date start, Date end,String webSite) {
        List<MemberEnquiry> enquiryHoursList = memberEnquiryReadMapper.getAdminEnquiryTrendByHour(start, end, webSite);

        Map<String, MemberEnquiry> enquiryMap = new HashMap<>();
        enquiryHoursList.forEach(c -> {
            enquiryMap.put(c.getEnquiryDay(), c);
        });
        List<String> enquiryHours = enquiryHoursList.stream().map(MemberEnquiry::getEnquiryDay).collect(Collectors.toList());

        List<MemberEnquiry> newLineList = new ArrayList<>();
        List<String> hourList = new LinkedList<>();
        List<LocalTime> tmpList = Stream.iterate(LocalTime.of(0, 0), seed ->
                seed.plusMinutes(60)).limit(24).collect(Collectors.toList());
        tmpList.forEach(k -> hourList.add(k.toString()));

        for (String hour : hourList) {
            MemberEnquiry enquiry = new MemberEnquiry();
            if (enquiryHours.contains(hour)) {
                enquiry = enquiryMap.get(hour);
            } else {
                MemberEnquiry enquiry2 = new MemberEnquiry();
                enquiry2.setEnquiryDay(hour);
                enquiry2.setEnquiryNum(0);
                enquiry = enquiry2;
            }
            newLineList.add(enquiry);
        }
        return newLineList;
    }

    /**
     * 卖家端-询盘列表
     *
     * @param name
     * @param email
     * @param storeId
     * @param isStoreAdmin
     * @param vendorId
     * @param validStatus
     * @param webSite
     * @param phone
     * @param pager
     * @return
     */
    public List<MemberEnquiry> getEnquiryListByPage(String name, String email, Long storeId, String isStoreAdmin, Long vendorId, Integer validStatus,String webSite,String phone, PagerInfo pager) {
        List<MemberEnquiry> enquiryList = null;
        if (pager != null) {
            enquiryList = memberEnquiryReadMapper.enquiryListPage(name, email, storeId, isStoreAdmin, vendorId, validStatus, webSite, phone, pager.getStart(), pager.getPageSize());
        }
        return enquiryList;
    }

    /**
     * 卖家端-询盘数量
     *
     * @param name
     * @param email
     * @param storeId
     * @param isStoreAdmin
     * @param vendorId
     * @param validStatus
     * @param webSite
     * @param phone
     * @return
     */
    public Integer enquiryListPageCount(String name, String email, Long storeId, String isStoreAdmin, Long vendorId, Integer validStatus,String webSite,String phone) {
        return memberEnquiryReadMapper.enquiryListPageCount(name, email, storeId, isStoreAdmin, vendorId, validStatus, webSite, phone);
    }

    /**
     * 平台管理端-询盘列表
     *
     * @param name  查询条件信息
     * @param email 查询条件信息
     * @param storeId
     * @param isSupAdmin
     * @param sysAdminId
     * @param validStatus
     * @param webSite
     * @param phone
     * @param pager 分页信息
     */
    public List<MemberEnquiry> getEnquiryAdminListByPage(String name, String email, String isSupAdmin, Integer sysAdminId, Integer validStatus, PagerInfo pager, Long storeId, String webSite,String phone) {
        List<MemberEnquiry> enquiryList = null;
        if (pager != null) {
            enquiryList = memberEnquiryReadMapper.enquiryAdminListPage(name, email, isSupAdmin, sysAdminId, validStatus, pager.getStart(), pager.getPageSize(), storeId, webSite,phone);
        }
        return enquiryList;
    }

    /**
     * 平台管理端-询盘数量
     *
     * @param name  查询条件信息
     * @param email 查询条件信息
     * @param isSupAdmin
     * @param sysAdminId
     * @param validStatus
     * @param storeId
     * @param webSite
     * @param phone
     * @return 购物车列表
     */
    public Integer enquiryAdminListPageCount(String name, String email, String isSupAdmin, Integer sysAdminId, Integer validStatus, Long storeId, String webSite,String phone) {
        return memberEnquiryReadMapper.enquiryAdminListPageCount(name, email, isSupAdmin, sysAdminId, validStatus, storeId, webSite, phone);
    }

    /**
     * 根据条件获取会员询盘数量
     *
     * @param example 查询条件信息
     * @return
     */
    public Integer getMemberEnquiryCount(MemberEnquiryExample example) {
        return memberEnquiryReadMapper.countByExample(example);
    }

    /**
     * 询盘删除
     *
     * @param enquiryId
     * @return
     */
    public Integer delMemberEnquiry(HttpServletRequest request, Long enquiryId) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);
        EnquiryExample enquiryExample = new EnquiryExample();
        EnquiryExample.Criteria criteria = enquiryExample.createCriteria();
        criteria.andIdEqualTo(enquiryId);
        Enquiry enquiry = new Enquiry();
        enquiry.setStatus(EnquiryConst.ENQUIRY_DELETE);
        enquiry.setLastUid(vendor.getVendorId());
        enquiry.setLastUsername(vendor.getVendorName());
        enquiry.setLastTime(new Date());
        int count = enquiryWriteMapper.updateByExampleSelective(enquiry, enquiryExample);
        AssertUtil.notNullOrZero(count, "询盘删除失败，请重试");
        return count;
    }

    /**
     * 发送询盘邮件
     *
     * @param enquiry
     */
    public void sendEnquiryEmail(Enquiry enquiry) {
        log.info("*********** 开始发送询盘邮件::sendEnquiryEmail **********");
        log.info("**** 询盘信息如下:{} ****", JSON.toJSONString(enquiry));
        List<String> tos = new ArrayList<>();
        if (enquiry.getStoreId() == 0) {
            AdminEnquiryReceiveMailSettingExample adminEnquiryReceiveMailSettingExample = new AdminEnquiryReceiveMailSettingExample();
            adminEnquiryReceiveMailSettingExample.setWebSite(enquiry.getWebSite());
            List<AdminEnquiryReceiveMailSetting> list = adminEnquiryReceiverMailSettingModel.getEnquiryAdminReceiveMailSettings(adminEnquiryReceiveMailSettingExample, null);
            if (!CollectionUtils.isEmpty(list)) {
                tos = list.stream().map(AdminEnquiryReceiveMailSetting::getEmail).collect(Collectors.toList());
            }
        } else {
            EnquiryReceiveMailSettingExample enquiryReceiveMailSettingExample = new EnquiryReceiveMailSettingExample();
            enquiryReceiveMailSettingExample.setWebSite(enquiry.getWebSite());
            enquiryReceiveMailSettingExample.setStoreId(enquiry.getStoreId());
            List<EnquiryReceiveMailSetting> list = enquiryReceiverMailSettingModel.getEnquiryReceiveMailSettings(enquiryReceiveMailSettingExample, null);
            if (!CollectionUtils.isEmpty(list)) {
                tos = list.stream().map(EnquiryReceiveMailSetting::getEmail).collect(Collectors.toList());
            }
        }
//        List<String> tos = new ArrayList<>();
//        tos.add("1245357320@qq.com");
//        tos.add("cyan95@hotmail.com");
        if (!CollectionUtils.isEmpty(tos)) {
            //网站名称
            String siteName = stringRedisTemplate.opsForValue().get("basic_site_name");
            //获取对应的模版
            StoreTpl storeTpl = storeTplModel.getStoreTplByTplCode(StoreTplConst.ENQUIRY_REMINDER);
            if (storeTpl == null) {
                log.error("******* 询盘邮件模板不存在 *******");
                return;
            }
            //正则匹配定义的参数
            Pattern pattern = Pattern.compile("[{][$]\\S*?}");
            if (storeTpl.getEmailSwitch().equals(MsgConst.IS_OPEN_SWITCH_YES)) {
                try {
                    String[] siteParam = {siteName};
                    //定义参数值
                    if (StringUtil.isEmpty(enquiry.getPhone())) {
                        enquiry.setPhoneCode("");
                    }
                    String[] templateArray = {enquiry.getName(), enquiry.getEmail(), enquiry.getCountry(), enquiry.getPhoneCode(), enquiry.getPhone(), enquiry.getQuantity() == null ? "-" : String.valueOf(enquiry.getQuantity()), enquiry.getMessage(), enquiry.getPageUrl()};
                    sendHtmlMail(storeTpl.getEmailContent(), tos, siteParam, templateArray, pattern);
                } catch (Exception e) {
                    log.error("[sendEnquiryInfo][发送邮件]:", e);
                }
            }
        }
    }

    /**
     * 发送询盘短信
     *
     * @param enquiry
     */
    public void sendEnquirySms(Enquiry enquiry) {
        log.info("*********** 开始发送询盘短信::sendEnquirySms **********");
        log.info("**** 询盘信息如下:{} ****", JSON.toJSONString(enquiry));
        List<String> mobiles = new ArrayList<>();
        if (enquiry.getStoreId() == 0) {
            AdminEnquiryReceiveMailSettingExample adminEnquiryReceiveMailSettingExample = new AdminEnquiryReceiveMailSettingExample();
            adminEnquiryReceiveMailSettingExample.setWebSite(enquiry.getWebSite());
            List<AdminEnquiryReceiveMailSetting> list = adminEnquiryReceiverMailSettingModel.getEnquiryAdminReceiveMailSettings(adminEnquiryReceiveMailSettingExample, null);
            if (!CollectionUtils.isEmpty(list)) {
                mobiles = list.stream().filter(admin -> !StringUtil.isEmpty(admin.getPhone())).map(AdminEnquiryReceiveMailSetting::getPhone).collect(Collectors.toList());
            }
        } else {
            EnquiryReceiveMailSettingExample enquiryReceiveMailSettingExample = new EnquiryReceiveMailSettingExample();
            enquiryReceiveMailSettingExample.setWebSite(enquiry.getWebSite());
            enquiryReceiveMailSettingExample.setStoreId(enquiry.getStoreId());
            List<EnquiryReceiveMailSetting> list = enquiryReceiverMailSettingModel.getEnquiryReceiveMailSettings(enquiryReceiveMailSettingExample, null);
            if (!CollectionUtils.isEmpty(list)) {
                mobiles = list.stream().filter(s -> !StringUtil.isEmpty(s.getPhone())).map(EnquiryReceiveMailSetting::getPhone).collect(Collectors.toList());
            }
        }
        if (!CollectionUtils.isEmpty(mobiles)) {
            String mobilesStr = mobiles.stream().collect(Collectors.joining(","));
            log.info("mobilesStr:{}", mobilesStr);
            SmsSender smsSender = new DySmsSender(stringRedisTemplate);
            SmsRequest smsRequest = new SmsRequest();
            smsRequest.setSmsType(SMSConst.NOTIFICATION_SMS);
            smsRequest.setMobile(mobilesStr);
            String templateCode = stringRedisTemplate.opsForValue().get("notification_sms_ali_enquiry_sms_template");
            log.info("templateCode:{}", templateCode);
            if (!StringUtil.isEmpty(templateCode)) {
                smsRequest.setTemplateId(templateCode);
                log.info("smsRequest:{}", JSON.toJSONString(smsRequest));
                SmsResponse smsResponse = smsSender.sendSms(smsRequest);
                log.info("smsResponse:{}", JSON.toJSONString(smsResponse));
            }
        }
    }

    /**
     * @param emailContent
     * @param toAddress
     * @param siteParam
     * @param templateArray
     * @param pattern
     */
    private void sendHtmlMail(String emailContent, List<String> toAddress, String[] siteParam, String[] templateArray, Pattern pattern) {
        JSONObject jsonObjectForEmail = JSONObject.parseObject(emailContent);
        String subject = jsonObjectForEmail.getString("email_subject");
        String content = jsonObjectForEmail.getString("email_content");
        //内容替换
        Matcher matcher = pattern.matcher(subject);
        int i = 0;
        while (matcher.find()) {
            subject = subject.replace(matcher.group(), siteParam[i++]);
        }
        Matcher contentMatcher = pattern.matcher(content);
        int j = 0;
        while (contentMatcher.find()) {
            content = content.replace(contentMatcher.group(), templateArray[j++]);
        }
        //发邮件
        msgSendModel.sendHtmlMail(toAddress, subject, content);
    }

    /**
     * 询盘地域分布
     * @param webSite
     * @return
     */
    public List<ScreenEnquiryDistribution> getEnquiryDistribution(String webSite) {
        return memberEnquiryReadMapper.getEnquiryDistribution(webSite);
    }
}
