package com.quantgroup.asset.distribution.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.quantgroup.asset.distribution.model.entity.fund.FundConfigCondition;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Stopwatch;
import com.quantgroup.asset.distribution.constant.FundModuleConstants;
import com.quantgroup.asset.distribution.enums.response.FundModuleResponse;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
import com.quantgroup.asset.distribution.service.funding.IFundModuleService;
import com.quantgroup.asset.distribution.util.fund.module.ChannelFundConfigUtil;

import lombok.extern.slf4j.Slf4j;

import javax.persistence.criteria.CriteriaBuilder;

/**
 * 资方模块Controller
 * @author liwenbin
 *
 */
@RestController
@Slf4j
@RequestMapping("/fund")
public class FundModuleController {
	
	@Autowired
	private IFundModuleService fundModuleService;
	
	@RequestMapping("/get_all_funds")
	public GlobalResponse getAllFunds() {
		Stopwatch stopwatch = Stopwatch.createStarted();
		GlobalResponse response = fundModuleService.getMiddleOfficeAllFundsInfo();
		log.info("资方模块接口, 获取所有资方信息完成, 耗时 : {}, response : {}", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping("/get_all_limit_type")
	public GlobalResponse getAllLimitInfo() {
		Stopwatch stopwatch = Stopwatch.createStarted();
		GlobalResponse response = fundModuleService.getAllLimitType();
		log.info("资方模块接口, 获取所有条件限制类型完成, 耗时 : {}, response : {}", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping("save_channel_funds_config")
	public GlobalResponse saveChannelFundsConfig(Integer type, Long id, String bizChannel, String funds, String remarks, 
			String auditor, String proposer) {
		return saveChannelFundsConfigCommon(type, id, bizChannel, funds, remarks, auditor, proposer, 1);
	}
	
	@RequestMapping("/get_channel_fund_configs")
	public GlobalResponse getChannelFundConfigs(String bizChannel, Long fundId, Integer pageNum, Integer pageSize) {
		return getChannelFundsConfigCommon(bizChannel, fundId, pageNum, pageSize, 1,null);
	}
	
	@RequestMapping("/get_audit_infos")
	public GlobalResponse getAuditInfos(String targetName, Integer auditStatus, Integer auditType, Integer auditTarget, String applyStartTime, String applyEndTime, String user, Integer pageNum, Integer pageSize) {
		log.info("资方模块接口, 获取审批列表开始, targetName : {}, auditStatus : {}, auditType : {}, auditTarget : {}， applyStartTime : {}, applyEndTime : {}, user : {}, pageNum : {}, pageSize : {}", targetName, auditStatus, auditType, auditTarget, applyStartTime, applyEndTime, user, pageNum, pageSize);
		if (pageNum == null || pageSize == null) {
			return GlobalResponse.create(FundModuleResponse.PAGEING_CONDITIONS_IS_EMPTY);
		}
		if (StringUtils.isEmpty(user)) {
			return GlobalResponse.create(FundModuleResponse.USER_IS_EMPTY);
		}
		Stopwatch stopwatch = Stopwatch.createStarted();
		GlobalResponse response = fundModuleService.getAuditInfos(targetName, auditStatus, auditType, auditTarget, applyStartTime, applyEndTime, user, pageNum, pageSize);
		log.info("资方模块接口, 获取审批列表结束, targetName : {}, auditStatus : {}, auditType : {}, auditTarget : {}， applyStartTime : {}, applyEndTime : {}, user : {}, pageNum : {}, pageSize : {}， 耗时 : {}, response : {}", targetName, auditStatus, auditType, auditTarget, applyStartTime, applyEndTime, user, pageNum, pageSize, stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), JSON.toJSONString(response));
		return response;
	}
	
	@RequestMapping("/find_channel_fund_config")
	public GlobalResponse findChannelFundConfig(Long configId) {
		return findChannelFundConfigCommon(configId, 1);
	}
	
	@RequestMapping("/audit")
	public GlobalResponse audit(Long id, Integer auditStatus) {
		log.info("资方模块接口，审批执行开始, id : {}, auditStatus : {}", id, auditStatus);
		if (id == null) {
			return GlobalResponse.create(FundModuleResponse.ID_IS_EMPTY);
		}
		if (auditStatus == null) {
			return GlobalResponse.create(FundModuleResponse.AUDIT_STATUS_IS_EMPTY);
		}
		Stopwatch stopwatch = Stopwatch.createStarted();
		GlobalResponse response = fundModuleService.audit(id, auditStatus);
		log.info("资方模块接口，审批执行开始, id : {}, auditStatus : {}, 耗时 : {}, response : {}", id, auditStatus, stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), JSON.toJSONString(response));
		return response;
	}

	@RequestMapping("/save_channel_funds_config_new")
	public GlobalResponse saveChannelFundsConfigNew(Integer type, Long id, String bizChannel, String funds, String remarks,
													String auditor, String proposer) {
		return saveChannelFundsConfigCommon(type, id, bizChannel, funds, remarks, auditor, proposer, 2);
	}

	@RequestMapping("/get_channel_fund_configs_new")
	public GlobalResponse getChannelFundConfigsNew(String bizChannel, Long fundId, Integer pageNum, Integer pageSize,Integer sortMode) {
		return getChannelFundsConfigCommon(bizChannel, fundId, pageNum, pageSize, 2,sortMode);
	}

	@RequestMapping("/find_channel_fund_config_new")
	public GlobalResponse findChannelFundConfigNew(Long configId) {
		return findChannelFundConfigCommon(configId, 2);
	}

	@RequestMapping("/simulation/conditions")
	public GlobalResponse allConditions(Long configId){
		return fundConfigConditions(configId);
	}

	@RequestMapping("/simulation/result")
	public GlobalResponse simulationResult(String configConditions, Long configId){
		return simulation(JSON.parseArray(configConditions,FundConfigCondition.class),configId);
	}

	@RequestMapping("/get_all_channel")
	public GlobalResponse getAllConfigingChannels() {
		Stopwatch stopwatch = Stopwatch.createStarted();
		GlobalResponse response = fundModuleService.getAllConfigChannel();
		log.info("资方模块接口, 获取所有已进行资方配置的渠道号结束, response : {}, 耗时 : {}", JSON.toJSONString(response), stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
		return response;
	}

	private GlobalResponse saveChannelFundsConfigCommon(Integer type, Long id, String bizChannel, String funds, String remarks,
														String auditor, String proposer, int oldOrNew) {
		log.info("资方模块接口, 新增或修改资方配置开始, type : {}, id : {}, bizChannel : {}, funds : {}, remarks : {}, auditor : {}, proposer : {}", type, id, bizChannel, funds, remarks, auditor, proposer);
		// 参数校验
		if (type == null) {
			return GlobalResponse.create(FundModuleResponse.TYPE_IS_EMPTY);
		}
		if (type != FundModuleConstants.CHANNEL_FUNDS_OPERAOTR_TYPE_ADD && type != FundModuleConstants.CHANNEL_FUNDS_OPERATOR_TYPE_UPDATE) {
			return GlobalResponse.create(FundModuleResponse.UNKNOW_TYPE);
		}
		if (type == 2 && id == null) {
			return GlobalResponse.create(FundModuleResponse.ID_IS_EMPTY);
		}
		if (StringUtils.isEmpty(bizChannel)) {
			return GlobalResponse.create(FundModuleResponse.BIZ_CHANNEL_IS_EMPTY);
		}
		if (StringUtils.isEmpty(funds)) {
			return GlobalResponse.create(FundModuleResponse.FUNDS_INFO_IS_EMPTY);
		}
		if (!ChannelFundConfigUtil.checkFunds(funds)) {
			return GlobalResponse.create(FundModuleResponse.FUNDS_INFO_ERROR);
		}
		if (StringUtils.isEmpty(auditor) || StringUtils.isEmpty(proposer)) {
			return GlobalResponse.create(FundModuleResponse.AUDITOR_OR_PROPOSER_IS_EMPTY);
		}
		Stopwatch stopwatch = Stopwatch.createStarted();
		GlobalResponse response = null;
		if (oldOrNew == 1) {
			// 老接口
			response = fundModuleService.saveChannelFundConfig(type, id, bizChannel, funds, remarks, auditor, proposer);
		} else {
			// 新接口
			response = fundModuleService.saveChannelFundConfigNew(type, id, bizChannel, funds, remarks, auditor, proposer);
		}
		log.info("资方模块接口, 新增或修改资方配置结束, type : {}, id : {}, bizChannel : {}, funds : {}, remarks : {}, auditor : {}, proposer : {}, 耗时 : {}, reponse : {}", type, id, bizChannel, funds, remarks, auditor, proposer, stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), JSON.toJSONString(response));
		return response;
	}

	private GlobalResponse getChannelFundsConfigCommon(String bizChannel, Long fundId, Integer pageNum, Integer pageSize, int oldOrNew,Integer sortMode) {
		log.info("资方模块接口, 查询渠道资方配置信息开始, bizChannel : {}, fundId : {}, pageNum : {}, pageSize : {}", bizChannel, fundId, pageNum, pageSize);
		if (pageNum == null || pageSize == null) {
			return GlobalResponse.create(FundModuleResponse.PAGEING_CONDITIONS_IS_EMPTY);
		}
		Stopwatch stopwatch = Stopwatch.createStarted();
		GlobalResponse response = null;
		if (oldOrNew == 1) {
			// 老接口
			response = fundModuleService.getChannelFundConfigs(bizChannel, fundId, pageNum, pageSize);
		} else {
			response = fundModuleService.getChannelFundConfigsNew(bizChannel, fundId, pageNum, pageSize,sortMode);
		}

		log.info("资方模块接口, 查询渠道资方配置信息结束, bizChannel : {}, fundId : {}, pageNum : {}, pageSize : {}, 耗时 : {}, response : {}", bizChannel, fundId, pageNum, pageSize, stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), JSON.toJSONString(response));
		return response;
	}

	private GlobalResponse findChannelFundConfigCommon(Long configId, int oldOrNew) {
		log.info("资方模块接口，根据id获取资方配置, configId : {}", configId);
		if (configId == null) {
			return GlobalResponse.create(FundModuleResponse.ID_IS_EMPTY);
		}
		Stopwatch stopwatch = Stopwatch.createStarted();
		GlobalResponse response = null;
		if (oldOrNew == 1) {
			// 老接口
			response = fundModuleService.findChannelFundConfigById(configId);
		} else {
			response = fundModuleService.findChannelFundConfigNewById(configId);
		}
		log.info("资方模块接口, 根据id获取资方配置, configId : {} 耗时 : {}, response : {}", configId, stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), JSON.toJSONString(response));
		return response;
	}

	private GlobalResponse fundConfigConditions(Long configId){
		log.info("资方模块接口，根据id获取所有案例, configId : {}", configId);
		if (configId == null) {
			return GlobalResponse.create(FundModuleResponse.ID_IS_EMPTY);
		}
		Stopwatch stopwatch = Stopwatch.createStarted();
		GlobalResponse response = fundModuleService.getAllConditionsOfFundConfig(configId);
		log.info("资方模块接口,根据id获取所有案例, configId : {} 耗时 : {}, response : {}", configId, stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), JSON.toJSONString(response));
		return response;
	}

	private GlobalResponse simulation(List<FundConfigCondition> configConditions,Long configId){
		log.info("资方模块接口，根据案例进行空跑, configConditions : {}, configId:{}", configConditions,configId);
		if (CollectionUtils.isEmpty(configConditions)) {
			return GlobalResponse.create(FundModuleResponse.ID_IS_EMPTY);
		}
		Stopwatch stopwatch = Stopwatch.createStarted();
		GlobalResponse response = fundModuleService.simulationCases(configConditions,configId);
		log.info("资方模块接口,根据id获取所有案例, configConditions : {}, configId:{}, 耗时 : {}, response : {}", configConditions, configId,stopwatch.stop().elapsed(TimeUnit.MILLISECONDS), JSON.toJSONString(response));
		return response;
	}
}
