package com.usky.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.util.DateUtils;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.iot.domain.CrmCustomRemind;
import com.usky.iot.mapper.CrmCustomRemindMapper;
import com.usky.iot.service.CrmCustomRemindService;
import com.usky.common.mybatis.core.AbstractCrudService;
import org.springframework.stereotype.Service;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * <p>
 * 客户提醒信息表 服务实现类
 * </p>
 *
 * @author han
 * @since 2023-06-27
 */
@Service
public class CrmCustomRemindServiceImpl extends AbstractCrudService<CrmCustomRemindMapper, CrmCustomRemind> implements CrmCustomRemindService {

    @Override
    public void add(CrmCustomRemind crmCustomRemind){
        String method = crmCustomRemind.getRemindMethod();
        StringBuffer sendStatus = new StringBuffer();
        StringBuffer sendContext = new StringBuffer();
        //发送短信
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", "LTAI5tH3VvRL5BUkovCokHJX", "SaaWUouNqvcA0C746gcNOH9m6SRYN4");
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(crmCustomRemind.getPhone());//接收短信的手机号码
        request.setSignName("上海永天科技股份有限公司");//短信签名名称
        request.setTemplateCode("SMS_461850226");//短信模板CODE
        Date date = DateUtils.parseDate(crmCustomRemind.getExpireDate());
        long days = (date.getTime() - new Date().getTime())/(24*60*60*1000);

        String custom = "#/pages/common/invoicing/index?customId="+crmCustomRemind.getCustomId();
        request.setTemplateParam("{\"date\":\""+crmCustomRemind.getExpireDate()+"\","+"\"custom\":\""+custom+"\"}");//短信模板变量对应的实际值

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            if(response.getCode() != null){
                if(response.getCode().equals("OK")){
                    sendStatus.append("1");
                    //查询发送短信内容

                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    QuerySendDetailsRequest request1 = new QuerySendDetailsRequest();
                    request1.setPhoneNumber(crmCustomRemind.getPhone());
                    request1.setSendDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
                    request1.setPageSize((long)10);
                    request1.setCurrentPage((long)1);
                    QuerySendDetailsResponse response1 = client.getAcsResponse(request1);
                    if(response1.getCode() != null){
                        if(response1.getCode().equals("OK")){
                            sendContext.append(response1.getSmsSendDetailDTOs().get(0).getContent());
                        }

                    }

                }else{
                    sendStatus.append("2");
                }
            }
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }

        crmCustomRemind.setSendStatus(sendStatus.toString());  //发送状态需要根据发送返回结果确认
        crmCustomRemind.setSendContext(sendContext.toString()); //发送内容
        crmCustomRemind.setSendTime(LocalDateTime.now());
        crmCustomRemind.setCreateBy(SecurityUtils.getUsername());
        crmCustomRemind.setCreateTime(LocalDateTime.now());
        crmCustomRemind.setTenantId(SecurityUtils.getTenantId());
        this.save(crmCustomRemind);
    }

    @Override
    public CommonPage<CrmCustomRemind> page(Integer current, Integer size, Integer customId){
        IPage<CrmCustomRemind> page = new Page<>(current,size);
        LambdaQueryWrapper<CrmCustomRemind> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CrmCustomRemind::getCustomId,customId)
                .eq(CrmCustomRemind::getTenantId,SecurityUtils.getTenantId())
                .orderByDesc(CrmCustomRemind::getId);
        page = this.page(page,queryWrapper);

        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getSize(),page.getCurrent());
    }

}
