package cn.com.poc.thirdparty.resource.demand.ai.plugin_business.rest.impl;
import java.util.Date;

import java.util.LinkedList;
import java.util.List;
import javax.annotation.Resource;

import cn.com.poc.common.utils.Assert;
import cn.com.poc.common.utils.DateUtils;
import cn.com.poc.common.utils.RandomCodeUtils;
import cn.com.poc.common.utils.StringUtils;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.frame.entity.EmailSenderEntity;
import cn.com.yict.framemax.frame.service.EmailSenderService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import cn.com.poc.thirdparty.resource.demand.ai.plugin_business.rest.BizPluginBusinessRest;
import cn.com.poc.thirdparty.resource.demand.ai.plugin_business.service.BizPluginBusinessService;
import cn.com.poc.thirdparty.resource.demand.ai.plugin_business.dto.BizPluginBusinessDto;
import cn.com.poc.thirdparty.resource.demand.ai.plugin_business.entity.BizPluginBusinessEntity;

@Component
public class BizPluginBusinessRestImpl implements BizPluginBusinessRest {
   
   	@Resource
    private BizPluginBusinessService service;

   	@Resource
    private EmailSenderService emailSenderService;


	@Override
	public void submitTravelForm(BizPluginBusinessDto bizPluginBusinessDto) throws Exception {
		Assert.notBlank(bizPluginBusinessDto.getFormType());
		Assert.notNull(bizPluginBusinessDto.getFromDataDto());

		String formData = cn.com.yict.framemax.core.utils.JSON.serialize(bizPluginBusinessDto.getFromDataDto());
		BizPluginBusinessEntity entity = new BizPluginBusinessEntity();
		entity.setFormNo(String.valueOf(new Date().getTime()));
		entity.setFormData(formData);
		entity.setFormType(bizPluginBusinessDto.getFormType());
		BizPluginBusinessEntity save = service.save(entity);


		JSONObject jsonObject = JSON.parseObject(formData);
		String email = jsonObject.getString("email");
		if (StringUtils.isBlank(email)) {
			return;
		}
		EmailSenderEntity emailSenderEntity = new EmailSenderEntity();
		emailSenderEntity.setBody("您提交的出差申请已成功受理！");
		emailSenderEntity.setSubject("出差申请回执");
		List<String> list = new LinkedList<>();
		list.add(email);
		emailSenderEntity.setTo(list); //接收者
		try {
			// 如果成功发送，则把验证码存入redis当中，并设置15分钟的过期时间
			emailSenderService.sendMail(emailSenderEntity, null);
		} catch (Exception e) {
			throw new I18nMessageException("exception/verification.code.sending.failed.please.try.again");
		}
	}
}