package com.jeequan.jeepay.agent.ctrl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.agent.config.SystemYmlConfig;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.ctrls.AbstractCtrl;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.BaseModel;
import com.jeequan.jeepay.core.model.security.JeeUserDetails;
import com.jeequan.jeepay.db.entity.AgentInfo;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.db.entity.PayInterfaceDefine;
import com.jeequan.jeepay.service.impl.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 通用ctrl类
 *
 * @author terrfly
 * @modify zhuxiao
 * @date 2021-04-27 15:50
 */
public abstract class CommonCtrl extends AbstractCtrl {

    @Autowired protected SystemYmlConfig mainConfig;

    @Autowired protected SysConfigService sysConfigService;

    @Autowired protected MchInfoService mchInfoService;

    @Autowired protected MchStoreService mchStoreService;

    @Autowired protected PayInterfaceDefineService payInterfaceDefineService;

    @Autowired protected AgentInfoService agentInfoService;

    /** 获取当前用户ID */
    protected JeeUserDetails getCurrentUser(){

        return (JeeUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    /** 获取当前商户ID **/
    protected String getCurrentAgentNo() {
        return getCurrentUser().getSysUser().getBelongInfoId();
    }

    /**
     * 获取当前用户登录IP
     * @return
     */
    protected String getIp() {
        return getClientIp();
    }

    /**
     * 校验当前用户是否为超管
     * @return
     */
    protected ApiRes checkIsAdmin() {
        SysUser sysUser = getCurrentUser().getSysUser();
        if (sysUser.getUserType() != SysUser.UEST_TYPE_ADMIN) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }else {
            return null;
        }

    }

    /** model 存入服务商名称 **/
    public void setAgentName(List<? extends BaseModel> modeList) {

        if(modeList == null || modeList.isEmpty()){
            return ;
        }
        ArrayList<String> agentNoList = new ArrayList<>();
        for (BaseModel model:modeList) {
            JSONObject json = (JSONObject) JSONObject.toJSON(model);
            String agentNo = json.getString("agentNo");
            agentNoList.add(agentNo);
        }
        List<AgentInfo> agentInfoList = agentInfoService.list(AgentInfo.gw().select(AgentInfo::getAgentNo, AgentInfo::getAgentName).in(AgentInfo::getAgentNo, agentNoList));
        for (BaseModel model:modeList) {
            JSONObject json = (JSONObject) JSONObject.toJSON(model);
            String agentNo = json.getString("agentNo");

            if(StringUtils.isBlank(agentNo)) {
                continue;
            }

            for (AgentInfo info:agentInfoList) {
                if (agentNo.equals(info.getAgentNo())) {
                    model.addExt("agentName", info.getAgentName());
                }
            }
        }
    }

    /** model 存入商户名称 **/
    public void setMchName(List<? extends BaseModel> modeList) {

        if(modeList == null || modeList.isEmpty()){
            return ;
        }
        ArrayList<String> mchNoList = new ArrayList<>();
        for (BaseModel model:modeList) {
            JSONObject json = (JSONObject) JSONObject.toJSON(model);
            String mchNo = json.getString("mchNo");
            mchNoList.add(mchNo);
        }
        List<MchInfo> mchInfoList = mchInfoService.list(MchInfo.gw().select(MchInfo::getMchNo, MchInfo::getMchName).in(MchInfo::getMchNo, mchNoList));
        for (BaseModel model:modeList) {
            JSONObject json = (JSONObject) JSONObject.toJSON(model);
            String mchNo = json.getString("mchNo");

            if(StringUtils.isBlank(mchNo)) {
                continue;
            }

            for (MchInfo info:mchInfoList) {
                if (mchNo.equals(info.getMchNo())) {
                    model.addExt("mchName", info.getMchName());
                }
            }
        }
    }

    /** model 存入门店名称 **/
    public void setStoreName(List<? extends BaseModel> modeList) {

        if (modeList == null || modeList.isEmpty()) {
            return;
        }
        ArrayList<String> storeIdList = new ArrayList<>();
        for (BaseModel model : modeList) {
            JSONObject json = (JSONObject) JSONObject.toJSON(model);
            String storeId = json.getString("storeId");
            storeIdList.add(storeId);
        }
        List<MchStore> mchInfoList = mchStoreService.list(MchStore.gw().select(MchStore::getStoreId, MchStore::getStoreName).in(MchStore::getStoreId, storeIdList));
        for (BaseModel model : modeList) {
            JSONObject json = (JSONObject) JSONObject.toJSON(model);
            String storeId = json.getString("storeId");

            if (storeId == null) {
                continue;
            }

            for (MchStore store : mchInfoList) {
                if (storeId.equals(store.getStoreId())) {
                    model.addExt("storeName", store.getStoreName());
                }
            }
        }
    }

    /** model 存入支付接口名称 **/
    public void setIfName(List<? extends BaseModel> modeList) {

        if(modeList == null || modeList.isEmpty()){
            return ;
        }
        ArrayList<String> ifCodeList = new ArrayList<>();
        for (BaseModel model:modeList) {
            JSONObject json = (JSONObject) JSONObject.toJSON(model);
            String ifCode = json.getString("ifCode");
            ifCodeList.add(ifCode);
        }
        List<PayInterfaceDefine> defineList = payInterfaceDefineService.list(PayInterfaceDefine.gw().select(PayInterfaceDefine::getIfCode, PayInterfaceDefine::getIfName).in(PayInterfaceDefine::getIfCode, ifCodeList));
        for (BaseModel model : modeList) {
            JSONObject json = (JSONObject) JSONObject.toJSON(model);
            String ifCode = json.getString("ifCode");

            if(StringUtils.isBlank(ifCode)) {
                continue;
            }

            for (PayInterfaceDefine define : defineList) {
                if (ifCode.equals(define.getIfCode())) {
                    model.addExt("ifName", define.getIfName());
                }
            }
        }
    }

    /** 判断当前用户是否有某个权限  */
    public boolean currentUserHasEnt(String ent){
        return getCurrentUser().getAuthorities().contains(new SimpleGrantedAuthority("ENT_MCH_APPLYMENT_PAY_CONFIG"));
    }

    /** 根据服务商号，查询服务商下的商户号List **/
    public List<String> getMchNoListByAgentNo(String agentNo) {

        if (StringUtils.isBlank(agentNo)) {
            return null;
        }

        AgentInfo agentInfo = agentInfoService.getById(agentNo);
        if (agentInfo == null || agentInfo.getState() != CS.YES) {
            throw new BizException("服务商不存在或状态不正确");
        }

        List<MchInfo> list = mchInfoService.list(MchInfo.gw().eq(com.jeequan.jeepay.core.entity.MchInfo::getAgentNo, agentNo));
        if (CollUtil.isEmpty(list)) {
            return null;
        }

        List<String> mchNoList = new LinkedList<>();
        list.forEach(mchInfo -> mchNoList.add(mchInfo.getMchNo()));
        return mchNoList;
    }

}
