package com.fs.common.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.param.SmsSendBatchParam;
import com.fs.common.param.SmsSendOrderBatchParam;
import com.fs.common.param.SmsSendParam;
import com.fs.common.param.SmsSendStoreOrderParam;
import com.fs.common.service.ISmsService;
import com.fs.common.utils.StringUtils;
import com.fs.common.vo.SmsSendItemVO;
import com.fs.common.vo.SmsNotifyVO;
import com.fs.common.vo.SmsSendVO;
import com.fs.company.domain.*;
import com.fs.company.service.*;
import com.fs.crm.domain.CrmCustomer;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.service.IFsStoreOrderService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.Synchronized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements ISmsService
{
    private String account1="922164";
    private String password1="UcUo4Wkw0IFi";
    private String account2="911158";
    private String password2="Rwkwghp86";
    private String url1="http://219.152.167.228:7862/";
    private String url2="http://120.78.121.202:7862/";
    private String code1="10690";
    private String code2="10690";
    private String sign="【果雨大药房】";
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICompanySmsTempService smsTempService;

    @Autowired
    private ICompanySmsService companySmsService;

    @Autowired
    private ICompanySmsLogsService smsLogsService;

    @Autowired
    private ICrmCustomerService crmCustomerService;

    @Autowired
    private ICompanyUserService companyUserService;
    private Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);
    @Override
    public R sendTSms(String mobile, String code) {
//        try{
//
//            Credential cred = new Credential("AKIDzmMgiSFqWwf7IAttkKdfPmtjKgHbKQvg", "QebQyFEx6xWnpZ4H1Wml4B3cuvIQItJT");
//            HttpProfile httpProfile = new HttpProfile();
//            httpProfile.setEndpoint("sms.tencentcloudapi.com");
//
//            ClientProfile clientProfile = new ClientProfile();
//            clientProfile.setHttpProfile(httpProfile);
//
//            SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);
//
//            String params = "{\"PhoneNumberSet\":[\"86"+mobile+"\"],\"TemplateID\":\"1053531\",\"Sign\":\"一韩信息\",\"TemplateParamSet\":[\""+code+"\"],\"SmsSdkAppid\":\"1400511898\"}";
//            SendSmsRequest req = SendSmsRequest.fromJsonString(params, SendSmsRequest.class);
//
//            SendSmsResponse resp = client.SendSms(req);
//            System.out.println(SendSmsRequest.toJsonString(resp));
//            if(resp.getSendStatusSet()!=null&&resp.getSendStatusSet()[0].getCode().equals("Ok")){
//                //将手机号写入redis
//                redisCache.setCacheObject(mobile,String.valueOf(code),120, TimeUnit.SECONDS);
//                return R.ok("短信成功发送");
//            }
//            else{
//
//                return R.error("短信发送失败:"+resp.getSendStatusSet()[0].getCode());
//            }
//
//
//        } catch (TencentCloudSDKException e) {
//            System.out.println(e.toString());
//            return R.error(e.toString());
//        }
        return R.ok();
    }

    @Override
    @Transactional
    @Synchronized
    public R sendSms(SmsSendParam param) {
        CompanySmsTemp temp=smsTempService.selectCompanySmsTempByCode(param.getTempCode());
        if(temp!=null&&temp.getStatus().equals(1)&&temp.getIsAudit().equals(1)){
            CompanySms sms=companySmsService.selectCompanySmsByCompanyId(param.getCompanyId());
            if(sms!=null){
                if(sms.getRemainSmsCount()>0){
                    SmsSendBatchParam smsSendBatchParam=new SmsSendBatchParam();
                    smsSendBatchParam.setSmsType(temp.getTempType());
                    smsSendBatchParam.setCompanyId(param.getCompanyId());
                    smsSendBatchParam.setCompanyUserId(param.getCompanyUserId());
                    smsSendBatchParam.setTempCode(temp.getTempCode());
                    Long[] ids=new Long[1];
                    ids[0]=param.getCustomerId();
                    smsSendBatchParam.setCustomerIds(ids);
                    smsSendBatchParam.setContent(param.getContent());
                    //如果选择的是名片短链接模版  update by qxj 2023年05月26日10:45:28
                    if(StringUtils.isNotEmpty(param.getCardUrl())){
                        smsSendBatchParam.setCardUrl(param.getCardUrl());
                    }
                    batchSmsOp(temp,smsSendBatchParam);
                    return R.ok("短信提交成功，正在发送中...");
//                    //尊敬的${csName}，您好。我看到您已签收药品了，签收后不要自己乱用，第一时间拨打我的电话${phoneNumber}，我会安排指导专员指导你用药，祝你早日改善好身体，谢谢。
//                    //双十一老粉钜惠，加企微9.9换购原价199元的纯妆爆款氨基酸洗面奶。满59元，还可参与抽奖，现金红包等你拿 ！100%中奖→ https://4m.cn/BTHXp，
//                    //尊敬的${csName}，你好。我是添精补肾膏官网客服，刚刚给你去电你是因为在忙所以没接电话吗？看到信息可以回拨刚才的020固话，这边会尽快回电给你。
//                    //http://120.78.121.202:7862/sms?action=send&account=900002&password=b3Tdwn&mobile=15193190697&content=%E5%86%85%E5%AE%B9&extno=10690&rt=json
//                    String content="";
//                    content=param.getContent();
//                    content=content.replace("${sms.csName}",crmCustomer.getCustomerName());
//                    content=content.replace("${sms.phoneNumber}",companyUser.getPhonenumber());
////                    JSONObject jsonObject = new JSONObject();
////                    jsonObject.put("action","send");
////                    jsonObject.put("account",account);
////                    jsonObject.put("password",password);
////                    jsonObject.put("mobile",crmCustomer.getMobile());
////                    try {
////                        jsonObject.put("content", URLEncoder.encode(sign+content+" 退订回T", "UTF-8"));
////                    } catch (UnsupportedEncodingException e) {
////                        e.printStackTrace();
////                    }
////                    jsonObject.put("extno",code);
////                    jsonObject.put("rt","json");
//                    String urls= null;
//                    // 通知类的不加 退订回T 只有营销类的加
//                    try {
//                        if(temp.getTempType().equals(1)){
//                            urls = url1+"sms?action=send&account="+account1+"&password="+password1+"&mobile="+param.getMobile()+"&content="+ URLEncoder.encode(sign+content, "UTF-8")+"&extno="+code1+"&rt=json";
//
//                        }
//                        else if(temp.getTempType().equals(2)){
//                            urls = url2+"sms?action=send&account="+account2+"&password="+password2+"&mobile="+param.getMobile()+"&content="+ URLEncoder.encode(sign+content+"退订回T", "UTF-8")+"&extno="+code2+"&rt=json";
//
//                        }
//                    } catch (UnsupportedEncodingException e) {
//                        e.printStackTrace();
//                    }
//                    String post = HttpRequest.get(urls)
////                            .body(String.valueOf(jsonObject))
//                            .execute().body();
//                    SmsSendVO vo=JSONUtil.toBean(post, SmsSendVO.class);
//                    if(vo.getStatus().equals(0)){
//                        Integer resultCount=0;
//                        for(SmsSendItemVO itemVO:vo.getList()){
//                            if(itemVO.getResult().equals("0")){
//                                CompanySmsLogs logs=new CompanySmsLogs();
//                                logs.setCompanyId(param.getCompanyId());
//                                logs.setCustomerId(param.getCustomerId());
//                                logs.setContent(content);
//                                logs.setTempCode(temp.getTempCode());
//                                logs.setCompanyUserId(param.getCompanyUserId());
//                                logs.setTempId(temp.getTempId());
//                                logs.setPhone(param.getMobile());
//                                logs.setSendTime(new Date());
//                                logs.setStatus(0);
//                                logs.setMid(itemVO.getMid());
//
//                                Integer counts=logs.getContent().length()/67;
//                                if(logs.getContent().length()%67>0){
//                                    counts++;
//                                }
//                                if(counts==0){
//                                    counts=1;
//                                }
//                                logs.setNumber(counts);
//                                smsLogsService.insertCompanySmsLogs(logs);
//                                companySmsService.subCompanySms(logs.getCompanyId(),1);
//                                resultCount++;
//                            }
//                        }
////                        return R.ok("发送成功");
//                        if(resultCount.equals(vo.getList().size())){
//                            return R.ok("发送成功");
//                        }
//                        else{
//                            return R.error("短信发送失败,共:"+vo.getList().size()+",成功:"+resultCount+"失败:"+(vo.getList().size()-resultCount));
//                        }
//                    }
//                    else{
//                        return R.error("短信发送失败,code:"+vo.getStatus());
//                    }
                }
                else{
                    return R.error("剩余短信数量不足，请充值");
                }
            }
            else{
                return R.error("请充值");
            }
        }
        else {
            return R.error("模板未审核");
        }

    }

    @Override
    public String smsNotify(String json) {
        List<SmsNotifyVO> list = JSONUtil.parseArray(json).toList(SmsNotifyVO.class);
        if(list!=null){
            for(SmsNotifyVO vo:list){
                if(vo.getFlag()==0){ //手机用户上行
                    CompanySmsLogs logs=smsLogsService.selectCompanySmsLogsByMobile(vo.getMobile());
                    if(logs!=null){
                        logs.setReplyContent(vo.getContent());
                        smsLogsService.updateCompanySmsLogs(logs);
                    }
                }
                else if(vo.getFlag()==1){ //状态报告
                    CompanySmsLogs logs=smsLogsService.selectCompanySmsLogsByMid(vo.getMid());
                    if(logs!=null){
                        logs.setStat(vo.getStat());
                        logs.setSendTime(new Date());
                        //状态报告
                        if(vo.getStat().equals("DELIVRD")){
                            companySmsService.addCompanySms(logs.getCompanyId(),logs.getNumber());
                            logs.setStatus(1);
                        }
                        else{
                            logs.setStatus(-1);
                        }
                        smsLogsService.updateCompanySmsLogs(logs);
                    }
                }
            }
        }
        return "OK";
    }

    @Override
    @Synchronized
    public R sendBatchSms(SmsSendBatchParam param) {
        CompanySmsTemp temp=smsTempService.selectCompanySmsTempByCode(param.getTempCode());
        if(temp!=null&&temp.getStatus().equals(1)&&temp.getIsAudit().equals(1)){
            CompanySms sms=companySmsService.selectCompanySmsByCompanyId(param.getCompanyId());
            if(sms!=null){
                if(sms.getRemainSmsCount()>0){
                    if(sms.getRemainSmsCount()<(param.getCustomerIds().length*2)){
                        return R.error("短信数量不足");
                    }
                    batchSmsOp(temp,param);
                    return R.ok("短信提交成功，正在发送中...");
                }
                else{
                    return R.error("剩余短信数量不足，请充值");
                }
            }
            else{
                return R.error("请充值");
            }
        }
        else {
            return R.error("模板未审核");
        }
    }

    @Async
    public void batchSmsOp(CompanySmsTemp temp,SmsSendBatchParam param){
        CompanyUser companyUser=companyUserService.selectCompanyUserById(param.getCompanyUserId());
        for(Long id:param.getCustomerIds()){
            CrmCustomer crmCustomer=crmCustomerService.selectCrmCustomerById(id);
            String content="";
            content=param.getContent();
            if(StringUtils.isNotEmpty(crmCustomer.getCustomerName())){
                content=content.replace("${sms.csName}",crmCustomer.getCustomerName());
            }
            if(companyUser!=null&&StringUtils.isNotEmpty(companyUser.getPhonenumber())){
                content=content.replace("${sms.phoneNumber}",companyUser.getPhonenumber());
            }
            if(StringUtils.isNotEmpty(param.getCardUrl())){
                content=content.replace("${sms.cardUrl}",param.getCardUrl());
            }

            String urls= null;
            // 通知类的不加 退订回T 只有营销类的加
            //最多500个手机号
            try {
                if(temp.getTempType().equals(1)){
                    urls = url1+"sms?action=send&account="+account1+"&password="+password1+"&mobile="+crmCustomer.getMobile()+"&content="+ URLEncoder.encode(sign+content, "UTF-8")+"&extno="+code1+"&rt=json";
                }
                else if(temp.getTempType().equals(2)){
                    urls = url2+"sms?action=send&account="+account2+"&password="+password2+"&mobile="+crmCustomer.getMobile()+"&content="+ URLEncoder.encode(sign+content+"拒收请回复R", "UTF-8")+"&extno="+code2+"&rt=json";
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String post = HttpRequest.get(urls)
//                            .body(String.valueOf(jsonObject))
                    .execute().body();
            SmsSendVO vo=JSONUtil.toBean(post, SmsSendVO.class);
            if(vo.getStatus().equals(0)){
                Integer resultCount=0;
                for(SmsSendItemVO itemVO:vo.getList()){
                    if(itemVO.getResult().equals("0")){
                        CompanySmsLogs logs=new CompanySmsLogs();
                        logs.setCompanyId(param.getCompanyId());
                        logs.setCustomerId(id);
                        logs.setContent(content);
                        logs.setTempCode(temp.getTempCode());
                        logs.setCompanyUserId(param.getCompanyUserId());
                        logs.setTempId(temp.getTempId());
                        logs.setPhone(crmCustomer.getMobile());
                        logs.setSendTime(new Date());
                        logs.setStatus(0);
                        logs.setMid(itemVO.getMid());
                        Integer counts=logs.getContent().length()/67;
                        if(counts==0){
                            counts=1;
                        }
                        if(logs.getContent().length()%67>0){
                            counts=counts+1;
                        }
                        logs.setNumber(counts);
                        smsLogsService.insertCompanySmsLogs(logs);
                        companySmsService.subCompanySms(logs.getCompanyId(),logs.getNumber());
                        resultCount++;
                    }
                }
            }else{
                logger.info("----batchSmsOp:"+post);
            }


        }
    }

    @Override
    @Transactional
    @Synchronized
    public R sendStoreOrderSms(SmsSendStoreOrderParam param) {
        CompanySmsTemp temp=smsTempService.selectCompanySmsTempByCode(param.getTempCode());
        if(temp!=null&&temp.getStatus().equals(1)&&temp.getIsAudit().equals(1)){
            CompanySms sms=companySmsService.selectCompanySmsByCompanyId(param.getCompanyId());
            if(sms!=null){
                if(sms.getRemainSmsCount()>0){
                    SmsSendOrderBatchParam smsSendBatchParam=new SmsSendOrderBatchParam();
                    smsSendBatchParam.setSmsType(temp.getTempType());
                    smsSendBatchParam.setCompanyId(param.getCompanyId());
                    smsSendBatchParam.setCompanyUserId(param.getCompanyUserId());
                    smsSendBatchParam.setTempCode(temp.getTempCode());
                    smsSendBatchParam.setOrderId(param.getOrderId());
                    smsSendBatchParam.setContent(param.getContent());
                    //如果选择的是名片短链接模版  update by qxj 2023年05月26日10:45:28
                    if(StringUtils.isNotEmpty(param.getCardUrl())){
                        smsSendBatchParam.setCardUrl(param.getCardUrl());
                    }
                    batchOrderSmsOp(temp,smsSendBatchParam);
                    return R.ok("短信提交成功，正在发送中...");
                }
                else{
                    return R.error("剩余短信数量不足，请充值");
                }
            }
            else{
                return R.error("请充值");
            }
        }
        else {
            return R.error("模板未审核");
        }
    }

    @Autowired
    private IFsStoreOrderService orderService;

    @Async
    public void batchOrderSmsOp(CompanySmsTemp temp,SmsSendOrderBatchParam param){
        CompanyUser companyUser=companyUserService.selectCompanyUserById(param.getCompanyUserId());
        FsStoreOrder order  = orderService.selectFsStoreOrderById(param.getOrderId());
        String content="";
        content=param.getContent();
        if(StringUtils.isNotEmpty(order.getRealName())){
            content=content.replace("${sms.csName}",order.getRealName());
        }
        if(companyUser!=null&&StringUtils.isNotEmpty(companyUser.getPhonenumber())){
            content=content.replace("${sms.phoneNumber}",companyUser.getPhonenumber());
        }
        if(StringUtils.isNotEmpty(param.getCardUrl())){
            content=content.replace("${sms.cardUrl}",param.getCardUrl());
        }

        String urls= null;
        // 通知类的不加 退订回T 只有营销类的加
        //最多500个手机号
        try {
            if(temp.getTempType().equals(1)){
                urls = url1+"sms?action=send&account="+account1+"&password="+password1+"&mobile="+order.getUserPhone()+"&content="+ URLEncoder.encode(sign+content, "UTF-8")+"&extno="+code1+"&rt=json";
            }
            else if(temp.getTempType().equals(2)){
                urls = url2+"sms?action=send&account="+account2+"&password="+password2+"&mobile="+order.getUserPhone()+"&content="+ URLEncoder.encode(sign+content+"拒收请回复R", "UTF-8")+"&extno="+code2+"&rt=json";
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String post = HttpRequest.get(urls)
//                            .body(String.valueOf(jsonObject))
                .execute().body();
        SmsSendVO vo=JSONUtil.toBean(post, SmsSendVO.class);
        if(vo.getStatus().equals(0)){
            Integer resultCount=0;
            for(SmsSendItemVO itemVO:vo.getList()){
                if(itemVO.getResult().equals("0")){
                    CompanySmsLogs logs=new CompanySmsLogs();
                    logs.setCompanyId(param.getCompanyId());
                    logs.setContent(content);
                    logs.setTempCode(temp.getTempCode());
                    logs.setCompanyUserId(param.getCompanyUserId());
                    logs.setTempId(temp.getTempId());
                    logs.setPhone(order.getUserPhone());
                    logs.setSendTime(new Date());
                    logs.setStatus(0);
                    logs.setMid(itemVO.getMid());
                    Integer counts=logs.getContent().length()/67;
                    if(logs.getContent().length()%67>0){
                        counts=counts+1;
                    }
                    if(counts==0){
                        counts=1;
                    }
                    logs.setNumber(counts);
                    smsLogsService.insertCompanySmsLogs(logs);
                    companySmsService.subCompanySms(logs.getCompanyId(),logs.getNumber());
                    resultCount++;
                }
            }
        }



    }
}
