package com.tykj.dev.device.decommissioning.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tykj.dev.blockcha.subject.service.BlockChainUtil;
import com.tykj.dev.device.decommissioning.entity.DeviceDecommissioningDetail;
import com.tykj.dev.device.decommissioning.repository.DeviceDecommissioningDetailDao;
import com.tykj.dev.device.decommissioning.service.DeviceDecommissioningDetailService;
import com.tykj.dev.device.file.service.FilesUtil;
import com.tykj.dev.device.library.repository.DeviceLibraryDao;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.library.subject.vo.ScriptSaveVo;
import com.tykj.dev.misc.exception.ApiException;
import com.tykj.dev.misc.utils.DeviceSeqUtil;
import com.tykj.dev.misc.utils.JacksonUtil;
import com.tykj.dev.misc.utils.StringSplitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName DeviceDecommissioningDetailServiceImpl.java
 * @Description TODO
 * @createTime 2021年03月29日 16:18:00
 */
@Service
@Slf4j
@SuppressWarnings("ALL")
public class DeviceDecommissioningDetailServiceImpl implements DeviceDecommissioningDetailService {
    @Autowired
    DeviceDecommissioningDetailDao deviceDecommissioningDetailDao;

    @Autowired
    DeviceLibraryDao deviceLibraryDao;

    @Autowired
    BlockChainUtil blockChainUtil;

    @Override
    public DeviceDecommissioningDetail saveDeviceDecommissioningDetail(DeviceDecommissioningDetail deviceDecommissioningDetail) {
//        log.info("[清退] 详情添加成功");
        CompletableFuture.runAsync(()-> {
            if (deviceDecommissioningDetail.getRecordId() == null || deviceDecommissioningDetail.getRecordId().equals("")) {
                deviceDecommissioningDetail.setRecordId(blockChainUtil.sendText(1000, JacksonUtil.toJSon(deviceDecommissioningDetail)).getData().getRecordID());
                deviceDecommissioningDetailDao.save(deviceDecommissioningDetail);
                log.info("[退役]上链数据时间本次");
            } else {
                deviceDecommissioningDetail.setRecordId(blockChainUtil.appendText(JacksonUtil.toJSon(deviceDecommissioningDetail), deviceDecommissioningDetail.getRecordId()).getData().getRecordID());
                deviceDecommissioningDetailDao.save(deviceDecommissioningDetail);
            }
        });
        return deviceDecommissioningDetailDao.save(deviceDecommissioningDetail);
    }

    @Override
    public DeviceDecommissioningDetail findDeviceDecommissioningDetail(Integer decommissioningId) {
        Optional<DeviceDecommissioningDetail> optional = deviceDecommissioningDetailDao.findById(decommissioningId);
        if (optional.isPresent()){
            DeviceDecommissioningDetail deviceDecommissioningDetail=optional.get();
            deviceDecommissioningDetail.setScripts(JacksonUtil.readValue(deviceDecommissioningDetail.getScriptJson(), new TypeReference<List<ScriptSaveVo>>() {
            }));
            deviceDecommissioningDetail.setBillFiles(FilesUtil.stringFileToList(deviceDecommissioningDetail.getBillFile()));
            deviceDecommissioningDetail.setOutboundFiles(FilesUtil.stringFileToList(deviceDecommissioningDetail.getOutboundFile()));
            deviceDecommissioningDetail.setInFiles(FilesUtil.stringFileToList(deviceDecommissioningDetail.getInFile()));
            deviceDecommissioningDetail.setReplyFileList(FilesUtil.stringFileToList(deviceDecommissioningDetail.getReplyFiles()));
            deviceDecommissioningDetail.setApplyFileList(FilesUtil.stringFileToList(deviceDecommissioningDetail.getApplyFiles()));
            List<String> seqNumbers=new ArrayList<>();
            JacksonUtil.readValue(deviceDecommissioningDetail.getScriptJson(), new TypeReference<List<ScriptSaveVo>>() {}).forEach(
                    scriptSaveVo -> {
                        if (scriptSaveVo.getSeqNumber()!=null){
                            seqNumbers.addAll(DeviceSeqUtil.selectDeviceSeqs(scriptSaveVo.getSeqNumber()));
                        }
                    }
            );
            deviceDecommissioningDetail.setDeviceLibraryEntities(deviceLibraryDao.findAllBySeqNumberIn(seqNumbers).stream().map(DeviceLibrary::setConfigName).collect(Collectors.toList()));
            return deviceDecommissioningDetail;
        }else {
            log.info("[退役] 详情查看错误，id没有找到{}",decommissioningId);
            throw new ApiException(ResponseEntity.status(500).body("退役详情id没有找到:"+decommissioningId));
        }
    }

    @Override
    public DeviceDecommissioningDetail findDeviceDecommissioningDetailNoDev(Integer decommissioningId) {
        Optional<DeviceDecommissioningDetail> optional = deviceDecommissioningDetailDao.findById(decommissioningId);
        if (optional.isPresent()){
            return optional.get();
        }else {
            log.info("[退役] 详情查看错误，id没有找到{}",decommissioningId);
            throw new ApiException(ResponseEntity.status(500).body("退役详情id没有找到:"+decommissioningId));
        }
    }

    @Override
    public List<DeviceDecommissioningDetail> findAll() {
        return deviceDecommissioningDetailDao.findAll();
    }

    @Override
    public DeviceDecommissioningDetail findApplyId(Integer applyId) {
        return deviceDecommissioningDetailDao.findByApplyId(applyId);
    }

    private List<DeviceLibrary> findInvoleDevice(String involeDevice){
        if (involeDevice!=null && !involeDevice.equals(",") ) {
            List<String> idStringList = Arrays.asList(involeDevice.split(","));
            List<String> idListString = idStringList.stream().filter(list2->!list2.equals("")).collect(Collectors.toList());
            System.out.println(idListString);
            List<Integer> devIds = idListString.stream().map(Integer::parseInt).collect(Collectors.toList());
            return deviceLibraryDao.getDeviceLibraryEntitiesByIdIn(devIds).stream().map(DeviceLibrary::setConfigName).collect(Collectors.toList());
        }else {
            return new ArrayList<>();
        }
    }
}
