package org.dromara.resource.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.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.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.MpLoginHelper;
import org.dromara.common.sms.config.SmsProperties;
import org.dromara.resource.danmi_sms.DMSmsUtils;
import org.dromara.resource.danmi_sms.common.DMSmsResult;
import org.dromara.resource.danmi_sms.config.SmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.resource.domain.bo.SysSmsBo;
import org.dromara.resource.domain.vo.SysSmsVo;
import org.dromara.resource.domain.SysSms;
import org.dromara.resource.mapper.SysSmsMapper;
import org.dromara.resource.service.ISysSmsService;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 短信Service业务层处理
 *
 * @author sunzexing
 * @date 2024-03-27
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SysSmsServiceImpl implements ISysSmsService {

    private final SysSmsMapper baseMapper;

    @Resource
    private SmsProperties smsProperties;

    @Autowired
    private DMSmsUtils dmSmsUtils;


    /**
     * 查询短信
     */
    @Override
    public SysSmsVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询短信列表
     */
    @Override
    public TableDataInfo<SysSmsVo> queryPageList(SysSmsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysSms> lqw = buildQueryWrapper(bo);
        Page<SysSmsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询短信列表
     */
    @Override
    public List<SysSmsVo> queryList(SysSmsBo bo) {
        LambdaQueryWrapper<SysSms> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysSms> buildQueryWrapper(SysSmsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysSms> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getIType() != null, SysSms::getVType, bo.getIType());
        lqw.like(StringUtils.isNotBlank(bo.getVUserName()), SysSms::getVUserName, bo.getVUserName());
        lqw.eq(bo.getIUserId() != null, SysSms::getIUserId, bo.getIUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getVPhone()), SysSms::getVPhone, bo.getVPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getVVerCode()), SysSms::getVVerCode, bo.getVVerCode());
        lqw.eq(StringUtils.isNotBlank(bo.getVTempId()), SysSms::getVTempId, bo.getVTempId());
        lqw.eq(StringUtils.isNotBlank(bo.getVSendContent()), SysSms::getVSendContent, bo.getVSendContent());
        lqw.eq(bo.getDtmSendTime() != null, SysSms::getDtmSendTime, bo.getDtmSendTime());
        lqw.eq(bo.getDtmExpirTime() != null, SysSms::getDtmExpirTime, bo.getDtmExpirTime());
        lqw.eq(bo.getIsUse() != null, SysSms::getIsUse, bo.getIsUse());
        lqw.eq(bo.getIStatus() != null, SysSms::getIStatus, bo.getIStatus());
        return lqw;
    }

    /**
     * 新增短信
     */
    @Override
    public Boolean insertByBo(SysSmsBo bo) {
        SysSms add = MapstructUtils.convert(bo, SysSms.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改短信
     */
    @Override
    public Boolean updateByBo(SysSmsBo bo) {
        SysSms update = MapstructUtils.convert(bo, SysSms.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    @Override
    public Boolean sendMpSmsCode(String phone) {
        return null;
    }


    /*
     * @Param
     * @Return
     * @Author sunzexing
     * @Date 2024-03-27 13:45
     * 说明：发送公众号登录验证码
     **/
    @Override
    public Boolean sendMpSmsCode(String domain, String phone) {
//        String key = GlobalConstants.CAPTCHA_CODE_KEY+SmsType.MP.getIType() + phone;
//        String code = RandomUtil.randomNumbers(4);
//        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(SmsType.MP.getExpireTime()));
//        LinkedHashMap<String, String> map = new LinkedHashMap<>();
//        map.put("code", code);
//        map.put("expirs", SmsType.MP.getExpireTime() + "");
//        RemoteSms sysSms = remoteSmsService.send(domain,phone,SmsType.MP,map);
        return null;
    }




    /*
     * @Param
     * @Return
     * @Author sunzexing
     * @Date 2024-04-07 17:22
     * 说明：通用发送短息
     **/

    public  Boolean sendSmsCode(SmsType smsType,
                                       String phonenumber,
                                       LinkedHashMap<String, String> param,
                                       Map smsConfig) {


        if(smsConfig == null){
            throw new RuntimeException("短信配置不能为空");
        }

        try{
            java.util.Date  currentDate = DateUtil.date().toJdkDate();
//            SmsBlend smsBlend = null;
//            String smsFacType = "tencent";
//            String tempKey =  (String)smsConfig.get("tempId");
//            String tempId = (String)smsConfig.get(tempKey);
//            if(StringUtils.isNotEmpty(smsProperties.getType())){
//                smsFacType = smsProperties.getType();
//            }
//            switch (smsFacType){
//                case "aliyun":
//                    AlibabaConfig  alibabaConfig = new AlibabaConfig();
//                    alibabaConfig.setAccessKeyId((String)smsConfig.get("accid_aliyun"));
//                    alibabaConfig.setAccessKeySecret((String)smsConfig.get("acckey_aliyun"));
//                    alibabaConfig.setSignature((String)smsConfig.get("sign_aliyun"));
//                    tempId = (String)smsConfig.get(tempKey+"_aliyun");
//                    smsBlend = SmsFactory.createSmsBlend(SupplierType.ALIBABA, alibabaConfig);
//                    break;
//                case  "tencent":
//                    TencentConfig tencentConfig = new TencentConfig();
//                    tencentConfig.setAccessKeyId((String)smsConfig.get("accid"));
//                    tencentConfig.setAccessKeySecret((String)smsConfig.get("acckey"));
//                    tencentConfig.setSignature((String)smsConfig.get("sign"));
//                    tencentConfig.setSdkAppId((String)smsConfig.get("appid"));
//                    smsBlend = SmsFactory.createSmsBlend(SupplierType.TENCENT,tencentConfig);
//                    break;
//            }

//            SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, tempId, param);
            JSONObject jsonObject = JSON.parseObject((String) smsConfig.get("smsConfig"));

            DMSmsResult result = this.dmSmsUtils.verificationCode((String) smsConfig.get("smsConfig"), phonenumber, param.get("code"));
            if(!result.isSuccess()){
                log.error("{}-{}验证码短信发送异常 => {}",smsType.getDesc(),phonenumber, result.getErrorMsg());
            }
//
//
//
//
//            if (!"OK".equals(smsResponse.getCode())) {
//                log.error("{}-{}验证码短信发送异常 => {}",smsType.getDesc(),phonenumber, smsResponse);
//            }


            SysSms smsEntity = new SysSms();

            smsEntity.setIUserId(MpLoginHelper.getUserId());
            smsEntity.setVTempId(jsonObject.get("verification").toString());
            smsEntity.setDtmSendTime(currentDate);
            smsEntity.setVType(smsType.getDesc());
            smsEntity.setVSendContent(JsonUtils.toJsonString(param));
            smsEntity.setCreateTime(currentDate);
            smsEntity.setVPhone(phonenumber);
    //        smsEntity.setDtmExpirTime(DateUtil.offsetMinute(currentDate,Constants.CAPTCHA_EXPIRATION));

            this.baseMapper.insert(smsEntity);
        }catch (Exception e){
            e.printStackTrace();
            log.error("发送短信失败==>",e.getMessage());
            throw e;
        }
        return true;
    }
}
