package com.product.data.sync.controller;

import com.product.core.config.CoreConst;
import com.product.core.controller.support.AbstractBaseController;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.RequestParameterEntity;
import com.product.core.exception.BaseException;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.data.sync.config.CmnConst;
import com.product.data.sync.config.SystemCode;
import com.product.data.sync.service.FeDataDSService;
import com.product.data.sync.service.SyFeDataService;
import com.product.module.sys.version.ApiVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/api/syncfe")
public class SyFeDataController extends AbstractBaseController {
	@Autowired
	public SyFeDataService syFeDataService;

	@Autowired
	public FeDataDSService feDataDSService;

	@RequestMapping(value = "/sy-oracle-fun/{version}", method = RequestMethod.POST)
	public String saveSyncConfig(HttpServletRequest request) {
		try {
			//鑾峰彇鍙傛暟
			FieldSetEntity fse = null;
			Object bean = request.getAttribute(CoreConst.API_POST_REQUEST_DATA);
			if (bean != null) {
				RequestParameterEntity reqp = (RequestParameterEntity) bean;
				fse = reqp.getFormData();
			}
			//鍒ゆ柇鍙傛暟鏄惁涓虹┖
			if (bean == null || fse == null) {
				SpringMVCContextHolder.getSystemLogger().error(SystemCode.SYSTEM_FORM_NODATA.getValue(), SystemCode.SYSTEM_FORM_NODATA.getText());
				return this.error(SystemCode.SYSTEM_FORM_NODATA.getValue(), SystemCode.SYSTEM_FORM_NODATA.getText());
			}
			//鍒ゆ柇琛ㄥ悕鏄惁姝e父
			if (!CmnConst.PRODUCT_SYS_FUNCTIONS.equals(fse.getTableName())) {
				SpringMVCContextHolder.getSystemLogger().error(SystemCode.SYSTEM_TABLE_NODATA.getValue(), SystemCode.SYSTEM_TABLE_NODATA.getText());
				return this.error(SystemCode.SYSTEM_TABLE_NODATA.getValue(), SystemCode.SYSTEM_TABLE_NODATA.getText());
			}
			String uuid = syFeDataService.saveSyncFedata(fse);

			return OK();
		} catch (BaseException e) {
			e.printStackTrace();
			SpringMVCContextHolder.getSystemLogger().error(e);
			return this.error(e);
		} catch (Exception e) {
			SpringMVCContextHolder.getSystemLogger().error(e);
			return this.error(SystemCode.SYSTEM_SAVE_SYNC_CONFIG_FAIL.getValue(), SystemCode.SYSTEM_SAVE_SYNC_CONFIG_FAIL.getText());
		}
	}


	@PostMapping("/flow-sync/{version}")
	@ApiVersion(1)
	public String flowSync() {
		try {
			syFeDataService.flowPermission();
			return OK();
		} catch (Exception e) {
			e.printStackTrace();
			return error(new BaseException(e));
		}
	}

}