package org.springblade.flow.form.service.impl;

import org.springblade.flow.base.service.BillRuleService;
import org.springblade.flow.engine.util.ModelUtil;
import org.springblade.flow.exception.WorkFlowException;
import org.springblade.flow.form.entity.TravelApplyEntity;
import org.springblade.flow.form.mapper.TravelApplyMapper;
import org.springblade.flow.form.model.travelapply.TravelApplyForm;
import org.springblade.flow.form.service.TravelApplyService;
import org.springblade.flow.util.JsonUtil;
import org.springblade.flow.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 出差预支申请单
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月29日 上午9:18
 */
@Service
public class TravelApplyServiceImpl extends ServiceImpl<TravelApplyMapper, TravelApplyEntity>
		implements TravelApplyService {

	@Autowired
	private BillRuleService billRuleService;

	@Override
	public TravelApplyEntity getInfo(String id) {
		QueryWrapper<TravelApplyEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(TravelApplyEntity::getId, id);
		return this.getOne(queryWrapper);
	}

	@Override
	@Transactional(rollbackFor = WorkFlowException.class)
	public void save(String id, TravelApplyEntity entity) throws WorkFlowException {
		// 表单信息
		if (id == null) {
			entity.setId(RandomUtil.uuId());
			this.save(entity);
			billRuleService.useBillNumber("WF_TravelApplyNo");
		} else {
			entity.setId(id);
			this.updateById(entity);
		}
		// 流程信息
		ModelUtil.save(id, entity.getFlowId(), entity.getId(), entity.getFlowTitle(), entity.getFlowUrgent(),
				entity.getBillNo(), entity);
	}

	@Override
	@Transactional(rollbackFor = WorkFlowException.class)
	public void submit(String id, TravelApplyEntity entity) throws WorkFlowException {
		// 表单信息
		if (id == null) {
			entity.setId(RandomUtil.uuId());
			this.save(entity);
			billRuleService.useBillNumber("WF_TravelApplyNo");
		} else {
			entity.setId(id);
			this.updateById(entity);
		}
		// 流程信息
		ModelUtil.submit(id, entity.getFlowId(), entity.getId(), entity.getFlowTitle(), entity.getFlowUrgent(),
				entity.getBillNo(), entity, null);
	}

	@Override
	public void data(String id, String data) {
		TravelApplyForm travelApplyForm = JsonUtil.getJsonToBean(data, TravelApplyForm.class);
		TravelApplyEntity entity = JsonUtil.getJsonToBean(travelApplyForm, TravelApplyEntity.class);
		entity.setId(id);
		this.saveOrUpdate(entity);
	}
}
