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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.AgentConfig;
import com.jeequan.jeepay.db.entity.ThirdAuthDataEntity;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.AgentConfigService;
import com.jeequan.jeepay.service.impl.ThirdAuthDataService;
import com.jeequan.jeepay.thirdparty.service.SaasConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 服务商服务商配置管理类
 *
 * @author yr
 *
 * @date 2023-03-30 14:15
 */
@RestController
@RequestMapping("/api/agentConfig")
public class AgentConfigController extends CommonCtrl {

    @Autowired
    private AgentConfigService agentConfigService;

    @Autowired
    private SaasConfigService saasConfigService;

    @Autowired
    private ThirdAuthDataService thirdAuthDataService;

    /**
     * 查询服务商配置
     */
    @PreAuthorize("hasAuthority('ENT_AGENT_CONFIG_PAGE')")
    @GetMapping
    public ApiRes list() {

        String groupKey = getValString("groupKey");
        String configKey = getValString("configKey");

        LambdaQueryWrapper<AgentConfig> queryWrapper = AgentConfig.gw().eq(AgentConfig::getAgentNo, getValStringRequired("agentNo"));
        if (StringUtils.isNotBlank(groupKey)) {
            queryWrapper.eq(AgentConfig::getGroupKey, groupKey);
        }
        if (StringUtils.isNotBlank(configKey)) {
            queryWrapper.eq(AgentConfig::getConfigKey, configKey);
        }
        List<AgentConfig> list = agentConfigService.list(queryWrapper);
        return ApiRes.ok(list);
    }

    /**
     * 根据configKey查询服务商配置
     */
    @PreAuthorize("hasAuthority('ENT_AGENT_CONFIG_PAGE')")
    @GetMapping("/{configKey}")
    public ApiRes get(@PathVariable("configKey") String configKey) {

        AgentConfig agentConfig = agentConfigService.getOne(AgentConfig.gw().eq(AgentConfig::getAgentNo, getValStringRequired("agentNo")).eq(AgentConfig::getConfigKey, configKey));
        return ApiRes.ok(agentConfig);
    }

    /**
     * 批量更新服务商配置信息
     */
    @PreAuthorize("hasAuthority('ENT_AGENT_CONFIG_PAGE')")
    @MethodLog(remark = "批量更新服务商配置信息")
    @PutMapping("/{groupKey}")
    public ApiRes updateBatch(@PathVariable("groupKey") String groupKey) {

        String params = getValStringRequired("configData");

        List<AgentConfig> agentConfigList = JSONArray.parseArray(params, AgentConfig.class);
        // 判断是否需要同步当前及下级所有服务商
        String ifUpdateAllSubAgent = getValString("updateType");
        int update;
        if (StringUtils.isNotEmpty(ifUpdateAllSubAgent) && ifUpdateAllSubAgent.equals(AgentConfig.IF_ALL_CURRENT_AND_SUB_AGENT)) {
            update = agentConfigService.updateBatchAll(agentConfigList, getValStringRequired("agentNo"), groupKey);
        } else {
            update = agentConfigService.updateBatch(agentConfigList, getValStringRequired("agentNo"), groupKey);
        }
        if (update <= 0) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }

        return ApiRes.ok();
    }

    /**
     * 服务商贴牌配置信息更新or新增
     */
    @MethodLog(remark = "更新服务商贴牌信息")
    @PutMapping("/updateOem")
    public ApiRes updateOem() {
        AgentConfig agentConfig = new AgentConfig();
        List<AgentConfig> agentConfigList = new ArrayList<>();
        String groupKey = getValStringRequired("groupKey");
        //String configKey = getValStringRequired("configKey");
        String agentNo = getValStringRequired("agentNo");
        JSONObject paramJSON = getReqParamJSON();
        Map<String, String> updateMap = new HashMap<>();
        //平台配置
        if ("oemConfig".equals(groupKey)) {
            try {
                //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());
                agentConfig.setAgentNo(agentNo);
                agentConfig.setConfigKey(groupKey);
                agentConfig.setGroupKey(groupKey);
                agentConfig.setConfigVal(updateMap.get("oemConfig"));
                agentConfig.setCreatedAt(new Date());
                agentConfig.setUpdatedAt(new Date());
                agentConfigList.add(agentConfig);
            } catch (Exception e) {
                throw new BizException("参数解析错误！");
            }
        } else if ("treatyConfig".equals(groupKey)) {
            paramJSON.remove("groupKey");
            paramJSON.remove("agentNo");
            Map<String, String> map = JSONObject.toJavaObject(paramJSON, Map.class);
            for (String key : map.keySet()) {
                // 记录为空 = 不更新
                if (StringUtils.isEmpty(map.get(key))) {
                    continue;
                }
                agentConfig = new AgentConfig();
                agentConfig.setAgentNo(agentNo);
                agentConfig.setConfigKey(key);
                agentConfig.setGroupKey(groupKey);
                agentConfig.setConfigVal(map.get(key));
                agentConfig.setCreatedAt(new Date());
                agentConfig.setUpdatedAt(new Date());
                agentConfigList.add(agentConfig);
            }
        }

        int updateOem = agentConfigService.updateOem(agentConfigList);
        if (updateOem <= 0) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }
        return ApiRes.ok();
    }

    @GetMapping("/siteConfig")
    public ApiRes getSiteConfig() {
        String agentNo = getValStringRequired("agentNo");

        List<AgentConfig> agentSiteConfig = agentConfigService.lambdaQuery()
                .eq(AgentConfig::getGroupKey, "agentSiteConfig")
                .eq(AgentConfig::getAgentNo, agentNo)
                .list();

        Map<String, Object> result = new HashMap<>();
        agentSiteConfig.forEach(item -> {
            result.put(item.getConfigKey(), item.getConfigVal());
        });

        return ApiRes.ok(result);
    }

    @PostMapping("/siteConfig")
    public ApiRes setSiteConfig() {
        String agentNo = getValStringRequired("agentNo");
        String agentSiteUrl = getValStringRequired("agentSiteUrl");
        String agentSiteCrtUrl = getValStringRequired("agentSiteCrtUrl");
        String agentSitePriKeyUrl = getValStringRequired("agentSitePriKeyUrl");
        String mchSiteUrl = getValStringRequired("mchSiteUrl");
        String mchSiteCrtUrl = getValStringRequired("mchSiteCrtUrl");
        String mchSitePriKeyUrl = getValStringRequired("mchSitePriKeyUrl");

        saasConfigService.siteConfig(agentNo, agentSiteUrl, agentSiteCrtUrl, agentSitePriKeyUrl, mchSiteUrl, mchSiteCrtUrl, mchSitePriKeyUrl);

        return ApiRes.ok();
    }

    @GetMapping("/authData")
    public ApiRes authData() {
        Page<ThirdAuthDataEntity> iPage = getIPage();

        String agentNo = getValStringRequired("agentNo");
        String type = getValStringRequired("type");

        Page<ThirdAuthDataEntity> page = thirdAuthDataService.lambdaQuery()
                .eq(ThirdAuthDataEntity::getAgentNo, agentNo)
                .eq(ThirdAuthDataEntity::getType, type)
                .page(iPage);

        return ApiRes.ok(page);
    }

    @DeleteMapping("/authData/{id}")
    public ApiRes removeAuthData(@PathVariable("id") Long id) {
        thirdAuthDataService.removeById(id);
        return ApiRes.ok();
    }

    @PostMapping("/authData")
    public ApiRes addAuthData() {
        ThirdAuthDataEntity entity = getObject(ThirdAuthDataEntity.class);
        Assert.notNull(entity.getType(), "授权渠道[type]不能为空");
        Assert.notNull(entity.getSubType(), "授权类型[subType]不能为空");
        Assert.notNull(entity.getAuthFileName(), "文件名称[authFileName]不能为空");
        Assert.notNull(entity.getValue(), "文件内容[value]不能为空");

        ThirdAuthDataEntity one = thirdAuthDataService.lambdaQuery()
                .eq(ThirdAuthDataEntity::getAuthFileName, entity.getAuthFileName())
                .one();

        if (one != null) {
            throw new BizException("数据已存在");
        }

        thirdAuthDataService.save(entity);

        return ApiRes.ok();
    }

    @PostMapping("/config")
    public ApiRes setConfig() {
        AgentConfig reqParam = getObject(AgentConfig.class);
        Assert.notNull(reqParam, "缺少参数");
        Assert.notNull(reqParam.getGroupKey(), "配置分组名称代码[groupKey]不能为空");
        Assert.notNull(reqParam.getConfigKey(), "配置名称代码[configKey]不能为空");
        Assert.notNull(reqParam.getAgentNo(), "服务商编号[agentNo]不能为空");
        Assert.notNull(reqParam.getConfigVal(), "配置项[configVal]未赋值");

        agentConfigService.saveOrUpdateConfig(reqParam);

        return ApiRes.ok();
    }
}
