package com.yeejoin.amos.api.openapi.face.service;


import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.api.openapi.face.model.TmCylinderTagsModel;
import com.yeejoin.amos.api.openapi.face.orm.dao.TmCylinderTagsMapper;
import com.yeejoin.amos.api.openapi.face.orm.entity.TmCylinderTags;
import com.yeejoin.amos.api.openapi.listener.event.FileToBeDeleteEvent;
import com.yeejoin.amos.api.openapi.publisher.EventPublisher;
import com.yeejoin.amos.api.openapi.service.MyBaseServiceImpl;
import com.yeejoin.amos.api.openapi.util.FileDeleteUtil;
import com.yeejoin.amos.api.openapi.util.MultiFieldKey;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 
 * <pre>
 * 气瓶标签信息 服务类
 * </pre>
 *
 * @author gwb
 * @version $Id: TmCylinderTagsService.java, v 0.1 2021年9月30日 下午3:28:55 gwb Exp $
 */
@Component
public class TmCylinderTagsService extends MyBaseServiceImpl<TmCylinderTagsModel, TmCylinderTags, TmCylinderTagsMapper> {

	@Autowired
	private SyncCylinderDataService syncCylinderDataService;

	@Autowired
	private EventPublisher eventPublisher;

	@Transactional(rollbackFor = {java.lang.Exception.class})
	@DSTransactional
	public String createCylinderTag(List<TmCylinderTagsModel> model) {
		if (ValidationUtil.isEmpty(model))
			throw new BadRequest("气瓶标签信息为空.");
		String appId = getAppId();
		Date now = new Date();
		for (TmCylinderTagsModel cylinderTagsModel : model) {
			cylinderTagsModel.setSequenceNbr(null);
			cylinderTagsModel.setRecDate(now);
			cylinderTagsModel.setAppId(appId);
		}
		// 同步至气瓶业务库
		syncCylinderTag(model);

		List<TmCylinderTags> tmCylinderTagsList = Bean.toModels(model, TmCylinderTags.class);
		this.saveOrUpdateBatchByUniqueFields(
				tmCylinderTagsList,
				tmCylinderTags -> new LambdaQueryWrapper<TmCylinderTags>()
						.eq(TmCylinderTags::getAppId, tmCylinderTags.getAppId())
						.eq(TmCylinderTags::getSequenceCode, tmCylinderTags.getSequenceCode()),
				entity -> new MultiFieldKey(entity.getAppId(), entity.getSequenceCode()),
				"appId", "sequenceCode"
		);

		// 从数据库查询tmCylinderTagsList对应信息
		LambdaQueryWrapper<TmCylinderTags> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(TmCylinderTags::getAppId, tmCylinderTagsList.stream().map(TmCylinderTags::getAppId).collect(Collectors.toList()))
				.in(TmCylinderTags::getSequenceCode, tmCylinderTagsList.stream().map(TmCylinderTags::getSequenceCode).collect(Collectors.toList()));
		List<TmCylinderTags> oldList = this.baseMapper.selectList(queryWrapper);

		deleteOldFile(oldList);

		return "OK";
	}

	/**
	 * 删除旧的附件
	 * @param oldList 旧附件列表
	 */
	private void deleteOldFile(List<TmCylinderTags> oldList) {
		if (!ValidationUtil.isEmpty(oldList)) {
			List<String> fileUrlList = Lists.newArrayList();
			oldList.forEach(old -> {
				if (old.getGasCylinderStamp() != null) {
					fileUrlList.addAll(Arrays.asList(ValidationUtil.isEmpty(old.getGasCylinderStamp()) ? new String[0] : old.getGasCylinderStamp().split(",")));
				}
			});
			eventPublisher.publish(new FileToBeDeleteEvent(this, FileDeleteUtil.extractFileNames(fileUrlList)));
		}
	}

	/**
	 * 同步气瓶标签信息至气瓶服务
	 * @param model
	 */
	private void syncCylinderTag(List<TmCylinderTagsModel> model) {
		syncCylinderDataService.syncCylinderTag(model);
	}
}
