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

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.agent.ctrl.CommonCtrl;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
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.IsvInfoEntity;
import com.jeequan.jeepay.db.entity.MchConfig;
import com.jeequan.jeepay.service.impl.IsvInfoService;
import com.jeequan.jeepay.service.impl.PayInterfaceConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 服务商管理类
 *
 * @author pangxiaoyu
 * @date 2021-06-07 07:15
 */
@RestController
@RequestMapping("/api/isvInfo")
public class IsvInfoController extends CommonCtrl {

    @Autowired
    private IsvInfoService isvInfoService;

    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;

    /**
     * @author: pangxiaoyu
     * @date: 2021/6/7 16:12
     * @describe: 查询服务商信息列表
     */
    @PreAuthorize("hasAuthority('ENT_ISV_LIST')")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ApiRes list() {
        IsvInfoEntity isvInfoEntity = getObject(IsvInfoEntity.class);
        LambdaQueryWrapper<IsvInfoEntity> wrapper = IsvInfoEntity.gw();
        if (StringUtils.isNotEmpty(isvInfoEntity.getIsvNo())) {
            wrapper.eq(IsvInfoEntity::getIsvNo, isvInfoEntity.getIsvNo());
        }
        if (StringUtils.isNotEmpty(isvInfoEntity.getIsvName())) {
            wrapper.eq(IsvInfoEntity::getIsvName, isvInfoEntity.getIsvName());
        }
        if (isvInfoEntity.getState() != null) {
            wrapper.eq(IsvInfoEntity::getState, isvInfoEntity.getState());
        }
        wrapper.orderByDesc(IsvInfoEntity::getCreatedAt);
        IPage<IsvInfoEntity> pages = isvInfoService.page(getIPage(true), wrapper);

        return ApiRes.page(pages);
    }

    /**
     * @author: pangxiaoyu
     * @date: 2021/6/7 16:13
     * @describe: 查看服务商信息
     */
    @PreAuthorize("hasAnyAuthority('ENT_ISV_INFO_VIEW', 'ENT_ISV_INFO_EDIT')")
    @RequestMapping(value = "/{isvNo}", method = RequestMethod.GET)
    public ApiRes detail(@PathVariable("isvNo") String isvNo) {
        IsvInfoEntity isvInfoEntity = isvInfoService.getById(isvNo);
        if (isvInfoEntity == null) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }
        return ApiRes.ok(isvInfoEntity);
    }

    @GetMapping("/isvInfoList")
    public ApiRes getIsvInfoList() {
        String ifCode = getValStringRequired("ifCode");
        String infoType = getValStringRequired("infoType");
        String infoId = getValStringRequired("infoId");
        String range = getValString("range");
        Integer state = getValInteger("state");
        String isvName = getValString("isvName");

        if ("CURRENTAGENT".equals(infoId)) {
            infoId = getCurrentAgentNo();
        }

        List<IsvInfo> isvAndPayConfig = isvInfoService.getIsvAndPayConfig(infoType, isvName, infoId, ifCode, range, state);

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

        if (!CS.SYS_ROLE_TYPE.MCH.equals(infoType)) {
            return ApiRes.ok(page);
        }

        // 如果是查看商户数据，则查询他的默认渠道
        List<Map<String, String>> defIsv = mchInfoService.getDefIsv(infoId, ifCode);
        if (!ObjectUtils.isEmpty(defIsv)) {
            Map<String, String> defIsvItem = defIsv.get(0);

            page.getRecords().forEach(r -> {
                if (r.getIsvNo().equals(defIsvItem.get(MchConfig.getDefIsvKey(ifCode)))) {
                    r.addExt("defIsv", CS.YES);
                }
            });
        }

        return ApiRes.ok(page);
    }

    @PostMapping("/autoBindIsvConn")
    public ApiRes autoBindIsvConn() {
        String isvNo = getValStringRequired("isvNo");
        String infoId = getValStringRequired("infoId");
        String roleType = getValStringRequired("roleType");
        Byte configStatus = getValByteRequired("configStatus");

        isvInfoService.autoBindIsvConn(isvNo, infoId, roleType, configStatus);

        return ApiRes.ok();
    }

    @PostMapping("/isvConn")
    public ApiRes isvConn() {
        String isvNo = getValStringRequired("isvNo");
        String infoId = getValStringRequired("infoId");
        String infoType = getValStringRequired("infoType");

        isvInfoService.saveIsvConn(isvNo, infoType, infoId, getCurrentUser().getSysUser());

        return ApiRes.ok();
    }

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

    @PostMapping("/editStatus")
    public ApiRes editStatus() {
        String isvNo = getValStringRequired("isvNo");
        String ifCode = getValStringRequired("ifCode");
        String infoId = getValStringRequired("infoId");
        String infoType = getValStringRequired("infoType");
        Integer status = getValIntegerRequired("state");

        isvInfoService.editConnStatus(isvNo, ifCode, infoId, infoType, status);

        return ApiRes.ok();
    }
}
