package com.quantgroup.asset.distribution.controller;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import com.quantgroup.asset.distribution.service.asset.IBizAssetOrderService;
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.enums.response.AssetResponse;
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.asset.IAssetService;
import com.quantgroup.asset.distribution.util.UUIDUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 资产入库Controller
 * @author liwenbin
 *
 */
@RestController
@Slf4j
@RequestMapping("/biz")
public class AssetController {
	
	@Autowired
	private IAssetService assetService;
	@Autowired
	private IAlarmService alarmService;
	@Autowired
	private IBizAssetOrderService bizAssetOrderService;
	
	@RequestMapping("/asset_in")
	public GlobalResponse assetsIn(AssetForm assetForm, HttpServletRequest request) {
		Stopwatch stopwatch = Stopwatch.createStarted();
		assetForm.setAssetNo(UUIDUtil.getAssetNo());
		String authKey = request.getHeader("as_auth_key");
		log.info("资产入库分发开始, assetForm : {}, authKey : {}", JSON.toJSONString(assetForm), authKey);
		GlobalResponse response = assetService.checkAssetForm(assetForm);
		if (response.getCode() != 0) { 
			log.info("资产入库入参错误, assetForm : {}, authKey : {}, 耗时 : {}", JSON.toJSONString(assetForm), authKey, stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
			alarmService.dingtalkAlarm("Warn", "资产入库参数校验失败", "bizChannel : " + assetForm.getBizChannel()
				+ " , bizType : " + assetForm.getBizType() + " , bizNo : " + assetForm.getBizNo()
				+ " , assetNo : " + assetForm.getAssetNo() + " , uuid : " + assetForm.getUuid()
				+ " , code : " + response.getCode() + " , errorMsg : " + response.getMsg());
			return response; 
		}
		// 保存资产分发订单
		bizAssetOrderService.saveAssetOrder(assetForm);

		assetService.assetsIn(assetForm);
		log.info("资产入库分发结束, assetForm : {}, authKey : {}, response : {}, 耗时 : {}", JSON.toJSONString(assetForm), authKey, JSON.toJSONString(response), stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
		return GlobalResponse.create(AssetResponse.SUCCESS);
	}
}
