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.model.form.AssetForm;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
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.IAidFundAuditOrderService;
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.NiwodaiCostant;
import com.quantgroup.asset.distribution.service.niwodai.vo.NiwodaiIncomingCallbackResponseVO;
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.service.redis.IRedisService;
import com.quantgroup.asset.distribution.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.util.Map;

/**
 * @author : Hyuk
 * @description : NiWoDaiContraoller
 * @date : 2020/3/27 2:12 下午
 */
@RestController
@Slf4j
@RequestMapping("/niwodai")
public class NiWoDaiController {

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

    @RequestMapping("/incoming/callback")
    public GlobalResponse auditResultCallback(@RequestBody NiwodaiIncomingCallbackResponseVO responseVO) {
        String orderId = responseVO.getOrderId();
        String type = responseVO.getType();
        Integer code = responseVO.getCode();
        Long timestamp = responseVO.getTimestamp();
        String data = responseVO.getData();
        log.info("你我贷审核进件回调收到结果, orderId : {}, type : {}, code : {}, timestamp : {}, data : {}", orderId,
                type, code, timestamp, data);
        AidLoanFundAuditOrder aidLoanFundAuditOrder = aidFundAuditOrderService.findByBizNoAndFundId(orderId, AidFundConstants.FundId.NIWODAI);
        if (aidLoanFundAuditOrder == null) {
            log.info("你我贷审核进件回调结果未找到订单, orderId : {}, type : {}, code : {}, timestamp : {}, data : {}", orderId, type, code, timestamp, data);
            alarmService.dingtalkAlarm("Error", "你我贷资方审核回调结果未找到订单", "bizNo : " + orderId + " , type : " + type + " , code : " + code + " , timestamp : " + timestamp + " , data : "  + data);
            return GlobalResponse.success();
        }
        if (aidLoanFundAuditOrder.getAuditResult().intValue() != AidFundStatus.Incoming.WAIT && aidLoanFundAuditOrder.getAuditResult().intValue() != AidFundStatus.Incoming.PRE) {
            log.info("你我贷进件回调结果订单重复通知结果, 请查看, orderId : {}, type : {}, code : {}, timestamp : {}, data : {}", orderId, type, code, timestamp, data);
            return GlobalResponse.success();
        }
        if (!"APPLY".equals(type)) {
            log.info("你我贷审核进件回调结果type出现错误, orderId : {}, type : {}, code : {}, timestamp : {}, data : {}", orderId, type, code, timestamp , data);
            alarmService.dingtalkAlarm("Error", "你我贷审核结果回调type错误", "bizNo : " + orderId + " , type : " + type + " , code : " + code + " , timestamp : " + timestamp + " , data : "  + data);
            return GlobalResponse.success();
        }
        if (code == null || (code.intValue() != 300005 && code.intValue() != 300006)) {
            log.info("你我贷审核进件回调结果code出现错误, orderId : {}, type : {}, code : {}, timestamp : {}, data : {}", orderId, type, code, timestamp , data);
            alarmService.dingtalkAlarm("Error", "你我贷审核结果回调code出现错误", "bizNo : " + orderId + " , type : " + type + " , code : " + code + " , timestamp : " + timestamp + " , data : "  + data);
            return GlobalResponse.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 (300005 == code.intValue()) {
            // 将助贷审核订单状态改为拒绝
            aidFundAuditOrderService.updateOrderStatus(aidLoanFundAuditOrder, AidFundStatus.Incoming.REJECT);
            // 将分发记录改为失败
            assetDistributeRecordService.updateAssetDistributeStatus(orderId, StatusConstants.FAIL);
            // 重新进行分发
            assetDistributeService.distribute(assetForm, asset, dataMap);
        } else {
            NiwodaiIncomingResultResponseVO vo = JSON.parseObject(data, NiwodaiIncomingResultResponseVO.class);
            aidLoanFundAuditOrder.setAuditContext(JSON.toJSONString(vo));
            if (!checkIncomingResult(vo)) {
                log.info("你我贷审核进件回调结果data出现错误, orderId : {}, type : {}, code : {}, timestamp : {}, data : {}", orderId, type, code, timestamp, JSON.toJSONString(vo));
                alarmService.dingtalkAlarm("Error", "你我贷审核结果回调data出现错误", "bizNo : " + orderId + " , type : " + type + " , code : " + code + " , timestamp : " + timestamp + " , data : "  + data);
                return GlobalResponse.success();
            }
            // 通过了直接通知资金系统
            String finance = financeProductService.createSingletonFinanceProduct(vo.getApprovedAmount().toString(), String.valueOf(vo.getApproveTerm()), aidLoanFundAuditOrder.getFundId(), aidLoanFundAuditOrder.getFundProductId());
            assetForm = financeProductService.checkFundResult(assetForm, finance, Long.parseLong(vo.getValidBefore()));
            assetForm.setAmount(vo.getApprovedAmount().toString());
            assetForm.setTerm(String.valueOf(vo.getApproveTerm()));
            // 将助贷审核订单状态改为成功
            aidFundAuditOrderService.updateOrderStatus(aidLoanFundAuditOrder, AidFundStatus.Incoming.PASS);
            notifyService.notifyFundServer(assetForm, dataMap);
        }
        log.info("你我贷审核进件回调结果处理完成, orderId : {}, type : {}, code : {}, timestamp : {}, data : {}", orderId,
                 type, code, timestamp, data);
        return GlobalResponse.success();
    }

    /**
     * 审核通过，检验参数
     * @param vo
     * @return
     */
    private boolean checkIncomingResult(NiwodaiIncomingResultResponseVO vo) {
        if (vo == null || vo.getApprovedAmount() == null || vo.getValidBefore() == null || vo.getApproveTerm() == null) {
            return false;
        }
        return true;
    }
}