package com.yh.saas.platform.controller;

import java.util.List;

import org.activiti.engine.impl.util.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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 com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.winsea.svc.base.base.entity.CommonEmailConfig;
import com.winsea.svc.base.base.service.ICommonEmailConfigService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;

/**
 * <p>
 * 'winsea_platform.certificate_view' is not BASE TABLE 前端控制器
 * </p>
 *
 * @author ZhangMingYu
 * @since 2019-06-13
 */
@RestController
@RequestMapping("/emailConfig")
public class EmailConfigController {

	@SofaReference
	private ICommonEmailConfigService emailConfigService;

	/**
	 *
	 * @param emailConfig 邮件配置信息
	 * @return emailConfigID 邮件配置信息id
	 */
	@PostMapping("/api/create")
	public String create(@RequestBody CommonEmailConfig emailConfig) {
		emailConfig.setCompId(getCompId(emailConfig.getCompId()));
		return emailConfigService.create(emailConfig);
	}

	/**
	 *
	 * @param compId 公司id
	 * @param code   code
	 * @return 邮件配置信息
	 */
	@GetMapping("/query/emailConfig")
	public CommonEmailConfig emailConfig(@RequestParam String compId, @RequestParam String code) {
		List<CommonEmailConfig> emailConfigs = emailConfigService.selectList(new EntityWrapper<CommonEmailConfig>()
				.eq(CommonEmailConfig.QueryFields.COMP_ID, compId).eq(CommonEmailConfig.QueryFields.CODE, code));
		return CollectionUtil.isEmpty(emailConfigs) ? null : emailConfigs.get(0);
	}

	/**
	 *
	 * @param emailConfig 邮件配置信息
	 */
	@PostMapping("/api/update")
	public void update(@RequestBody CommonEmailConfig emailConfig) {
		emailConfigService.updateById(emailConfig);
	}

	/**
	 * 获取公司ID
	 *
	 * @param compId 公司ID
	 * @return 公司ID
	 */
	private String getCompId(String compId) {
		return !StringUtils.isEmpty(compId) ? compId : AuthSecurityUtils.getCurrentUserInfo().getCompId();
	}
}
