package com.quantgroup.asset.distribution.controller;

import com.alibaba.fastjson.JSON;
import com.quantgroup.asset.distribution.constant.AidFundConstants;
import com.quantgroup.asset.distribution.constant.AidFundStatus;
import com.quantgroup.asset.distribution.constant.StatusConstants;
import com.quantgroup.asset.distribution.constant.aid.AidAuditResultConstants;
import com.quantgroup.asset.distribution.enums.response.MiddleOfficeCommonResponseEnum;
import com.quantgroup.asset.distribution.exception.QGException;
import com.quantgroup.asset.distribution.exception.QGExceptionType;
import com.quantgroup.asset.distribution.exception.QGPreconditions;
import com.quantgroup.asset.distribution.model.entity.aid.AidAuditResultEntity;
import com.quantgroup.asset.distribution.model.entity.aid.AidRsaParams;
import com.quantgroup.asset.distribution.model.form.AssetForm;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
import com.quantgroup.asset.distribution.model.response.MiddleOfficeResponse;
import com.quantgroup.asset.distribution.service.aid.IAidFundInfoConfigService;
import com.quantgroup.asset.distribution.service.alarm.IAlarmService;
import com.quantgroup.asset.distribution.service.distribute.IAssetDistributeRecordService;
import com.quantgroup.asset.distribution.service.distribute.IAssetDistributeService;
import com.quantgroup.asset.distribution.service.funding.IAidAssetCommonService;
import com.quantgroup.asset.distribution.service.funding.IAidFundAuditOrderService;
import com.quantgroup.asset.distribution.service.jpa.entity.AidFundInfoConfig;
import com.quantgroup.asset.distribution.service.jpa.entity.AidLoanFundAuditOrder;
import com.quantgroup.asset.distribution.service.jpa.entity.Asset;
import com.quantgroup.asset.distribution.service.niwodai.vo.NiwodaiIncomingResultResponseVO;
import com.quantgroup.asset.distribution.service.notify.INotifyService;
import com.quantgroup.asset.distribution.service.product.IFinanceProductService;
import com.quantgroup.asset.distribution.util.RsaUtils;
import com.quantgroup.asset.distribution.util.aid.AidAuditResultCheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;
import java.util.Optional;

/**
 * @author : Hyuk
 * @description : AidCommonCallbackController
 * @date : 2020/7/5 11:14 下午
 */
@RestController
@Slf4j
@RequestMapping("/distribution/aid/common/asset")
public class AidCommonCallbackController {

    @Autowired
    private IAlarmService alarmService;
    @Autowired
    private IAidFundInfoConfigService aidFundInfoConfigService;
    @Autowired
    private IAidFundAuditOrderService aidFundAuditOrderService;
    @Autowired
    private IAssetDistributeRecordService assetDistributeRecordService;
    @Autowired
    private IAssetDistributeService assetDistributeService;
    @Autowired
    private IFinanceProductService financeProductService;
    @Autowired
    private INotifyService notifyService;

    @RequestMapping("/{fund_id}/{fund_product_id}/audit_result_callback")
    public MiddleOfficeResponse auditResultCallback(@PathVariable("fund_id") String fundId,
                                                    @PathVariable("fund_product_id") String fundProId,
                                                    @RequestBody AidRsaParams aidRsaParams) {

        // mdgbd, 对方不肯下回调接口, 先直接返回成功
//        try {
//            QGPreconditions.checkArgument(StringUtils.isNoneEmpty(fundId, fundProId, aidRsaParams.getContent()),
//                    QGExceptionType.AID_COMMON_AUDIT_RESULT_ORDER_ERROR, fundId, fundProId, aidRsaParams.getContent());
//
//            AidFundInfoConfig aidFundInfoConfig = aidFundInfoConfigService.findAidFundInfo(fundId, fundProId);
//            QGPreconditions.checkArgument(aidFundInfoConfig != null, QGExceptionType.UNKNOW_AID_FUND_ID, fundId);
//
//            String content = RsaUtils.decryptByPublicKey(aidRsaParams.getContent(), aidFundInfoConfig.getPublicKey());
//            log.info("通用助贷资方接收审核结果, fundId : {}, fundProductId : {}, content : {}", fundId, fundProId, content);
//
//            AidAuditResultEntity aidAuditResultEntity = JSON.parseObject(content, AidAuditResultEntity.class);
//            QGPreconditions.checkArgument(AidAuditResultCheckUtils.check(aidAuditResultEntity),
//                    QGExceptionType.AID_COMMON_AUDIT_RESULT_ORDER_ERROR, fundId, fundProId, JSON.toJSONString(aidAuditResultEntity));
//
//            // 定位订单
//            AidLoanFundAuditOrder aidLoanFundAuditOrder = aidFundAuditOrderService.findByBizNoAndFundId(
//                    aidAuditResultEntity.getOrderNo(), fundId);
//            QGPreconditions.checkArgument(aidLoanFundAuditOrder != null &&
//                            (aidLoanFundAuditOrder.getAuditResult().equals(AidFundStatus.Incoming.WAIT) ||
//                            aidLoanFundAuditOrder.getAuditResult().equals(AidFundStatus.Incoming.PRE)),
//                    QGExceptionType.AID_COMMON_AUDIT_RESULT_ORDER_ERROR,
//                    aidAuditResultEntity.getOrderNo(), fundId, aidLoanFundAuditOrder.getAuditResult());
//
//
//            // 开始处理审核结果
//            String orderNo = aidAuditResultEntity.getOrderNo();
//            if (aidAuditResultEntity.getAuditResult().equals(AidAuditResultConstants.AUDITING)) {
//                return MiddleOfficeResponse.created(MiddleOfficeCommonResponseEnum.SUCCESS);
//            }
//
//            AssetForm assetForm = JSON.parseObject(aidLoanFundAuditOrder.getAssetFormText(), AssetForm.class);
//            Asset asset = JSON.parseObject(aidLoanFundAuditOrder.getAssetText(), Asset.class);
//            Map<String, Object> dataMap = JSON.parseObject(aidLoanFundAuditOrder.getDataText(), Map.class);
//
//            // 审核拒绝
//            if (aidAuditResultEntity.getAuditResult().equals(AidAuditResultConstants.REJECT)) {
//                // 将助贷审核订单状态改为拒绝
//                aidFundAuditOrderService.updateOrderStatus(aidLoanFundAuditOrder, AidFundStatus.Incoming.REJECT);
//                // 将分发记录改为失败
//                assetDistributeRecordService.updateAssetDistributeStatus(orderNo, StatusConstants.FAIL);
//                // 重新进行分发
//                assetDistributeService.distribute(assetForm, asset, dataMap);
//                return MiddleOfficeResponse.created(MiddleOfficeCommonResponseEnum.SUCCESS);
//            }
//
//            // 审核通过
//            if (aidAuditResultEntity.getAuditResult().equals(AidAuditResultConstants.PASS)) {
//                aidLoanFundAuditOrder.setAuditContext(JSON.toJSONString(aidAuditResultEntity));
//                // 通过了直接通知资金系统
//                String finance = financeProductService.createSingletonFinanceProduct(aidAuditResultEntity.getAmount().toString(),
//                        String.valueOf(aidAuditResultEntity.getTerm()), aidLoanFundAuditOrder.getFundId(), aidLoanFundAuditOrder.getFundProductId());
//                assetForm = financeProductService.checkFundResult(assetForm, finance, aidAuditResultEntity.getDeadLine());
//                assetForm.setAmount(aidAuditResultEntity.getAmount().toString());
//                assetForm.setTerm(String.valueOf(aidAuditResultEntity.getTerm()));
//
//                // 将助贷审核订单状态改为成功
//                aidFundAuditOrderService.updateOrderStatus(aidLoanFundAuditOrder, AidFundStatus.Incoming.PASS);
//                notifyService.notifyFundServer(assetForm, dataMap);
//            }
//            return MiddleOfficeResponse.created(MiddleOfficeCommonResponseEnum.SUCCESS);
//        } catch (QGException qx) {
//            log.error("助贷资方通用审核结果回调接口出现错误 : {}, fundId : {}, fundProductId : {}, aidRsaParams : {}", fundId,
//                    fundProId, aidRsaParams);
//            alarmService.dingtalkAlarm("Warn", "助贷资方通用审核结果回调接口出现错误", "fundId : " +
//                    fundId + " , fundProductId : " + fundProId + " , 错误信息 : " + qx.qgExceptionType.code + "->" + qx.detail);
//        } catch (Exception e) {
//            log.error("助贷资方通用审核结果回调接口出现未知异常, fundId : {}, fundProductId : {}, aidRsaParams : {}", fundId,
//                    fundProId, aidRsaParams, e);
//            alarmService.dingtalkAlarm("Warn", "助贷资方通用审核结果回调接口出现未知错误", "fundId : " +
//                    fundId + " , fundProductId : " + fundProId + " , 错误信息 : 未知错误");
//        }
        return MiddleOfficeResponse.created(MiddleOfficeCommonResponseEnum.SUCCESS);
    }

}
