package com.jeequan.jeepay.mgr.ctrl.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeequan.jeepay.bizcommons.manage.sms.SmsManager;
import com.jeequan.jeepay.components.mq.model.ResetAppConfigMQ;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.core.utils.StringKit;
import com.jeequan.jeepay.db.entity.SysConfig;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 系统配置信息类
 *
 * @author pangxiaoyu
 *
 * @date 2021-06-07 07:15
 */
@Slf4j
@RestController
@RequestMapping("api/sysConfigs")
public class SysConfigController extends CommonCtrl {

	@Autowired private SysConfigService sysConfigService;
	@Autowired private IMQSender mqSender;
	@Autowired private SmsManager smsManager;


	/**
	 * @author: pangxiaoyu
	 * @date: 2021/6/7 16:19
	 * @describe: 分组下的配置
	 */
	@PreAuthorize("hasAnyAuthority('ENT_SYS_CONFIG_INFO', 'ENT_SYS_CONFIG_VIEW', 'ENT_PUSH_CONFIG_VIEW')")
    @GetMapping(value = "/{groupKey}")
	public ApiRes getConfigs(@PathVariable("groupKey") String groupKey) {
		LambdaQueryWrapper<SysConfig> condition = SysConfig.gw();
		condition.orderByAsc(SysConfig::getSortNum);
		if(StringUtils.isNotEmpty(groupKey)){
			condition.eq(SysConfig::getGroupKey, groupKey);
		}
		List<SysConfig> configList = sysConfigService.list(condition);

		// 数据脱敏
		this.autoDesen(configList);

		//返回数据
		return ApiRes.ok(configList);
	}

	/**
	 * @author: pangxiaoyu
	 * @date: 2021/6/7 16:19
	 * @describe: 系统配置修改
	 */
	@PreAuthorize("hasAnyAuthority('ENT_SYS_CONFIG_EDIT', 'ENT_PUSH_CONFIG_EDIT')")
	@MethodLog(remark = "系统配置修改")
	@RequestMapping(value="/{groupKey}", method = RequestMethod.PUT)
	public ApiRes update(@PathVariable("groupKey") String groupKey) {
		JSONObject paramJSON = getReqParamJSON();
		Map<String, String> updateMap = new HashMap<>();
		if ("smsConfig".equals(groupKey)) {

			// 1. 选择厂商
			updateMap.put("smsProvideKey", paramJSON.getString("smsProvideKey"));

			// 合并
			if(StringUtils.isNotEmpty(paramJSON.getString("aliyundySmsConfigValue"))){
				updateMap.put("aliyundySmsConfigValue", StringKit.marge(sysConfigService.getById("aliyundySmsConfigValue").getConfigVal(), paramJSON.getString("aliyundySmsConfigValue"), null));
			}
			if(StringUtils.isNotEmpty(paramJSON.getString("jeepaydxSmsConfigValue"))){
				updateMap.put("jeepaydxSmsConfigValue", StringKit.marge(sysConfigService.getById("jeepaydxSmsConfigValue").getConfigVal(), paramJSON.getString("jeepaydxSmsConfigValue"), null));
			}

			if(StringUtils.isNotEmpty(paramJSON.getString("juhedxSmsConfigValue"))){
				updateMap.put("juhedxSmsConfigValue", StringKit.marge(sysConfigService.getById("juhedxSmsConfigValue").getConfigVal(), paramJSON.getString("juhedxSmsConfigValue"), null));
			}

			if(StringUtils.isNotEmpty(paramJSON.getString("mocktestSmsConfigValue"))){
				// 没有需要加密的数据
				updateMap.put("mocktestSmsConfigValue", paramJSON.getString("mocktestSmsConfigValue"));
			}


		}else if ("ossConfig".equals(groupKey)) {

			// 合并
			updateMap.put("aliyunOssConfig", StringKit.marge(sysConfigService.getById("aliyunOssConfig").getConfigVal(), paramJSON.getString("aliyunOssConfig"), null));
			updateMap.put("ossUseType", paramJSON.getString("ossUseType"));
			updateMap.put("ossPublicSiteUrl", paramJSON.getString("ossPublicSiteUrl"));

		}else if ("oemConfig".equals(groupKey)) {
			paramJSON.put("mgr", paramJSON.getJSONObject("mgr"));
			paramJSON.put("mch", paramJSON.getJSONObject("mch"));
			paramJSON.put("agent", paramJSON.getJSONObject("agent"));
			paramJSON.put("reportIcp", paramJSON.getJSONObject("reportIcp"));
			paramJSON.put("reportGa", paramJSON.getJSONObject("reportGa"));
			paramJSON.put("reportJh", paramJSON.getJSONObject("reportJh"));
			paramJSON.put("reportDx", paramJSON.getJSONObject("reportDx"));
			paramJSON.put("copyrightInfo", paramJSON.getJSONObject("copyrightInfo"));
			updateMap.put("oemConfig", paramJSON.toJSONString());

		}else if ("defaultConfig".equals(groupKey)) {

			updateMap = JSONObject.toJavaObject(paramJSON, Map.class);

			// 处理 密码格式  解密 + 保存为DB格式,
			if(StringUtils.isNotEmpty(updateMap.get("defaultPassword") ) ) {

				// 20220406改为  encode格式，可以解密（通知短信需要查看密码原文）
//				String defaultPassword = new BCryptPasswordEncoder().encode(Base64.decodeStr(getValStringRequired("defaultPassword")));
//				updateMap.put("defaultPassword", defaultPassword);

			}else{
				updateMap.remove("defaultPassword");
			}

		}else if ("paymentConfig".equals(groupKey)) {
			updateMap.put("paymentConfig", paramJSON.toJSONString());
		}else {
			Map<String, String> map = JSONObject.toJavaObject(paramJSON, Map.class);

			for (String key : map.keySet()) {
				// 脱敏数据 && 记录为空 = 不更新
				if(desenKeys.contains(key) && StringUtils.isEmpty(map.get(key))){
					continue;
				}
				updateMap.put(key, map.get(key));
			}
		}
		int update = sysConfigService.updateByConfigKey(updateMap);
		if(update <= 0) {
            return ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR, "更新失败");
        }

		// 异步更新到MQ
		SpringBeansUtil.getBean(SysConfigController.class).updateSysConfigMQ(groupKey);

		return ApiRes.ok();
	}

	@Async
	public void updateSysConfigMQ(String groupKey){
		mqSender.send(ResetAppConfigMQ.build(groupKey));
	}


	/** 过滤脱敏数据 */
	private void autoDesen(List<SysConfig> sysConfigList){

		if(sysConfigList == null){
			return;
		}

		for (SysConfig sysConfig : sysConfigList) {
			if (desenKeys.contains(sysConfig.getConfigKey())){
				sysConfig.addExt("configValDesen", StringKit.autoDesensitization(sysConfig.getConfigVal()));
				sysConfig.setConfigVal(null);
			}

			// 短信配置 特殊处理
			if("aliyundySmsConfigValue".equals(sysConfig.getConfigKey())){
				JSONObject jsonObject = JSON.parseObject(sysConfig.getConfigVal());
				jsonObject.put("accessKeySecret", StringKit.autoDesensitization(jsonObject.getString("accessKeySecret")));

				// 原始文件删除配置项，  在外层增加加密脱敏数据。
				sysConfig.addExt("configValDesen", jsonObject.toJSONString());
				jsonObject.remove("accessKeySecret");
				sysConfig.setConfigVal(jsonObject.toJSONString());

			}// 计全短信 特殊处理
			if("jeepaydxSmsConfigValue".equals(sysConfig.getConfigKey())){
				JSONObject jsonObject = JSON.parseObject(sysConfig.getConfigVal());
				jsonObject.put("accountPwd", StringKit.autoDesensitization(jsonObject.getString("accountPwd")));

				// 原始文件删除配置项，  在外层增加加密脱敏数据。
				sysConfig.addExt("configValDesen", jsonObject.toJSONString());
				jsonObject.remove("accountPwd");
				sysConfig.setConfigVal(jsonObject.toJSONString());

			}else if("aliyunOssConfig".equals(sysConfig.getConfigKey())){ // OSS 特殊处理

				JSONObject jsonObject = JSON.parseObject(sysConfig.getConfigVal());
				jsonObject.put("accessKeySecret", StringKit.autoDesensitization(jsonObject.getString("accessKeySecret")));

				// 原始文件删除配置项，  在外层增加加密脱敏数据。
				sysConfig.addExt("configValDesen", jsonObject.toJSONString());
				jsonObject.remove("accessKeySecret");
				sysConfig.setConfigVal(jsonObject.toJSONString());
			}else if(SysConfigService.PAYMENT_CONFIG.left.equals(sysConfig.getConfigKey())){

				JSONObject jsonObject = JSON.parseObject(sysConfig.getConfigVal());
				jsonObject.put("secret", StringKit.autoDesensitization(jsonObject.getString("secret")));
				// 原始文件删除配置项，  在外层增加加密脱敏数据。
				sysConfig.addExt("configValDesen", jsonObject.toJSONString());
//				jsonObject.remove("secret");
				sysConfig.setConfigVal(jsonObject.toJSONString());
			}
		}

	}

	// 脱敏key
	private static final Set<String> desenKeys = new HashSet<>();
	static{
		desenKeys.add("uniPushMasterSecret"); //app推送 ： uniPush_masterSecret
		desenKeys.add("baiduBceAppSecret"); // 百度语音配置
		desenKeys.add("wxAppSecret"); // 微信公众号消息配置 微信公众号AppSecret


		desenKeys.add("apiMapWebSecret"); //高德地图配置
		desenKeys.add("tencentSecretKey"); // 腾讯OCR
		desenKeys.add("aliAccessKeySecret"); // 阿里 OCR
		desenKeys.add("platformApiSecret"); // 平台通信秘钥

		desenKeys.add("secret");
	}

	/**
	 * @author: yr
	 * @date: 2023/8/18 15:19
	 * @describe: 获取短信余额
	 */
	@PreAuthorize("hasAnyAuthority('ENT_SYS_CONFIG_INFO', 'ENT_SYS_CONFIG_VIEW', 'ENT_PUSH_CONFIG_VIEW')")
	@RequestMapping(value="/smsBalance", method = RequestMethod.GET)
	public ApiRes getSmsBalance() {
		String bizQueryType = getValString("bizQueryType");
		return ApiRes.ok(smsManager.querySmsInfo(bizQueryType));
	}

}
