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.TmCylinderFillingExamineModel;
import com.yeejoin.amos.api.openapi.face.orm.dao.TmCylinderFillingExamineMapper;
import com.yeejoin.amos.api.openapi.face.orm.entity.TmCylinderFillingExamine;
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: ElevatorService.java, v 0.1 2021年9月30日 下午3:28:55 gwb Exp $
 */
@Component
public class TmCylinderFillingExamineService extends MyBaseServiceImpl<TmCylinderFillingExamineModel, TmCylinderFillingExamine, TmCylinderFillingExamineMapper> {

    @Autowired
    private SyncCylinderDataService syncCylinderDataService;

    @Autowired
    private EventPublisher eventPublisher;

    @DSTransactional
    @Transactional(rollbackFor = Exception.class)
    public String createCylinderFillingExamine(List<TmCylinderFillingExamineModel> model) {
        if (ValidationUtil.isEmpty(model))
            throw new BadRequest("液化气体气瓶充装信息审核为空.");
        for (TmCylinderFillingExamineModel cylinderFillingExamineModel : model) {
            cylinderFillingExamineModel.setRecDate(new Date());
            cylinderFillingExamineModel.setAppId(getAppId());
        }
        // 同步至气瓶业务库
        syncCylinderFillingExamine(model);

        List<TmCylinderFillingExamine> tmCylinderFillingExamineList = Bean.toModels(model, TmCylinderFillingExamine.class);
        this.saveOrUpdateBatchByUniqueFields(
                tmCylinderFillingExamineList,
                tmCylinderFillingExamine -> new LambdaQueryWrapper<TmCylinderFillingExamine>()
                        .eq(TmCylinderFillingExamine::getAppId, getAppId())
                        .eq(TmCylinderFillingExamine::getSequenceCode, tmCylinderFillingExamine.getSequenceCode())
                        .eq(TmCylinderFillingExamine::getFillingExamineId, tmCylinderFillingExamine.getFillingExamineId()),
                entity -> new MultiFieldKey(entity.getAppId(), entity.getSequenceCode(), entity.getFillingExamineId()),
                "appId",
                "sequenceCode",
                "fillingExamineId");

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

        deleteOldFile(oldList);

        return "OK";
    }

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

    private void syncCylinderFillingExamine(List<TmCylinderFillingExamineModel> model) {
        syncCylinderDataService.syncCylinderFillingExamine(model);
    }
}
