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.TmCylinderUnitModel;
import com.yeejoin.amos.api.openapi.face.orm.dao.TmCylinderUnitMapper;
import com.yeejoin.amos.api.openapi.face.orm.entity.TmCylinderUnit;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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: ElevatorService.java, v 0.1 2021年9月30日 下午3:28:55 gwb Exp $
 */
@Component
@Slf4j
public class TmCylinderUnitService extends MyBaseServiceImpl<TmCylinderUnitModel, TmCylinderUnit, TmCylinderUnitMapper> {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SyncCylinderDataService syncCylinderDataService;

    @Autowired
    private EventPublisher eventPublisher;

    @DSTransactional
    @Transactional(rollbackFor = {java.lang.Exception.class})
    public String createCylinderUnit(List<TmCylinderUnitModel> model) {
        if (ValidationUtil.isEmpty(model))
            throw new BadRequest("气瓶企业信息数据为空.");
        String appId = getAppId();
        Date now = new Date();
        for (TmCylinderUnitModel cylinderUnitModel : model) {
            cylinderUnitModel.setSequenceNbr(null);
            cylinderUnitModel.setRecDate(now);
            cylinderUnitModel.setAppId(appId);
        }
        // 同步到业务库
        syncCylinderUnitModel(model);
        List<TmCylinderUnit> tmCylinderUnitList = Bean.toModels(model, TmCylinderUnit.class);

        this.saveOrUpdateBatchByUniqueFields(
                tmCylinderUnitList,
                tmCylinderUnit -> new LambdaQueryWrapper<TmCylinderUnit>()
                        .eq(TmCylinderUnit::getAppId, tmCylinderUnit.getAppId()),
                entity -> new MultiFieldKey(entity.getAppId()),
                "appId");

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

        deleteOldFile(oldList);
        return "OK";
    }

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

    /**
     * 同步气站信息至气瓶服务
     * @param model
     */
    private void syncCylinderUnitModel(List<TmCylinderUnitModel> model) {
        syncCylinderDataService.syncCylinderUnit(model);
    }
}
