package com.jeequan.jeepay.mch.ctrl.payconfig;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.IsvUserConn;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.PayInterfaceDefine;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.IsvInfoService;
import com.jeequan.jeepay.service.impl.MchInfoService;
import com.jeequan.jeepay.service.impl.PayInterfaceConfigService;
import com.jeequan.jeepay.service.impl.PayInterfaceDefineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 支付接口定义管理类
 *
 * @author zhuxiao
 *
 * @date 2021-04-27 15:50
 */
@RestController
@RequestMapping("api/payIfDefines")
public class PayInterfaceDefineController extends CommonCtrl {

    @Autowired private PayInterfaceDefineService payInterfaceDefineService;
    @Autowired private PayInterfaceConfigService payInterfaceConfigService;
    @Autowired private MchInfoService mchInfoService;
    @Autowired
    private IsvInfoService isvInfoService;

    /**
     * @Author: ZhuXiao
     * @Description: list
     * @Date: 15:51 2021/4/27
    */
    @GetMapping
    public ApiRes list() {

        MchInfo mchInfo = mchInfoService.getById(getCurrentMchNo());

        PayInterfaceDefine queryRecord = getObject(PayInterfaceDefine.class);

        LambdaQueryWrapper<PayInterfaceDefine> lambdaQueryWrapper = PayInterfaceDefine.gw();
        lambdaQueryWrapper.eq(queryRecord.getState() != null , PayInterfaceDefine::getState, queryRecord.getState());
        lambdaQueryWrapper.eq(queryRecord.getIsSupportApplyment() != null , PayInterfaceDefine::getIsSupportApplyment, queryRecord.getIsSupportApplyment());

        lambdaQueryWrapper.orderByAsc(PayInterfaceDefine::getCreatedAt);

        Map<String, IsvUserConn> isvConnMap = isvInfoService.getIsvUserConn(CS.SYS_ROLE_TYPE.MCH, mchInfo.getMchNo(), CS.YES);

        if (isvConnMap.isEmpty()) {
            return ApiRes.ok(Collections.emptyList());
        }

        // 过滤掉当前商户的所属服务商的配置没有填写或开通的接口。
        List<PayInterfaceDefine> list = payInterfaceDefineService.lambdaQuery()
                .in(PayInterfaceDefine::getIfCode, isvConnMap.keySet()).list();

        return ApiRes.ok(list);
    }
}
