package com.hr.controller;

import com.hr.dto.AggregateQueryDTO;
import com.hr.externelSystem.BizHandlerFactory;
import com.hr.param.AggregateRequest;
import com.hr.repository.domain.IpInterfacePO;
import com.hr.repository.domain.IpTokenPO;
import com.hr.service.IpTokenInterfaceService;
import com.hr.service.IpAccountService;
import com.hr.service.IpInterfaceService;
import com.hr.vo.IpAccountVO;
import com.hr.vo.IpInterfaceVO;
import com.yy.basedevelop.common.data.BaseReturnDto;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 三方调用聚合接口
 */
@RestController
@RequestMapping("/aggregate")
public class AggregateController {

    @Autowired
    private BizHandlerFactory bizHandlerFactory;

    @Autowired
    private IpTokenInterfaceService ipTokenInterfaceService;

    @Autowired
    private IpAccountService ipAccountService;

    @Autowired
    private IpInterfaceService ipInterfaceService;

    @PostMapping("/openApi")
    public BaseReturnDto<Object> aggregate(@RequestBody AggregateRequest req) {
        String accountNo = req.getAccountNo();
        String interfaceCode = req.getInterfaceCode();
        IpAccountVO ipAccount = ipAccountService.queryByAccountNo(accountNo);
        if(ipAccount == null){
            return BaseReturnDto.error("账户不存在");
        }
        if(!ipAccount.getStatus().equals("normal")){
            return BaseReturnDto.error("账户已禁用");
        }
        IpInterfaceVO ipInterfaceVO = ipInterfaceService.queryByInterfaceCode(interfaceCode);
        if(ipInterfaceVO == null){
            return BaseReturnDto.error("接口不存在");
        }
        if(!ipInterfaceVO.getStatus().equals("normal")){
            return BaseReturnDto.error("接口已禁用");
        }
        AggregateQueryDTO dto = ipTokenInterfaceService.queryConfigByInterfaceCodeAndAccountNo(ipAccount.getId(), ipInterfaceVO.getId());
        IpTokenPO ipTokenPO = dto.getIpTokenPO();
        if(!ipTokenPO.getToken().equals(req.getToken())){
            return BaseReturnDto.error("token错误");
        }
        IpInterfacePO ipInterfacePO = new IpInterfacePO();
        BeanUtils.copyProperties(ipInterfaceVO, ipInterfacePO);
        dto.setIpInterfacePO(ipInterfacePO);
        return bizHandlerFactory.dispatch(req,dto);
    }
}