package com.fs.company.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.vo.SmsSendItemVO;
import com.fs.common.vo.SmsSendVO;
import com.fs.company.domain.CompanySms;
import com.fs.company.domain.CompanySmsCommonLogs;
import com.fs.company.domain.CompanySmsTemp;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanySmsCommonLogsMapper;
import com.fs.company.param.CompanyDetectionPhoneSendLinkParam;
import com.fs.company.param.SmsSendFsUserParam;
import com.fs.company.service.ICompanySmsCommonLogsService;
import com.fs.company.service.ICompanySmsService;
import com.fs.company.service.ICompanySmsTempService;
import com.fs.company.service.ICompanyUserService;
import com.fs.his.config.FsSmsConfig;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import com.fs.his.utils.PhoneUtil;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 短信通用发送记录Service业务层处理
 * 
 * @author fs
 * @date 2025-12-17
 */
@Slf4j
@Service
public class CompanySmsCommonLogsServiceImpl extends ServiceImpl<CompanySmsCommonLogsMapper, CompanySmsCommonLogs> implements ICompanySmsCommonLogsService {

    @Autowired
    private ICompanySmsTempService smsTempService;
    @Autowired
    private SmsTServiceImpl smsTService;
    @Autowired
    private ICompanySmsService companySmsService;
    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    SysConfigMapper sysConfigMapper;
    @Autowired
    private IFsUserService fsUserService;
    @Autowired
    private CompanyDetectionPhoneRecordServiceImpl companyDetectionPhoneRecordService;

    /**
     * 查询短信通用发送记录
     * 
     * @param logsId 短信通用发送记录主键
     * @return 短信通用发送记录
     */
    @Override
    public CompanySmsCommonLogs selectCompanySmsCommonLogsByLogsId(Long logsId)
    {
        return baseMapper.selectCompanySmsCommonLogsByLogsId(logsId);
    }

    /**
     * 查询短信通用发送记录列表
     * 
     * @param companySmsCommonLogs 短信通用发送记录
     * @return 短信通用发送记录
     */
    @Override
    public List<CompanySmsCommonLogs> selectCompanySmsCommonLogsList(CompanySmsCommonLogs companySmsCommonLogs)
    {
        return baseMapper.selectCompanySmsCommonLogsList(companySmsCommonLogs);
    }

    /**
     * 新增短信通用发送记录
     * 
     * @param companySmsCommonLogs 短信通用发送记录
     * @return 结果
     */
    @Override
    public int insertCompanySmsCommonLogs(CompanySmsCommonLogs companySmsCommonLogs)
    {
        companySmsCommonLogs.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertCompanySmsCommonLogs(companySmsCommonLogs);
    }

    /**
     * 修改短信通用发送记录
     * 
     * @param companySmsCommonLogs 短信通用发送记录
     * @return 结果
     */
    @Override
    public int updateCompanySmsCommonLogs(CompanySmsCommonLogs companySmsCommonLogs)
    {
        return baseMapper.updateCompanySmsCommonLogs(companySmsCommonLogs);
    }

    /**
     * 批量删除短信通用发送记录
     * 
     * @param logsIds 需要删除的短信通用发送记录主键
     * @return 结果
     */
    @Override
    public int deleteCompanySmsCommonLogsByLogsIds(Long[] logsIds)
    {
        return baseMapper.deleteCompanySmsCommonLogsByLogsIds(logsIds);
    }

    /**
     * 删除短信通用发送记录信息
     * 
     * @param logsId 短信通用发送记录主键
     * @return 结果
     */
    @Override
    public int deleteCompanySmsCommonLogsByLogsId(Long logsId)
    {
        return baseMapper.deleteCompanySmsCommonLogsByLogsId(logsId);
    }

    @Override
    public R sendUserDownloadAppMsg(SmsSendFsUserParam param) {
        // 获取模板
        CompanySmsTemp temp = smsTempService.selectCompanySmsTempByCode(param.getTempCode());
        if (temp == null || !temp.getStatus().equals(1) || !temp.getIsAudit().equals(1)) {
            R.error("模板未审核");
        }
        // 获取公司短信配置
        CompanySms csms = companySmsService.selectCompanySmsByCompanyId(param.getCompanyId());
        if (csms == null) {
            R.error("请充值");
        }
        if (csms.getRemainSmsCount() <= 0) {
            R.error("剩余短信数量不足，请充值");
        }
        FsUser fsUser = fsUserService.selectFsUserByUserId(param.getUserId());
        if (fsUser == null) {
            return R.error("没有此会员");
        }
        if (fsUser.getPhone() == null) {
            return R.error("电话不能为空");
        }
        String phone = PhoneUtil.decryptPhone(fsUser.getPhone());
        String name = fsUser.getNickName();
        return templateSplicing(phone,name,param,temp,4);
    }

    @Override
    public CompanySmsCommonLogs selectCompanySmsCommonLogsByMid(String msgid) {
        return baseMapper.selectCompanySmsCommonLogsByMid(msgid);
    }

    @Override
    public CompanySmsCommonLogs selectCompanySmsCommonLogsByMobile(String phone) {
        return baseMapper.selectCompanySmsCommonLogsByMobile(phone);
    }

    @Override
    public R batchPushAppLinks(SmsSendFsUserParam param, Long companyId, String companyName, Long companyUserId, String userName) {
        int successCount = 0;
        int failCount = 0;

        for (Long userId : param.getUserIds()) {
            try {
                FsUser fsUser = fsUserService.selectFsUserByUserId(userId);
                if (fsUser == null || fsUser.getPhone() == null) {
                    failCount++;
                    continue;
                }

                String phone = PhoneUtil.decryptPhone(fsUser.getPhone());
                String nickName = fsUser.getNickName();

                CompanyDetectionPhoneSendLinkParam linkParam = CompanyDetectionPhoneSendLinkParam.builder()
                        .userId(userId)
                        .mobile(phone)
                        .nickName(nickName)
                        .build();

                String linkUrl = companyDetectionPhoneRecordService.getDownloadAppLink(
                        linkParam, companyId, companyName, companyUserId, userName);

                if (linkUrl != null && !linkUrl.isEmpty()) {
                    // 设置当前用户ID并发送短信
                    param.setUserId(userId);
                    param.setDownloaAppdUrl(linkUrl);
                    try {
                        sendUserDownloadAppMsg(param);
                        successCount++;
                    }catch (Exception e){
                        failCount++;
                        log.error("为用户 {} 发送短信时发生异常", userName, e);
                    }
                } else {
                    failCount++;
                }
            } catch (Exception e) {
                failCount++;
                log.error("为用户 {} 批量推送APP链接时发生异常", userName, e);
            }
        }
        return R.ok(String.format("批量推送完成，成功: %d，失败: %d", successCount, failCount));
    }



    /**
     * 组装模板短信及发送
     */
    private R templateSplicing(String phone,String name,SmsSendFsUserParam param,CompanySmsTemp temp,Integer sendType){
        CompanyUser companyUser = companyUserService.selectCompanyUserById(param.getCompanyUserId());
        String content;
        content = param.getContent();
        if (StringUtils.isNotEmpty(name)) {
            content = content.replace("${sms.csName}", name);
        }
        if (StringUtils.isNotEmpty(param.getCardUrl())) {
            content = content.replace("${sms.cardUrl}", param.getCardUrl());
        }
        if (companyUser != null && StringUtils.isNotEmpty(companyUser.getPhonenumber())) {
            content = content.replace("${sms.phoneNumber}", companyUser.getPhonenumber());
        }
        if(StringUtils.isNotEmpty(param.getDownloaAppdUrl())){
            content = content.replace("${sms.downloadAppLink}", param.getDownloaAppdUrl());
        }
        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)
//                            .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")) {
                        recordSmsLog(param,temp,content,phone,name,sms,itemVO.getMid(),sendType,companyUser.getUserName());
                    }
                }
            }
        } 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);
            }
            log.info("数据：{}", sendSmsReturn);
            if (sendSmsReturn != null) {
                if (sendSmsReturn.getResult() != null && sendSmsReturn.getResult().equals("0")) {
                    recordSmsLog(param,temp,content,phone,name,sms,sendSmsReturn.getMsgid(),sendType,companyUser.getUserName());
                }
            }
        }
        return R.ok("短信提交成功，正在发送中...");
    }

    /**
     * 记录发送短信日志
     */
    private void recordSmsLog(SmsSendFsUserParam param, CompanySmsTemp temp,String content,String phone,String name,FsSmsConfig sms,String mid,Integer sendType,String companyUserName) {
        CompanySmsCommonLogs logs = new CompanySmsCommonLogs();
        logs.setCompanyId(param.getCompanyId());
        logs.setContent(content);
        logs.setTempCode(temp.getTempCode());
        logs.setCompanyUserId(param.getCompanyUserId());
        logs.setCompanyUserName(companyUserName);
        logs.setTempId(temp.getTempId());

        //=======区别参数
        logs.setRecipientId(param.getUserId());
        logs.setRecipientName(name);
        logs.setSendType(sendType);
        //=======区别参数

        logs.setPhone(phone);
        logs.setSendTime(new Date());
        logs.setStatus(0);
        logs.setType(sms.getType());
        logs.setMid(mid);
        Integer counts = logs.getContent().length() / 67;
        if (logs.getContent().length() % 67 > 0) {
            counts = counts + 1;
        }
        if (counts == 0) {
            counts = 1;
        }
        logs.setNumber(counts);
        logs.setCreateTime(new Date());
        baseMapper.insertCompanySmsCommonLogs(logs);
        companySmsService.subCompanySms(logs.getCompanyId(), logs.getNumber());
    }
}
