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

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.IsvInfo;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.MchConfig;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/api/isvInfo")
public class IsvInfoController extends CommonCtrl {

    @Autowired
    private IsvInfoService isvInfoService;

    @Autowired
    private MchInfoService mchInfoService;

    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;

    @GetMapping("/isvInfoList")
    public ApiRes getIsvInfoList() {
        String ifCode = getValStringRequired("ifCode");
        String currentMchNo = getCurrentMchNo();
        String range = getValStringRequired("range");
        Integer state = getValInteger("state");

        String isvName = getValString("isvName");

        List<IsvInfo> isvAndPayConfig = isvInfoService.getIsvAndPayConfig(CS.SYS_ROLE_TYPE.MCH, isvName,currentMchNo, ifCode, range, state);

        Page<IsvInfo> page = new Page<>();
        page.setRecords(isvAndPayConfig);
        page.setSize(-1);
        page.setPages(1);

        // 如果是查看商户数据，则查询他的默认渠道
        List<Map<String, String>> defIsv = mchInfoService.getDefIsv(currentMchNo, ifCode);
        if (!ObjectUtils.isEmpty(defIsv)) {
            Map<String, String> defIsvItem = defIsv.get(0);
            String defIsvNo = defIsvItem.get(MchConfig.getDefIsvKey(ifCode));
            page.getRecords().forEach(r -> r.addExt("defFlag", r.getIsvNo().equals(defIsvNo) ? CS.YES : CS.NO));
        } else {
            page.getRecords().forEach(r -> r.addExt("defFlag", CS.NO));
        }

        return ApiRes.ok(page);
    }

    @GetMapping("/getSettType")
    public ApiRes getSettType(){
        String ifCode = getValStringRequired("ifCode");
        String infoId = getValStringRequired("infoId");
        JSONArray settType = isvInfoService.getSettType(ifCode, infoId);
        return ApiRes.ok(settType);
    }
}
