package com.jeequan.jeepay.thirdparty.service;

import com.jeequan.jeepay.db.entity.AgentConfig;
import com.jeequan.jeepay.service.impl.AgentConfigService;
import com.jeequan.jeepay.thirdparty.util.ChannelCertConfigKitBean;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SaasConfigService {

    @Autowired
    private AgentConfigService agentConfigService;

    @Autowired
    private ChannelCertConfigKitBean channelCertConfigKitBean;

    @Autowired
    private Configuration configuration;

    /**
     * 代理域名配置
     *
     * @param agentNo            代理商编号
     * @param agentSiteUrl       代理域名链接
     * @param agentSiteCrtUrl    域名SSL证书文件链接
     * @param agentSitePriKeyUrl 域名SSL私钥链接
     * @param mchSiteUrl         商户域名链接
     * @param mchSiteCrtUrl      商户SSL证书文件链接
     * @param mchSitePriKeyUrl   商户SSL私钥链接
     */
    public void siteConfig(
            String agentNo,
            String agentSiteUrl, String agentSiteCrtUrl, String agentSitePriKeyUrl,
            String mchSiteUrl, String mchSiteCrtUrl, String mchSitePriKeyUrl) {

        saveData(agentNo, agentSiteUrl, agentSiteCrtUrl, agentSitePriKeyUrl, "nginx_agent.ftl", "agentSiteUrl", "agentSiteCrtUrl", "agentSitePriKeyUrl");
        saveData(agentNo, mchSiteUrl, mchSiteCrtUrl, mchSitePriKeyUrl, "nginx_mch.ftl", "mchSiteUrl", "mchSiteCrtUrl", "mchSitePriKeyUrl");
    }

    private void saveData(String agentNo, String agentSiteUrl, String agentSiteCrtUrl, String agentSitePriKeyUrl, String nginxFtl, String configKey1, String configKey2, String configKey3) {
        agentSiteUrl = agentSiteUrl.replace("http://", "");
        agentSiteUrl = agentSiteUrl.replace("https://", "");

        AgentConfig exist = agentConfigService.lambdaQuery().eq(AgentConfig::getAgentNo, agentNo)
                .eq(AgentConfig::getConfigKey, configKey1)
                .eq(AgentConfig::getGroupKey, "agentSiteConfig").one();

        File existConfigFile = null;

        if (exist != null && !exist.getConfigVal().equals(agentSiteUrl)) {
            // 链接发生变化，则将需要将以前的文件改名
            existConfigFile = new File("/www/server/panel/vhost/nginx/", exist.getConfigVal() + ".conf");
        }

        // 第一次保存数据

        AgentConfig config = new AgentConfig();
        config.setAgentNo(agentNo);
        config.setConfigKey(configKey1);
        config.setGroupKey("agentSiteConfig");
        config.setConfigVal(agentSiteUrl);
        agentConfigService.saveOrUpdateConfig(config);

        config = new AgentConfig();
        config.setAgentNo(agentNo);
        config.setConfigKey(configKey2);
        config.setGroupKey("agentSiteConfig");
        config.setConfigVal(agentSiteCrtUrl);
        agentConfigService.saveOrUpdateConfig(config);

        config = new AgentConfig();
        config.setAgentNo(agentNo);
        config.setConfigKey(configKey3);
        config.setGroupKey("agentSiteConfig");
        config.setConfigVal(agentSitePriKeyUrl);
        agentConfigService.saveOrUpdateConfig(config);

        String agentSiteCrtPath = channelCertConfigKitBean.getCertFilePath(agentSiteCrtUrl);
        String agentSitePriKeyPath = channelCertConfigKitBean.getCertFilePath(agentSitePriKeyUrl);

        try {
            Template template = configuration.getTemplate(nginxFtl);

            Map<String, Object> param = new HashMap<>();
            param.put("agentSiteUrl", agentSiteUrl);
            param.put("agentSiteCrtPath", agentSiteCrtPath);
            param.put("agentSitePriKeyPath", agentSitePriKeyPath);
            // 将配置文件生成到宝塔的nginx配置目录下
            File configFile = new File("/www/server/panel/vhost/nginx/", agentSiteUrl + ".conf");
            if (!configFile.exists()) {
                File parentFile = configFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                configFile.createNewFile();
            }
            FileWriter sw = new FileWriter(configFile);
            template.process(param, sw);

            // 以前的文件改名
            if (existConfigFile != null && existConfigFile.exists()) {
                String c = existConfigFile.getAbsolutePath();
                // 加个时间戳，防止保存时重复
                File bak = new File(c + "." + System.currentTimeMillis() +".bak");
                existConfigFile.renameTo(bak);
            }
        } catch (Exception e) {
            log.info("生成模板文件异常", e);
        }

        try {
            Runtime.getRuntime().exec("nginx -s reload");
        } catch (Exception e) {
            log.info("刷新nginx配置异常", e);
        }
    }
}
