package com.jeequan.jeepay.mgr.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.components.mq.model.ResetIsvMchAppInfoConfigMQ;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.core.aop.MethodLog;
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.core.model.PrefixConfig;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.db.entity.IsvInfoEntity;
import com.jeequan.jeepay.db.entity.MchConfig;
import com.jeequan.jeepay.db.entity.RateConfig;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
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;

/**
 * 渠道商管理类
 */
@RestController
@RequestMapping("/api/isvInfo")
public class IsvInfoController extends CommonCtrl {

    @Autowired
    private IsvInfoService isvInfoService;



    @Autowired
    private IMQSender mqSender;

    @Autowired
    private PrefixConfig prefixConfig;

    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;

    /**
     * @author: pangxiaoyu
     * @date: 2021/6/7 16:12
     * @describe: 查询渠道商信息列表 ( 渠道商列表 和 新增商户都可查询 )
     */
    @PreAuthorize("hasAnyAuthority('ENT_ISV_LIST', 'ENT_MCH_INFO_ADD')")
    @GetMapping
    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);
    }

    /**
     * 新增渠道商信息
     */
    @PreAuthorize("hasAuthority('ENT_ISV_INFO_ADD')")
    @MethodLog(remark = "新增渠道商")
    @PostMapping
    public ApiRes add() {
        IsvInfoEntity isvInfoEntity = getObject(IsvInfoEntity.class);
        isvInfoEntity.setIsvNo(SeqKit.genIsvNo());
        isvInfoEntity.setCreatedUid(getCurrentUser().getSysUser().getSysUserId());
        isvInfoEntity.setCreatedBy(getCurrentUser().getSysUser().getRealname());
        boolean result = isvInfoService.save(isvInfoEntity);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }
        return ApiRes.ok();
    }

    /**
     * 删除渠道商信息
     */
    @PreAuthorize("hasAuthority('ENT_ISV_INFO_DEL')")
    @MethodLog(remark = "删除渠道商")
    @DeleteMapping("/{isvNo}")
    public ApiRes delete(@PathVariable("isvNo") String isvNo) {
        isvInfoService.removeByIsvNo(isvNo);

        // 推送mq到目前节点进行更新数据
        mqSender.send(ResetIsvMchAppInfoConfigMQ.build(ResetIsvMchAppInfoConfigMQ.RESET_TYPE_ISV_INFO, isvNo, null, null));
        return ApiRes.ok();
    }

    /**
     * 更新渠道商信息
     */
    @PreAuthorize("hasAuthority('ENT_ISV_INFO_EDIT')")
    @MethodLog(remark = "更新渠道商信息")
    @PutMapping("/{isvNo}")
    public ApiRes update(@PathVariable("isvNo") String isvNo) {
        IsvInfoEntity isvInfoEntity = getObject(IsvInfoEntity.class);
        isvInfoEntity.setIsvNo(isvNo);
        boolean result = isvInfoService.updateById(isvInfoEntity);

        // 推送mq到目前节点进行更新数据
        mqSender.send(ResetIsvMchAppInfoConfigMQ.build(ResetIsvMchAppInfoConfigMQ.RESET_TYPE_ISV_INFO, isvNo, null, null));

        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }
        return ApiRes.ok();
    }

    @PreAuthorize("hasAnyAuthority('ENT_ISV_INFO_VIEW', 'ENT_ISV_INFO_EDIT')")
    @GetMapping("/{isvNo}")
    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");

        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.equalsIgnoreCase(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);
            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);
    }


    @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();
    }

    /**
     * 获取商户费率在对应渠道下的费率
     *
     */
    @GetMapping("/mchUpsRate")
    public ApiRes getMchUpsRateList() {
        String mchNo = getValStringRequired("mchNo");
        String isvNo = getValStringRequired("isvNo");
        String ifCode = getValStringRequired("ifCode");
        Integer range = getValIntegerRequired("range");
        String mccCode = getValString("mccCode");

        List<RateConfig> mchUpsRateList = isvInfoService.getMchIsvRateConfig(mchNo, isvNo, ifCode, range, mccCode);
        return ApiRes.ok(mchUpsRateList);
    }

    /**
     * 新建服务商、用户与渠道的关联关系
     */
    @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();
    }
}
