package com.fs.common.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
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.CompanySms;
import com.fs.company.domain.CompanySmsLogs;
import com.fs.company.domain.CompanySmsTemp;
import com.fs.company.domain.CompanyUser;
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.sms.domain.SendSmsReturn;
import com.fs.sms.service.impl.SmsTServiceImpl;
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;

@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;

    @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) {
        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);
                    }
                }
                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);
                    }
                }
            }
        }
        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
    @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个手机号
            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());
                    }
                }
            }




        }
    }
}
