package com.gxwebsoft.common.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.annotation.IgnoreTenant;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.Setting;
import com.gxwebsoft.common.system.mapper.SettingMapper;
import com.gxwebsoft.common.system.param.SettingParam;
import com.gxwebsoft.common.system.service.SettingService;
import com.gxwebsoft.cms.entity.CmsWebsiteField;
import com.gxwebsoft.cms.service.CmsWebsiteFieldService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统设置Service实现
 *
 * @author WebSoft
 * @since 2022-11-19 13:54:27
 */
@Service
public class SettingServiceImpl extends ServiceImpl<SettingMapper, Setting> implements SettingService {
    // 本地缓存
    public static Map<String, Config> configMap = new HashMap<>();
    public static JsapiService service = null;
    public static Config config = null;
    @Resource
    private ConfigProperties pathConfig;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CmsWebsiteFieldService cmsWebsiteFieldService;

    @Value("${spring.profiles.active:prod}")
    private String activeProfile;
  @Autowired
  private SettingService settingService;

  @Override
    public PageResult<Setting> pageRel(SettingParam param) {
        PageParam<Setting, SettingParam> page = new PageParam<>(param);
        //page.setDefaultOrder("create_time desc");
        List<Setting> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<Setting> listRel(SettingParam param) {
        List<Setting> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<Setting, SettingParam> page = new PageParam<>();
        //page.setDefaultOrder("create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public Setting getByIdRel(Integer settingId) {
        SettingParam param = new SettingParam();
        param.setSettingId(settingId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public JSONObject getBySettingKey(String key, Integer tenantId) {
      System.out.println("tenantId = " + tenantId);
      final JSONObject settingKey = settingService.getBySettingKey("setting_key", tenantId);
      System.out.println("settingKey = " + settingKey);
      Setting setting = this.getOne(new QueryWrapper<Setting>().eq("setting_key", key), false);
      System.out.println("setting1 = " + setting);
      if(setting == null){
        if ("mp-weixin".equals(key)) {
          throw new BusinessException("小程序未配置1");
        }
        if ("payment".equals(key)) {
          throw new BusinessException("支付未配置");
        }
        if ("sms".equals(key)) {
          throw new BusinessException("短信未配置");
        }
        if ("wx-work".equals(key)){
          throw new BusinessException("企业微信未配置");
        }
        if ("setting".equals(key)) {
          throw new BusinessException("基本信息未配置");
        }
        if ("wx-official".equals(key)) {
          throw new BusinessException("微信公众号未配置");
        }
        if ("printer".equals(key)) {
          throw new BusinessException("打印机未配置");
        }
      }
      return JSON.parseObject(setting.getContent());
    }

    @Override
    @IgnoreTenant("跨租户获取指定租户的设置配置")
    public JSONObject getBySettingKeyIgnoreTenant(String key, Integer tenantId) {
        throw new BusinessException("此方法已废弃，请使用缓存方式获取配置：mp-weixin:" + tenantId);
    }

    @Override
    public Setting getData(String settingKey) {
      return query().eq("setting_key", settingKey).one();
    }

    @Override
    public JSONObject getCache(String key) {
      final String cache = stringRedisTemplate.opsForValue().get(key);
      final JSONObject jsonObject = JSONObject.parseObject(cache);
      if(jsonObject == null){
        throw new BusinessException("域名未配置");
      }
      return jsonObject;
    }

    @Override
    public void initConfig(Setting data) {
      if (data.getSettingKey().equals("payment")) {
        final JSONObject jsonObject = JSONObject.parseObject(data.getContent());
        final String mchId = jsonObject.getString("mchId");
        final String apiclientKey = jsonObject.getString("apiclientKey");
        final String privateKey = pathConfig.getUploadPath().concat(apiclientKey);
        final String apiclientCert = pathConfig.getUploadPath().concat(jsonObject.getString("apiclientCert"));
        final String merchantSerialNumber = jsonObject.getString("merchantSerialNumber");
        final String apiV3key = jsonObject.getString("wechatApiKey");
        if(config == null){
          // 根据环境选择不同的证书路径配置
          if ("dev".equals(activeProfile)) {
            // 开发环境：使用配置文件的upload-path拼接证书路径 - 租户ID 10550
            System.out.println("=== 开发环境：使用配置文件upload-path拼接证书路径 ===");
            String uploadPath = pathConfig.getUploadPath(); // 获取配置的upload-path
            String tenantId = "10550"; // 租户ID
            String certBasePath = uploadPath + "dev/wechat/" + tenantId + "/";
            String devPrivateKeyPath = certBasePath + "apiclient_key.pem";
            String devCertPath = certBasePath + "apiclient_cert.pem";

            System.out.println("配置的upload-path: " + uploadPath);
            System.out.println("证书基础路径: " + certBasePath);
            System.out.println("私钥文件路径: " + devPrivateKeyPath);
            System.out.println("证书文件路径: " + devCertPath);

            config = new RSAConfig.Builder()
              .merchantId("1246610101")
              .privateKeyFromPath(devPrivateKeyPath)
              .merchantSerialNumber("2903B872D5CA36E525FAEC37AEDB22E54ECDE7B7")
              .wechatPayCertificatesFromPath(devCertPath)
              .build();
            System.out.println("开发环境证书路径配置完成");
          } else {
            // 生产环境：使用数据库存储的路径
            System.out.println("=== 生产环境：使用数据库存储的证书路径 ===");
            config = new RSAConfig.Builder()
              .merchantId(mchId)
              .privateKeyFromPath(privateKey)
              .merchantSerialNumber(merchantSerialNumber)
              .wechatPayCertificatesFromPath(apiclientCert)
              .build();
            System.out.println("生产环境证书路径: " + privateKey);
          }
          configMap.put(data.getTenantId().toString(),config);
          System.out.println("当前环境: " + activeProfile);
          System.out.println("config = " + config);
        }
        if (service == null) {
          service = new JsapiService.Builder().config(config).build();
        }
      }
    }

    @Override
    public Config getConfig(Integer tenantId) {
      if(configMap.get(tenantId.toString()) == null){
        final Setting payment = getOne(new LambdaQueryWrapper<Setting>().eq(Setting::getSettingKey, "payment"));
        this.initConfig(payment);
        return configMap.get(tenantId.toString());
      }
      return configMap.get(tenantId.toString());
    }

}
