package org.dromara.mp.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.constant.MpContants;
import org.dromara.common.core.enums.SmsType;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.mp.domain.SysUnitDomain;
import org.dromara.mp.domain.bo.SysUnitDomainBo;
import org.dromara.mp.domain.vo.SysUnitDomainVo;
import org.dromara.mp.exception.MpException;
import org.dromara.mp.mapper.SysUnitDomainMapper;
import org.dromara.mp.service.ISysUnitDomainService;
import org.dromara.resource.api.RemoteSmsService;
import org.dromara.resource.api.domain.TencentSmsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.*;

/**
 * 单位域名配置Service业务层处理
 *
 * @author LionLi
 * @date 2024-04-07
 */
@RequiredArgsConstructor
@Service
public class SysUnitDomainServiceImpl implements ISysUnitDomainService {

    private static final Logger log = LoggerFactory.getLogger(SysUnitDomainServiceImpl.class);
    private final SysUnitDomainMapper baseMapper;
    @DubboReference
    public RemoteSmsService smsService;


    /**
     * @Param
     * @Return
     * @Author sunzexing
     * @Date 2024-04-07 17:45
     * 说明：发送验证码
     **/

    public boolean sendSms(String phone,String domainCode){
        SysUnitDomain smsConfig = this.selSmsConfig(domainCode);
        if(smsConfig == null){
            throw new MpException("站点未配置短信参数");
        }

        if(StringUtils.isEmpty(phone)){
            throw new MpException("手机号不能为空");
        }

//        String type = (String)smsConfig.get("type");
//        String sign = (String)smsConfig.get("sign");
//        String accid = (String)smsConfig.get("accid");
//        String acckey = (String)smsConfig.get("acckey");
//        String appid = (String)smsConfig.get("appid");
//        String temp_dlyzm = (String)smsConfig.get("temp_dlyzm");
//
//        TencentSmsConfig tencentSmsConfig = new TencentSmsConfig();
//
//        tencentSmsConfig.setAccessKeyId(accid);
//        tencentSmsConfig.setAccessKeySecret(acckey);
//        tencentSmsConfig.setSignature(sign);
//        tencentSmsConfig.setSdkAppId(appid);
//        tencentSmsConfig.setTemplateId(temp_dlyzm);

        String key = GlobalConstants.CAPTCHA_MP_PHONE_CODE_KEY+SmsType.MP.getIType() + phone;
        String code = RandomUtil.randomNumbers(4);
        String cacheCode = RedisUtils.getCacheObject(key);
        if(StringUtils.isNotEmpty(cacheCode)){
            throw new MpException("2分钟内不能重复发送");
        }


        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
//        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(1000));
        LinkedHashMap<String, String> map = new LinkedHashMap<>(2);
        map.put("code", code);
        map.put("expirs","2");
        Map<String, String> map1 = new HashMap<>();
        map1.put("smsConfig", smsConfig.getSmsConfig());
 //       smsConfig.put("tempId","temp_dlyzm");

        this.smsService.sendSmsCode(SmsType.MP,phone,map,map1);

        return true;
    }


    /**
     * 查询单位域名配置
     */
    @Override
    public SysUnitDomainVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public SysUnitDomainVo queryByMpDomain(String mpDomain) {

        if(StringUtils.isEmpty(mpDomain)){
            throw new MpException("站点域名不能为空！");
        }
        String cacheKey = MpContants.MP_DOMAIN_KEY+mpDomain.hashCode()  ;
        SysUnitDomain mpDomainVo =  RedisUtils.getCacheObject(cacheKey);
        if(mpDomainVo == null){
            SysUnitDomainBo bo = new SysUnitDomainBo();
            bo.setStatus(1);
            bo.setWeChatDomainName(mpDomain);
            LambdaQueryWrapper<SysUnitDomain> lqw = buildQueryWrapper(bo);
            mpDomainVo = this.baseMapper.selectOne(lqw);
            if(mpDomainVo != null){
                RedisUtils.setCacheObject(cacheKey,mpDomainVo);
            }else{
                throw new MpException("未配置公众号站点信息");
            }
        }

        SysUnitDomainVo domainVo = new SysUnitDomainVo();
        domainVo.setWebsiteName(mpDomainVo.getWebsiteName());
        domainVo.setHotline(mpDomainVo.getHotline());
        domainVo.setCopyright(mpDomainVo.getCopyright());
        domainVo.setWapBanner(mpDomainVo.getWapBanner());
        domainVo.setWapLogo(mpDomainVo.getWapLogo());
        domainVo.setWeChatPub(mpDomainVo.getWeChatPub());
        domainVo.setMpDomainHashCode(mpDomain.hashCode()+"");
        domainVo.setPrivacyAgreement(mpDomainVo.getPrivacyAgreement());
        domainVo.setMobileUserAgreement(mpDomainVo.getMobileUserAgreement());

        return domainVo;
    }


    /**
     * @Param
     * @Return
     * @Author sunzexing
     * @Date 2024-04-07 16:39
     * 说明：获取短信配置
     **/

    @Override
    public SysUnitDomain selSmsConfig(String domainCode) {


        log.info(domainCode+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        String cacheKey = MpContants.MP_DOMAIN_KEY+domainCode;
        SysUnitDomain mpDomainVo =  RedisUtils.getCacheObject(cacheKey);

        if(mpDomainVo != null){
//            String smsConfigStr = mpDomainVo.getSmsConfig();
//            return JsonUtils.parseObject(smsConfigStr,Map.class);
            return mpDomainVo;
        }

        return null;
    }


    /**
     * @Param
     * @Return
     * @Author sunzexing
     * @Date 2024-04-07 16:39
     * 说明：获取人脸核验等其他配置
     **/
    @Override
    public Map mpOtherThirdConfig(String domainCode) {

        String cacheKey = MpContants.MP_DOMAIN_KEY+domainCode;
        SysUnitDomain mpDomainVo =  RedisUtils.getCacheObject(cacheKey);
        if(mpDomainVo != null){
            String thirdConfigStr = mpDomainVo.getWeChatThirdParams();
            return JsonUtils.parseObject(thirdConfigStr,Map.class);
        }
        return null;

    }


    /**
     * 查询单位域名配置列表
     */
    @Override
    public TableDataInfo<SysUnitDomainVo> queryPageList(SysUnitDomainBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUnitDomain> lqw = buildQueryWrapper(bo);
        Page<SysUnitDomainVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询单位域名配置列表
     */
    @Override
    public List<SysUnitDomainVo> queryList(SysUnitDomainBo bo) {
        LambdaQueryWrapper<SysUnitDomain> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUnitDomain> buildQueryWrapper(SysUnitDomainBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUnitDomain> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getDomainName()), SysUnitDomain::getDomainName, bo.getDomainName());
        lqw.like(StringUtils.isNotBlank(bo.getWebsiteName()), SysUnitDomain::getWebsiteName, bo.getWebsiteName());
        lqw.eq(StringUtils.isNotBlank(bo.getHotline()), SysUnitDomain::getHotline, bo.getHotline());
        lqw.eq(StringUtils.isNotBlank(bo.getCopyright()), SysUnitDomain::getCopyright, bo.getCopyright());
        lqw.eq(StringUtils.isNotBlank(bo.getRecordNo()), SysUnitDomain::getRecordNo, bo.getRecordNo());
        lqw.eq(StringUtils.isNotBlank(bo.getCopyrightUrl()), SysUnitDomain::getCopyrightUrl, bo.getCopyrightUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getLoginPageLogo()), SysUnitDomain::getLoginPageLogo, bo.getLoginPageLogo());
        lqw.eq(StringUtils.isNotBlank(bo.getLoginPageBanner()), SysUnitDomain::getLoginPageBanner, bo.getLoginPageBanner());
        lqw.eq(StringUtils.isNotBlank(bo.getHomePageLogo()), SysUnitDomain::getHomePageLogo, bo.getHomePageLogo());
        lqw.eq(StringUtils.isNotBlank(bo.getWapLogo()), SysUnitDomain::getWapLogo, bo.getWapLogo());
        lqw.eq(StringUtils.isNotBlank(bo.getWapBanner()), SysUnitDomain::getWapBanner, bo.getWapBanner());
        lqw.eq(StringUtils.isNotBlank(bo.getWeChatPub()), SysUnitDomain::getWeChatPub, bo.getWeChatPub());
        lqw.eq(StringUtils.isNotBlank(bo.getPcLoginProtocol()), SysUnitDomain::getPcLoginProtocol, bo.getPcLoginProtocol());
        lqw.eq(StringUtils.isNotBlank(bo.getMobileUserAgreement()), SysUnitDomain::getMobileUserAgreement, bo.getMobileUserAgreement());
        lqw.eq(StringUtils.isNotBlank(bo.getPrivacyAgreement()), SysUnitDomain::getPrivacyAgreement, bo.getPrivacyAgreement());
        lqw.eq(StringUtils.isNotBlank(bo.getWeChatDomainName()),SysUnitDomain::getWeChatDomainName,bo.getWeChatDomainName());
        lqw.eq(bo.getStatus() != null, SysUnitDomain::getStatus, bo.getStatus());
        lqw.eq(bo.getBusRole() != null, SysUnitDomain::getBusRole, bo.getBusRole());
        lqw.eq(bo.getBusId() != null, SysUnitDomain::getBusId, bo.getBusId());
        return lqw;
    }

    /**
     * 新增单位域名配置
     */
    @Override
    public Boolean insertByBo(SysUnitDomainBo bo) {
        SysUnitDomain add = MapstructUtils.convert(bo, SysUnitDomain.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改单位域名配置
     */
    @Override
    public Boolean updateByBo(SysUnitDomainBo bo) {
        SysUnitDomain update = MapstructUtils.convert(bo, SysUnitDomain.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUnitDomain entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除单位域名配置
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
