package com.fs.common.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;

import com.fs.common.service.ISmsService;
import com.fs.common.utils.StringUtils;
import com.fs.common.vo.SmsNotifyVO;
import com.fs.common.vo.SmsSendItemVO;
import com.fs.common.vo.SmsSendVO;
import com.fs.company.domain.*;
import com.fs.company.service.ICompanySmsLogsService;
import com.fs.company.service.ICompanySmsService;
import com.fs.company.service.ICompanySmsTempService;
import com.fs.company.service.ICompanyUserService;
import com.fs.crm.domain.CrmCustomer;
import com.fs.crm.param.SmsSendBatchParam;
import com.fs.crm.param.SmsSendParam;
import com.fs.crm.param.SmsSendUserParam;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.his.config.FsSmsConfig;
import com.fs.his.domain.FsPayConfig;
import com.fs.his.domain.FsStoreOrder;
import com.fs.his.mapper.FsPackageOrderMapper;
import com.fs.his.mapper.FsStoreOrderMapper;
import com.fs.his.vo.FsPackageOrderVO;
import com.fs.qw.domain.QwSopSmsLogs;
import com.fs.qw.mapper.QwSopSmsLogsMapper;
import com.fs.qw.service.IQwSopSmsLogsService;
import com.fs.sms.domain.SendSmsReturn;
import com.fs.sms.service.impl.SmsTServiceImpl;
import com.fs.sop.domain.QwSopLogs;
import com.fs.sop.mapper.QwSopLogsMapper;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.google.gson.Gson;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
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.ConcurrentHashMap;
import com.fs.company.service.ICompanySmsCommonLogsService;

@Service
@Slf4j
public class SmsServiceImpl implements ISmsService
{
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICompanySmsTempService smsTempService;
    @Autowired
    private SmsTServiceImpl smsTService;
    @Autowired
    private ICompanySmsService companySmsService;

    @Autowired
    private ICompanySmsLogsService smsLogsService;

    @Autowired
    private ICrmCustomerService crmCustomerService;

    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    SysConfigMapper sysConfigMapper;
    @Autowired
    FsStoreOrderMapper storeOrderMapper;

    @Autowired
    private FsPackageOrderMapper packageOrderMapper;

    @Autowired
    private ICompanySmsCommonLogsService smsCommonLogsService;

    @Autowired
    private IQwSopSmsLogsService qwSopSmsLogsService;

    @Autowired
    private QwSopLogsMapper qwSopLogsMapper;

    @Autowired
    private QwSopSmsLogsMapper qwSopSmsLogsMapper;

    @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("短信提交成功，正在发送中...");
                }
                else{
                    return R.error("剩余短信数量不足，请充值");
                }
            }
            else{
                return R.error("请充值");
            }
        }
        else {
            return R.error("模板未审核");
        }

    }

    @Override
    public String smsNotify(String json) {
        log.info("短信回调参数：{}", json);
        List<SmsNotifyVO> list = JSONUtil.parseArray(json).toList(SmsNotifyVO.class);
        if (list != null) {
            for (SmsNotifyVO vo : list) {
                if (vo.getFlag() != null && vo.getFlag() == 0) {
                    //手机用户上行
                    CompanySmsLogs logs = smsLogsService.selectCompanySmsLogsByMobile(vo.getMobile());
                    if (logs != null) {
                        logs.setReplyContent(vo.getContent());
                        smsLogsService.updateCompanySmsLogs(logs);
                        if(logs.getSopSmsLogId() != null){
                            updateQwSopSmsLogsByUuid(logs.getSopSmsLogId(), null, null, vo.getContent(),logs.getSmsIndex());
                        }
                    }
                    CompanySmsCommonLogs commonLogs = smsCommonLogsService.selectCompanySmsCommonLogsByMobile(vo.getMobile());
                    if (commonLogs != null) {
                        commonLogs.setReplyContent(vo.getContent());
                        smsCommonLogsService.updateCompanySmsCommonLogs(commonLogs);
                    }
                } else if (vo.getFlag() != null && vo.getFlag() == 1) {
                    CompanySmsLogs logs = smsLogsService.selectCompanySmsLogsByMid(vo.getMid());
                    if (logs != null && logs.getStatus().equals(0)) {
                        logs.setStat(vo.getStat());
                        if (vo.getTime() != null) {
                            try {
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                logs.setSendTime(format.parse(vo.getTime()));
                            } catch (Exception e) {

                            }
                        }
                        //状态报告
                        if (vo.getStat().equals("DELIVRD")) {
                            logs.setStatus(1);
                        } else {
                            logs.setStatus(-1);
                            companySmsService.addCompanySms(logs.getCompanyId(), logs.getNumber());
                        }
                        smsLogsService.updateCompanySmsLogs(logs);
                    }

                    if(logs != null && logs.getSopSmsLogId() != null){
                        Integer sopStatus = "DELIVRD".equals(vo.getStat()) ? 2 : 3;
                        Date sopSendTime = null;
                        if (vo.getTime() != null) {
                            try {
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                sopSendTime = format.parse(vo.getTime());
                            } catch (Exception ignored) { }
                        }
                        updateQwSopSmsLogsByUuid(logs.getSopSmsLogId(), sopStatus, sopSendTime, null,logs.getSmsIndex());
                    }

                    CompanySmsCommonLogs commonLogs = smsCommonLogsService.selectCompanySmsCommonLogsByMid(vo.getMid());
                    if (commonLogs != null && commonLogs.getStatus().equals(0)) {
                        commonLogs.setStat(vo.getStat());
                        if (vo.getTime() != null) {
                            try {
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                commonLogs.setSendTime(format.parse(vo.getTime()));
                            } catch (Exception e) {

                            }
                        }
                        //状态报告
                        if (vo.getStat().equals("DELIVRD")) {
                            commonLogs.setStatus(1);
                        } else {
                            commonLogs.setStatus(-1);
                            companySmsService.addCompanySms(commonLogs.getCompanyId(), commonLogs.getNumber());
                        }
                        smsCommonLogsService.updateCompanySmsCommonLogs(commonLogs);

                    }
                }
            }
        }
        return "OK";
    }
    @Override
    @Synchronized
    public R sendUserSms(String phone,String UserName,String code) {
        CompanySmsTemp temp = smsTempService.selectCompanySmsTempByCode(code);
        if (temp==null){
            return R.error("没有模板");
        }
        String content = temp.getContent();
        if(StringUtils.isNotEmpty(UserName)){
                content=content.replace("${sms.csName}",UserName);
        }
            String urls= null;
            SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.sms");
            FsSmsConfig sms = JSON.parseObject(sysConfig.getConfigValue(), FsSmsConfig.class);
            if (sms.getType().equals("rf")){
                try {
                    if(temp.getTempType().equals(1)){
                        urls = sms.getRfUrl1()+"sms?action=send&account="+sms.getRfAccount1()+"&password="+sms.getRfPassword1()+"&mobile="+phone+"&content="+ URLEncoder.encode(sms.getRfSign()+content, "UTF-8")+"&extno="+sms.getRfCode1()+"&rt=json";
                    }
                    else if(temp.getTempType().equals(2)){
                        urls = sms.getRfUrl2()+"sms?action=send&account="+sms.getRfAccount2()+"&password="+sms.getRfPassword2()+"&mobile="+phone+"&content="+ URLEncoder.encode(sms.getRfSign()+content+"拒收请回复R", "UTF-8")+"&extno="+sms.getRfCode2()+"&rt=json";
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String post = HttpRequest.get(urls)
                        .execute().body();
                SmsSendVO vo=JSONUtil.toBean(post, SmsSendVO.class);
                if(vo.getStatus().equals(0)){
                    for(SmsSendItemVO itemVO:vo.getList()){
                        if(itemVO.getResult().equals("0")){
                            CompanySmsLogs logs=new CompanySmsLogs();
                            logs.setContent(content);
                            logs.setTempCode(temp.getTempCode());
                            logs.setTempId(temp.getTempId());
                            logs.setPhone(phone);
                            logs.setSendTime(new Date());
                            logs.setStatus(0);
                            logs.setType(sms.getType());
                            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);
                        }
                    }
                }
            }else if (sms.getType().equals("dh")){
                SendSmsReturn sendSmsReturn =null;
                if(temp.getTempType().equals(1)){
                    sendSmsReturn = smsTService.sendSms(sms.getDhAccount1(), sms.getDhPassword1(), content, phone);
                }
                else if(temp.getTempType().equals(2)){
                    sendSmsReturn=  smsTService.sendSms(sms.getDhAccount2(),sms.getDhPassword2(),content+"拒收请回复R",phone);
                }
                if (sendSmsReturn!=null){
                    if (sendSmsReturn.getResult()!=null&&sendSmsReturn.getResult().equals("0")){
                        CompanySmsLogs logs=new CompanySmsLogs();
                        logs.setContent(content);
                        logs.setTempCode(temp.getTempCode());
                        logs.setTempId(temp.getTempId());
                        logs.setPhone(phone);
                        logs.setSendTime(new Date());
                        logs.setStatus(0);
                        logs.setType(sms.getType());
                        logs.setMid(sendSmsReturn.getMsgid());
                        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);
                    }
                }
            }



        return R.ok();
        }

    @Override
    public R sendOrderMsg(SmsSendUserParam param) {
        CompanySmsTemp temp=smsTempService.selectCompanySmsTempByCode(param.getTempCode());
        if(temp!=null&&temp.getStatus().equals(1)&&temp.getIsAudit().equals(1)){
            CompanySms csms=companySmsService.selectCompanySmsByCompanyId(param.getCompanyId());
            if(csms!=null){
                if(csms.getRemainSmsCount()>0){

                    CompanyUser companyUser=companyUserService.selectCompanyUserById(param.getCompanyUserId());
                    FsStoreOrder fsStoreOrder = storeOrderMapper.selectFsStoreOrderByOrderId(param.getOrderId());
                    if (fsStoreOrder==null){
                        return R.error("没有此订单");
                    }
                    if (fsStoreOrder.getUserName()==null||fsStoreOrder.getUserPhone()==null){
                        return R.error("收货人电话有误");
                    }
                    String content="";
                        content=param.getContent();
                        if(StringUtils.isNotEmpty(fsStoreOrder.getUserName())){
                            content=content.replace("${sms.csName}",fsStoreOrder.getUserName());
                        }
                        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;
                        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.sms");
                        FsSmsConfig sms = JSON.parseObject(sysConfig.getConfigValue(), FsSmsConfig.class);
                        if (sms.getType().equals("rf")){
                            try {
                                if(temp.getTempType().equals(1)){
                                    urls = sms.getRfUrl1()+"sms?action=send&account="+sms.getRfAccount1()+"&password="+sms.getRfPassword1()+"&mobile="+fsStoreOrder.getUserPhone()+"&content="+ URLEncoder.encode(sms.getRfSign()+content, "UTF-8")+"&extno="+sms.getRfCode1()+"&rt=json";
                                }
                                else if(temp.getTempType().equals(2)){
                                    urls = sms.getRfUrl2()+"sms?action=send&account="+sms.getRfAccount2()+"&password="+sms.getRfPassword2()+"&mobile="+fsStoreOrder.getUserPhone()+"&content="+ URLEncoder.encode(sms.getRfSign()+content+"拒收请回复R", "UTF-8")+"&extno="+sms.getRfCode2()+"&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)){
                                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(fsStoreOrder.getUserPhone());
                                        logs.setSendTime(new Date());
                                        logs.setStatus(0);
                                        logs.setType(sms.getType());
                                        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());
                                    }
                                }
                            }
                        }else if (sms.getType().equals("dh")){
                            SendSmsReturn sendSmsReturn =null;
                            if(temp.getTempType().equals(1)){
                                sendSmsReturn = smsTService.sendSms(sms.getDhAccount1(), sms.getDhPassword1(), content, fsStoreOrder.getUserPhone());
                            }
                            else if(temp.getTempType().equals(2)){
                                sendSmsReturn=  smsTService.sendSms(sms.getDhAccount2(),sms.getDhPassword2(),content+"拒收请回复R",fsStoreOrder.getUserPhone());
                            }
                            System.out.println(sendSmsReturn);
                            if (sendSmsReturn!=null){
                                if (sendSmsReturn.getResult()!=null&&sendSmsReturn.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(fsStoreOrder.getUserPhone());
                                    logs.setSendTime(new Date());
                                    logs.setStatus(0);
                                    logs.setType(sms.getType());
                                    logs.setMid(sendSmsReturn.getMsgid());
                                    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());
                                }
                            }
                        }

                    return R.ok("短信提交成功，正在发送中...");
                }
                else{
                    return R.error("剩余短信数量不足，请充值");
                }
            }
            else{
                return R.error("请充值");
            }
        }
        else {
            return R.error("模板未审核");
        }
    }

    @Override
    public R sendPackageOrderMsg(SmsSendUserParam param) {
        CompanySmsTemp temp=smsTempService.selectCompanySmsTempByCode(param.getTempCode());
        if(temp!=null&&temp.getStatus().equals(1)&&temp.getIsAudit().equals(1)){
            CompanySms csms=companySmsService.selectCompanySmsByCompanyId(param.getCompanyId());
            if(csms!=null){
                if(csms.getRemainSmsCount()>0){

                    CompanyUser companyUser=companyUserService.selectCompanyUserById(param.getCompanyUserId());
                     FsPackageOrderVO packageOrder = packageOrderMapper.selectFsPackageOrderByOrderIdVO(param.getOrderId());
                    if (packageOrder==null){
                        return R.error("没有此订单");
                    }
                    if (packageOrder.getPhone()==null){
                        return R.error("电话不能为空");
                    }
                    String content="";
                    content=param.getContent();
                    if(StringUtils.isNotEmpty(packageOrder.getPackageName())){
                        content=content.replace("${sms.csName}",packageOrder.getPackageName());
                    }
                    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;
                    SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.sms");
                    FsSmsConfig sms = JSON.parseObject(sysConfig.getConfigValue(), FsSmsConfig.class);
                    if (sms.getType().equals("rf")){
                        try {
                            if(temp.getTempType().equals(1)){
                                urls = sms.getRfUrl1()+"sms?action=send&account="+sms.getRfAccount1()+"&password="+sms.getRfPassword1()+"&mobile="+packageOrder.getPhone()+"&content="+ URLEncoder.encode(sms.getRfSign()+content, "UTF-8")+"&extno="+sms.getRfCode1()+"&rt=json";
                            }
                            else if(temp.getTempType().equals(2)){
                                urls = sms.getRfUrl2()+"sms?action=send&account="+sms.getRfAccount2()+"&password="+sms.getRfPassword2()+"&mobile="+packageOrder.getPhone()+"&content="+ URLEncoder.encode(sms.getRfSign()+content+"拒收请回复R", "UTF-8")+"&extno="+sms.getRfCode2()+"&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)){
                            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(packageOrder.getPhone());
                                    logs.setSendTime(new Date());
                                    logs.setStatus(0);
                                    logs.setType(sms.getType());
                                    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());
                                }
                            }
                        }
                    }else if (sms.getType().equals("dh")){
                        SendSmsReturn sendSmsReturn =null;
                        if(temp.getTempType().equals(1)){
                            sendSmsReturn = smsTService.sendSms(sms.getDhAccount1(), sms.getDhPassword1(), content, packageOrder.getPhone());
                        }
                        else if(temp.getTempType().equals(2)){
                            sendSmsReturn=  smsTService.sendSms(sms.getDhAccount2(),sms.getDhPassword2(),content+"拒收请回复R", packageOrder.getPhone());
                        }
                        System.out.println(sendSmsReturn);
                        if (sendSmsReturn!=null){
                            if (sendSmsReturn.getResult()!=null&&sendSmsReturn.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(packageOrder.getPhone());
                                logs.setSendTime(new Date());
                                logs.setStatus(0);
                                logs.setType(sms.getType());
                                logs.setMid(sendSmsReturn.getMsgid());
                                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());
                            }
                        }
                    }
                    return R.ok("短信提交成功，正在发送中...");
                }
                else{
                    return R.error("剩余短信数量不足，请充值");
                }
            }
            else{
                return R.error("请充值");
            }
        }
        else {
            return R.error("模板未审核");
        }
    }

    @Override
    public R sendCaptcha(String phone, String captcha, String code) {
        log.info(captcha);
        CompanySmsTemp temp = smsTempService.selectCompanySmsTempByCode(code);
        if (temp == null) {
            return R.error("没有模板");
        }
        String content = temp.getContent();
        if (StringUtils.isNotEmpty(captcha)) {
            content = content.replace("${sms.captcha}", captcha);
        }
        String urls = null;
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.sms");
        FsSmsConfig sms = JSON.parseObject(sysConfig.getConfigValue(), FsSmsConfig.class);
        if (sms.getType().equals("rf")) {
            try {
                content = content.replace("${sms.sign}",sms.getRfSign());
                urls = sms.getRfUrl1() + "sms?action=send&account=" + sms.getRfAccount1() + "&password=" + sms.getRfPassword1() + "&mobile=" + phone + "&content=" + URLEncoder.encode(content, "UTF-8") + "&extno=" + sms.getRfCode1() + "&rt=json";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String post = HttpRequest.get(urls)
                    .execute().body();
            SmsSendVO vo = JSONUtil.toBean(post, SmsSendVO.class);
            if (vo.getStatus().equals(0)) {
                for (SmsSendItemVO itemVO : vo.getList()) {
                    if (itemVO.getResult().equals("0")) {
                        CompanySmsLogs logs = new CompanySmsLogs();
                        logs.setContent(content);
                        logs.setTempCode(temp.getTempCode());
                        logs.setTempId(temp.getTempId());
                        logs.setPhone(phone);
                        logs.setSendTime(new Date());
                        logs.setStatus(0);
                        logs.setType(sms.getType());
                        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);
                    }
                }
            }
        } else if (sms.getType().equals("dh")) {
            SendSmsReturn sendSmsReturn = null;
            content = content.replace("${sms.sign}",sms.getDhSign());
            sendSmsReturn = smsTService.sendSms(sms.getDhAccount1(), sms.getDhPassword1(), content, phone);
            if (sendSmsReturn != null) {
                if (sendSmsReturn.getResult() != null && sendSmsReturn.getResult().equals("0")) {
                    CompanySmsLogs logs = new CompanySmsLogs();
                    logs.setContent(content);
                    logs.setTempCode(temp.getTempCode());
                    logs.setTempId(temp.getTempId());
                    logs.setPhone(phone);
                    logs.setSendTime(new Date());
                    logs.setStatus(0);
                    logs.setType(sms.getType());
                    logs.setMid(sendSmsReturn.getMsgid());
                    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);
                }
            }
        }


        return R.ok();
    }


    @Override
    public R sendUrl(String phone, String content, String code,Long uuid,Integer smsIndex,String deleteKey,Long companyId,Long companyUserId) {
        log.info("发送短信：{}，链接地址：{}，短信模板：{}", phone, content, code);
        CompanySmsTemp temp = smsTempService.selectCompanySmsTempByCode(code);
        if (temp == null) {
            log.info("{},未找到短信模板：{}", phone, code);
            return R.error("没有模板");
        }
        String urls = null;
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.sms");
        FsSmsConfig sms = JSON.parseObject(sysConfig.getConfigValue(), FsSmsConfig.class);
        if (sms.getType().equals("rf")) {
            try {
//                content = content.replace("${sms.sign}",sms.getRfSign2());
                urls = sms.getRfUrl2() + "sms?action=send&account=" + sms.getRfAccount2() + "&password=" + sms.getRfPassword2() + "&mobile=" + phone + "&content=" + URLEncoder.encode(content, "UTF-8") + "&extno=" + sms.getRfCode2() + "&rt=json";
            } catch (UnsupportedEncodingException e) {
                log.error("{}发送失败", phone, e);
                return R.error("短信发送失败：" + e.getMessage());
            }
            String post = HttpRequest.get(urls)
                    .execute().body();
            SmsSendVO vo = JSONUtil.toBean(post, SmsSendVO.class);
            if (vo.getStatus().equals(0)) {
                for (SmsSendItemVO itemVO : vo.getList()) {
                    if (itemVO.getResult().equals("0")) {
                        CompanySmsLogs logs = new CompanySmsLogs();
                        logs.setContent(content);
                        logs.setTempCode(temp.getTempCode());
                        logs.setTempId(temp.getTempId());
                        logs.setPhone(phone);
                        logs.setSendTime(new Date());
                        logs.setStatus(0);
                        logs.setType(sms.getType());
                        logs.setMid(itemVO.getMid());
                        logs.setCompanyId(companyId);
                        logs.setCompanyUserId(companyUserId);
                        if (uuid != null) {
                            logs.setSopSmsLogId(uuid);
                        }
                        if (smsIndex != null) {
                            logs.setSmsIndex(smsIndex);
                        }
                        int 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);
                    }else{
                        log.info("{}不发送短信-itemVO.getResult().equals(\"0\")：{}", phone, itemVO);
                    }
                }
            }else{
                log.info("{}不发送短信-vo.getStatus().equals(0)：{}", phone, vo.getStatus());

                return R.error("发送短信失败！");
            }
        } else if (sms.getType().equals("dh")) {
            SendSmsReturn sendSmsReturn = null;
            content = content.replace("${sms.sign}",sms.getDhSign());
            sendSmsReturn = smsTService.sendSms(sms.getDhAccount1(), sms.getDhPassword1(), content, phone);
            if (sendSmsReturn != null) {
                if (sendSmsReturn.getResult() != null && sendSmsReturn.getResult().equals("0")) {
                    CompanySmsLogs logs = new CompanySmsLogs();
                    logs.setContent(content);
                    logs.setTempCode(temp.getTempCode());
                    logs.setTempId(temp.getTempId());
                    logs.setPhone(phone);
                    logs.setSendTime(new Date());
                    logs.setStatus(0);
                    logs.setType(sms.getType());
                    logs.setMid(sendSmsReturn.getMsgid());
                    if (uuid != null) {
                        logs.setSopSmsLogId(uuid);
                    }
                    if (smsIndex != null) {
                        logs.setSmsIndex(smsIndex);
                    }
                    int 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);
                }else{
                    log.info("{}不发送短信-sendSmsReturn.getResult() != null && sendSmsReturn.getResult().equals(\"0\")：{}", phone, sendSmsReturn);
                }
            }else{
                log.info("{}不发送短信-sendSmsReturn != null", phone);
            }
        }
        //删除redis缓存
        if(StringUtils.isNotEmpty(deleteKey)){
            redisCache.deleteObject(deleteKey);
        }
        return R.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());
            }
            if(StringUtils.isNotEmpty(param.getSenderName())){
                content=content.replace("${sms.senderName}",param.getSenderName());
            }

            String urls= null;
            // 通知类的不加 退订回T 只有营销类的加
            //最多500个手机号
            SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.sms");
            FsSmsConfig sms = JSON.parseObject(sysConfig.getConfigValue(), FsSmsConfig.class);
            if (sms.getType().equals("rf")){
                try {
                    if(temp.getTempType().equals(1)){
                        urls = sms.getRfUrl1()+"sms?action=send&account="+sms.getRfAccount1()+"&password="+sms.getRfPassword1()+"&mobile="+crmCustomer.getMobile()+"&content="+ URLEncoder.encode(sms.getRfSign()+content, "UTF-8")+"&extno="+sms.getRfCode1()+"&rt=json";
                    }
                    else if(temp.getTempType().equals(2)){
                        urls = sms.getRfUrl2()+"sms?action=send&account="+sms.getRfAccount2()+"&password="+sms.getRfPassword2()+"&mobile="+crmCustomer.getMobile()+"&content="+ URLEncoder.encode(sms.getRfSign()+content+"拒收请回复R", "UTF-8")+"&extno="+sms.getRfCode2()+"&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.setType(sms.getType());
                            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++;
                        }
                    }
                }
            }else if (sms.getType().equals("dh")){
                SendSmsReturn sendSmsReturn =null;
                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.setType(sms.getType());
                Integer counts=logs.getContent().length()/67;
                if(logs.getContent().length()%67>0){
                    counts=counts+1;
                }
                if(counts==0){
                    counts=1;
                }
                logs.setNumber(counts);
                if(temp.getTempType().equals(1)){
                    sendSmsReturn = smsTService.sendSms(sms.getDhAccount1(), sms.getDhPassword1(), content, crmCustomer.getMobile());
                }
                else if(temp.getTempType().equals(2)){
                    sendSmsReturn=  smsTService.sendSms(sms.getDhAccount2(),sms.getDhPassword2(),content+"拒收请回复R",crmCustomer.getMobile());
                }
                System.out.println(sendSmsReturn);
                if (sendSmsReturn!=null){
                    if (sendSmsReturn.getResult()!=null&&sendSmsReturn.getResult().equals("0")){
                        logs.setMid(sendSmsReturn.getMsgid());
                        smsLogsService.insertCompanySmsLogs(logs);
                        companySmsService.subCompanySms(logs.getCompanyId(),logs.getNumber());
                    }
                }
            }




        }
    }

    private static ConcurrentHashMap<Long, Object> smsCompanyLock = new ConcurrentHashMap();

    /**
     * copy一份 batchSmsOp
     * @param temp
     * @param param
     */
//    @Async
    public void batchSmsOp4AiSend(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());
            }
            if(StringUtils.isNotEmpty(param.getSenderName())){
                content=content.replace("${sms.senderName}",param.getSenderName());
            }

            String urls= null;
            // 通知类的不加 退订回T 只有营销类的加
            //最多500个手机号
            SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.sms");
            FsSmsConfig sms = JSON.parseObject(sysConfig.getConfigValue(), FsSmsConfig.class);
            if (sms.getType().equals("rf")){
                try {
                    if(temp.getTempType().equals(1)){
                        urls = sms.getRfUrl1()+"sms?action=send&account="+sms.getRfAccount1()+"&password="+sms.getRfPassword1()+"&mobile="+crmCustomer.getMobile()+"&content="+ URLEncoder.encode(sms.getRfSign()+content, "UTF-8")+"&extno="+sms.getRfCode1()+"&rt=json";
                    }
                    else if(temp.getTempType().equals(2)){
                        urls = sms.getRfUrl2()+"sms?action=send&account="+sms.getRfAccount2()+"&password="+sms.getRfPassword2()+"&mobile="+crmCustomer.getMobile()+"&content="+ URLEncoder.encode(sms.getRfSign()+content+"拒收请回复R", "UTF-8")+"&extno="+sms.getRfCode2()+"&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.setType(sms.getType());
                            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);
                            Object lock = smsCompanyLock.computeIfAbsent(logs.getCompanyId(), k -> new Object());
                            //任务调用时可能存在并发情况 这里优化一下扣减时条数准确
                            synchronized (lock) {
                                companySmsService.subCompanySms(logs.getCompanyId(), logs.getNumber());
                            }
//                            companySmsService.subCompanySms(logs.getCompanyId(),logs.getNumber());
                            resultCount++;
                        }
                    }
                }
            }else if (sms.getType().equals("dh")){
                SendSmsReturn sendSmsReturn =null;
                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.setType(sms.getType());
                Integer counts=logs.getContent().length()/67;
                if(logs.getContent().length()%67>0){
                    counts=counts+1;
                }
                if(counts==0){
                    counts=1;
                }
                logs.setNumber(counts);
                if(temp.getTempType().equals(1)){
                    sendSmsReturn = smsTService.sendSms(sms.getDhAccount1(), sms.getDhPassword1(), content, crmCustomer.getMobile());
                }
                else if(temp.getTempType().equals(2)){
                    sendSmsReturn=  smsTService.sendSms(sms.getDhAccount2(),sms.getDhPassword2(),content+"拒收请回复R",crmCustomer.getMobile());
                }
                System.out.println(sendSmsReturn);
                if (sendSmsReturn!=null){
                    if (sendSmsReturn.getResult()!=null&&sendSmsReturn.getResult().equals("0")){
                        logs.setMid(sendSmsReturn.getMsgid());
                        smsLogsService.insertCompanySmsLogs(logs);
//                        companySmsService.subCompanySms(logs.getCompanyId(),logs.getNumber());
                        Object lock = smsCompanyLock.computeIfAbsent(logs.getCompanyId(), k -> new Object());
                        synchronized (lock) {
                            companySmsService.subCompanySms(logs.getCompanyId(), logs.getNumber());
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据 uuid（QwSopSmsLogs.id）和索引更新子记录，并检查主记录完成状态
     */
    private void updateQwSopSmsLogsByUuid(Long sopSmsLogId, Integer status, Date sendTime, String replyContent, Integer smsIndex) {
        if (sopSmsLogId == null) return;
        QwSopSmsLogs update = new QwSopSmsLogs();
        update.setSopLogId(sopSmsLogId);
        update.setSmsIndex(smsIndex);
        if (status != null) {
            update.setStatus(status);
        }
        if (sendTime != null) {
            update.setSendTime(sendTime);
        }
        if (replyContent != null) {
            update.setRemark(replyContent);
        }

        qwSopSmsLogsService.updateSmsNotifyInfo(update);
        QwSopLogs mainLog = qwSopLogsMapper.selectoneByUid(sopSmsLogId);
        if (mainLog == null) return;
        JSONObject jsonObject = JSONObject.parseObject(mainLog.getContentJson());
        JSONArray jsonArray = jsonObject.getJSONArray("setting");
        int total = jsonArray.size();

        Integer processed = qwSopSmsLogsMapper.countProcessed(sopSmsLogId);

        if (processed != null && processed >= total) {
            int successCount = 0;
            int failCount = 0;

            List<QwSopSmsLogs> list = qwSopSmsLogsMapper.getSmsListBySopLogId(sopSmsLogId);
            //更新对应content_json信息
            JSONArray newArray = new JSONArray();
            for (QwSopSmsLogs sub : list) {
                JSONObject json = jsonArray.getJSONObject(sub.getSmsIndex());
                if (sub.getStatus() == 2) {
                    json.put("sendStatus","1");
                    successCount++;
                } else if (sub.getStatus() == 3) {
                    json.put("sendStatus","0");
                    failCount++;
                }
                newArray.add(json);
            }

            boolean allSuccess = (successCount == list.size());
            boolean allFail = (failCount == list.size());

            QwSopLogs updateLog = new QwSopLogs();
            updateLog.setSmsLogsId(sopSmsLogId);
            jsonObject.put("setting", newArray);
            updateLog.setContentJson(jsonObject.toJSONString());
            if (allSuccess) {
                updateLog.setSendStatus(1L);
                updateLog.setReceivingStatus(1L);//已接收
                log.info("主记录 {} 全部成功", sopSmsLogId);
            } else if (allFail) {
                updateLog.setSendStatus(0L);
                log.info("主记录 {} 全部失败", sopSmsLogId);
            } else {
                updateLog.setRemark("部分成功！");
                updateLog.setSendStatus(0L); // 部分成功
                log.info("主记录 {} 部分成功（成功{}条，失败{}条）",
                        sopSmsLogId, successCount, failCount);
            }


            qwSopLogsMapper.updateQwSopLogsBySmsLogsId(updateLog);
        }
    }

}
