package com.example.removetolocal.service.impl;

import com.example.removetolocal.newdevice.dao.DeviceLibraryDao;
import com.example.removetolocal.newdevice.dao.DeviceLogDao;
import com.example.removetolocal.newdevice.dao.PackingLibraryDao;
import com.example.removetolocal.newdevice.domin.DeviceLibrary;
import com.example.removetolocal.newdevice.domin.DeviceLog;
import com.example.removetolocal.newdevice.domin.PackingLibrary;
import com.example.removetolocal.newuser.dao.UnitsDao;
import com.example.removetolocal.newuser.dao.UserDao;
import com.example.removetolocal.olddevice.dao.*;
import com.example.removetolocal.olddevice.domin.DevCatalogEntity;
import com.example.removetolocal.olddevice.domin.DevModelEntity;
import com.example.removetolocal.olddevice.domin.DevOptlog;
import com.example.removetolocal.olddevice.domin.DevRecordEntity;
import com.example.removetolocal.oldentity.SysFile;
import com.example.removetolocal.oldentity.dao.SysFileDao;
import com.example.removetolocal.olduser.dao.SysCompanyDao;
import com.example.removetolocal.service.DeviceService;
import com.example.removetolocal.utils.StringSplitUtil;
import org.apache.logging.log4j.util.PropertySource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    PackingLibraryDao packingLibraryDao;
    @Autowired
    DeviceLibraryDao deviceLibraryDao;
    @Autowired
    DevCatalogDao devCatalogDao;
    @Autowired
    DevRecordDao devRecordDao;
    @Autowired
    UserDao userDao;
    @Autowired
    UnitsDao unitsDao;
    @Autowired
    DevModelDao devModelDao;
    @Autowired
    DevAcrossunitDao devAcrossunitDao;
    @Autowired
    SysCompanyDao sysCompanyDao;
    @Autowired
    DevOptlogDao devOptlogDao;
    @Autowired
    DeviceLogDao deviceLogDao;
    @Autowired
    SysFileDao sysFileDao;
    /**
     * 列装和装备库转换
     */
    @Override
    public void deviceChange() {
        //转换列装信息
        List<DevCatalogEntity> devCatalogEntities = devCatalogDao.findAll();
        devCatalogEntities.forEach(devCatalogEntity -> {
            PackingLibrary packingLibrary = new PackingLibrary();
            if (devCatalogEntity.getAnnex()!=null){
                List<Integer> ids = StringSplitUtil.fileIdSplit(devCatalogEntity.getAnnex());
                if (ids.size()>0){
                    SysFile sysFile = sysFileDao.findById(ids.get(0)).get();
                    packingLibrary.setFileName(sysFile.getFilename());
                    packingLibrary.setFileUrl(sysFile.getFilepath());
                }
            }
            if (devCatalogEntity.getCreatetime()!=null) {
                packingLibrary.setCreateTime(devCatalogEntity.getCreatetime());
            }
            else {
                packingLibrary.setCreateTime(devCatalogEntity.getUpdatetime());
            }
            packingLibrary.setUpdateTime(devCatalogEntity.getUpdatetime());
            if (devCatalogEntity.getCreateuser() != null) {
                if (userDao.findByOldCode(devCatalogEntity.getCreateuser()) != null || userDao.findByOldId(devCatalogEntity.getCreateuser()) != null) {
                    packingLibrary.setCreateUserId(userDao.findByOldCode(devCatalogEntity.getCreateuser()) == null ? userDao.findByOldId(devCatalogEntity.getCreateuser()).getUserId() : userDao.findByOldCode(devCatalogEntity.getCreateuser()).getUserId());
                }
            }
            if (devCatalogEntity.getUpdateuser() != null) {
                if (userDao.findByOldCode(devCatalogEntity.getUpdateuser()) != null || userDao.findByOldId(devCatalogEntity.getUpdateuser()) != null) {
                    packingLibrary.setUpdateUserId(userDao.findByOldCode(devCatalogEntity.getUpdateuser()) == null ? userDao.findByOldId(devCatalogEntity.getUpdateuser()).getUserId() : userDao.findByOldCode(devCatalogEntity.getUpdateuser()).getUserId());
                }
            }
            if (devCatalogEntity.getEndDate() != null && !"".equals(devCatalogEntity.getEndDate())) {
                packingLibrary.setExitTime(Timestamp.valueOf(devCatalogEntity.getEndDate() + " 00:00:00"));
            }
            if (devCatalogEntity.getPrice()!=null) {
                packingLibrary.setPrice(String.valueOf(devCatalogEntity.getPrice()));
            }
            if (devCatalogEntity.getCreateSup() != null && unitsDao.findByOldId(devCatalogEntity.getCreateSup()) != null) {
                packingLibrary.setCreateUnit(unitsDao.findByOldId(devCatalogEntity.getCreateSup()).getName());
            }
            packingLibrary.setProdUnit(devCatalogEntity.getProduction());
            packingLibrary.setStatus(devCatalogEntity.getStatus());
            packingLibrary.setNature(devCatalogEntity.getPackingProperty());
            if (devCatalogEntity.getStyle()!=null) {
                switch (devCatalogEntity.getStyle()) {
                    case 0:
                        packingLibrary.setType(9);
                    case 1:
                        packingLibrary.setType(7);
                        break;
                    case 2:
                        packingLibrary.setType(1);
                        break;
                    case 3:
                        packingLibrary.setType(2);
                        break;
                    case 4:
                        packingLibrary.setType(3);
                        break;
                    case 5:
                        packingLibrary.setType(8);
                        break;
                    case 6:
                        packingLibrary.setType(4);
                        break;
                    case 7:
                        packingLibrary.setType(5);
                        break;
                    case 8:
                        packingLibrary.setType(6);
                        break;
                    default:
                        packingLibrary.setType(devCatalogEntity.getStyle());
                        break;
                }
            }
            else {
                packingLibrary.setType(9);
            }
            if (devCatalogEntity.getVisibleRange()!=null) {
                switch (devCatalogEntity.getVisibleRange()) {
                    case 1:
                        packingLibrary.setInvisibleRange(4);
                        break;
                    case 2:
                        packingLibrary.setInvisibleRange(1);
                        break;
                    case 3:
                        packingLibrary.setInvisibleRange(2);
                        break;
                    case 4:
                        packingLibrary.setInvisibleRange(3);
                        break;
                    default:
                        packingLibrary.setInvisibleRange(devCatalogEntity.getVisibleRange());
                        break;
                }
            }
            if (devCatalogEntity.getMatchingArea()!=null) {
                switch (devCatalogEntity.getMatchingArea()) {
                    case 1:
                        packingLibrary.setMatchingRange(2);
                        break;
                    case 2:
                        packingLibrary.setMatchingRange(1);
                        break;
                    case 3:
                        packingLibrary.setMatchingRange(3);
                        break;
                    case 4:
                        packingLibrary.setMatchingRange(4);
                        break;
                    case 5:
                        packingLibrary.setMatchingRange(1);
                        break;
                    default:
                        packingLibrary.setMatchingRange(devCatalogEntity.getMatchingArea());
                        break;
                }
            }
            else {
                packingLibrary.setMatchingRange(4);
            }
            if (devCatalogEntity.getAppType()!=null) {
                switch (devCatalogEntity.getAppType()) {
                    case 4:
                        packingLibrary.setApplyType(5);
                        break;
                    case 5:
                        packingLibrary.setApplyType(4);
                        break;
                    default:
                        packingLibrary.setApplyType(devCatalogEntity.getAppType());
                        break;
                }
            }
            packingLibrary.setName(devCatalogEntity.getCode());
            if (devCatalogEntity.getSecretclass()!=null) {
                switch (devCatalogEntity.getSecretclass()) {
                    case 1:
                        packingLibrary.setSecretLevel(2);
                        break;
                    case 2:
                        packingLibrary.setSecretLevel(3);
                        break;
                    case 3:
                        packingLibrary.setSecretLevel(1);
                        break;
                    default:
                        packingLibrary.setSecretLevel(4);
                        break;
                }
            }
            else {
                packingLibrary.setSecretLevel(4);
            }
            packingLibrary.setModel(devCatalogEntity.getModel());
            if (devCatalogEntity.getEndDate() != null && !"".equals(devCatalogEntity.getEndDate())){
                packingLibrary.setPackingStatus(3);
            }
            else {
                if (devCatalogDao.findById(devCatalogEntity.getPid()).isPresent()){
                    DevCatalogEntity devCatalogEntity1 = devCatalogDao.findById(devCatalogEntity.getPid()).get();
                    if (devCatalogEntity1.getEndDate()!=null && !"".equals(devCatalogEntity1.getEndDate())){
                        packingLibrary.setPackingStatus(3);
                    }
                    else {
                        packingLibrary.setPackingStatus(2);
                    }
                }
                else {
                    packingLibrary.setPackingStatus(2);
                }
            }
            packingLibrary.setStyle(devCatalogEntity.getDevType());
            if (devCatalogEntity.getIsModelDir()==1) {
                packingLibrary.setIsRoot(1);
                packingLibrary.setMatchingRange(null);
                packingLibrary.setType(null);
                packingLibrary.setStyle(null);
                packingLibrary.setNature(null);
                packingLibrary.setCreateUnit(null);
                if (devModelDao.findAllByModel(devCatalogEntity.getModel()).size()>0) {
                    packingLibrary.setShowOrder(devModelDao.findAllByModel(devCatalogEntity.getModel()).stream()
                            .sorted(Comparator.comparing(DevModelEntity::getCreatetime).reversed())
                            .collect(Collectors.toList()).get(0).getShoworder());
                    if (packingLibrary.getShowOrder()==null){
                        packingLibrary.setShowOrder(99999);
                    }
                }
                else {
                    packingLibrary.setShowOrder(99999);
                }
            }
            else {
                packingLibrary.setIsRoot(0);
                packingLibrary.setShowOrder(99999);
                if (devCatalogDao.findById(devCatalogEntity.getPid()).get().getIsModelDir()==1){
                    packingLibrary.setIsPart(0);
                }
                else {
                    packingLibrary.setIsPart(1);
                }
            }
            packingLibrary.setOldId(devCatalogEntity.getId());
            packingLibraryDao.save(packingLibrary);
        });
        List<PackingLibrary> packingLibraries = packingLibraryDao.findAll();
        packingLibraries.forEach(packingLibrary -> {
            DevCatalogEntity devCatalogEntity = devCatalogDao.findById(packingLibrary.getOldId()).get();
            if (devCatalogEntity.getPid()!=null&&devCatalogEntity.getPid()>0){
                packingLibrary.setPartParentId(packingLibraryDao.findByOldId(devCatalogEntity.getPid()).getId());
                packingLibraryDao.save(packingLibrary);
            }
        });
        //转换装备信息
        List<DevRecordEntity> devRecordEntities = devRecordDao.findAll();
        devRecordEntities.forEach(devRecordEntity -> {
            //对应列装
            PackingLibrary packingLibrary = packingLibraryDao.findByOldId(devRecordEntity.getCatalogId());
            DeviceLibrary deviceLibrary = new DeviceLibrary();
            deviceLibrary.setCreateTime(devRecordEntity.getCreateTime());
            deviceLibrary.setUpdateTime(devRecordEntity.getUpdateTime());
            if (devRecordEntity.getCreateUser()!=null){
                if (userDao.findByOldCode(devRecordEntity.getCreateUser()) != null || userDao.findByOldId(devRecordEntity.getCreateUser()) != null) {
                    deviceLibrary.setCreateUserId(userDao.findByOldCode(devRecordEntity.getCreateUser()) == null ? userDao.findByOldId(devRecordEntity.getCreateUser()).getUserId() : userDao.findByOldCode(devRecordEntity.getCreateUser()).getUserId());
                }
            }
            if (devRecordEntity.getUpdateUser() != null) {
                if (userDao.findByOldCode(devRecordEntity.getUpdateUser()) != null || userDao.findByOldId(devRecordEntity.getUpdateUser()) != null) {
                    deviceLibrary.setUpdateUserId(userDao.findByOldCode(devRecordEntity.getUpdateUser()) == null ? userDao.findByOldId(devRecordEntity.getUpdateUser()).getUserId() : userDao.findByOldCode(devRecordEntity.getUpdateUser()).getUserId());
                }
            }
            deviceLibrary.setModel(devRecordEntity.getModel());
            deviceLibrary.setPackingId(packingLibrary.getId());
            deviceLibrary.setOldId(devRecordEntity.getId());
            deviceLibrary.setIsPart(packingLibrary.getIsPart());
            deviceLibrary.setSecretLevel(packingLibrary.getSecretLevel());
            deviceLibrary.setName(packingLibrary.getName());
            deviceLibrary.setSeqNumber(devRecordEntity.getSerNum());
            deviceLibrary.setProdNumber(devRecordEntity.getProNum());
//            deviceLibrary.setRfidCardId(devRecordEntity.getRfid());
//            deviceLibrary.setRfidSurfaceId(makeRfidNumber(packingLibrary.getType()==null?"0":String.valueOf(packingLibrary.getType()),devRecordEntity.getSerNum(),devRecordEntity.getProNum(),devRecordEntity.getModel()));
            deviceLibrary.setRfidSurfaceId(null);
            if (devRecordEntity.getWhereUnit()!=null){
                if (sysCompanyDao.findById(devRecordEntity.getWhereUnit()).isPresent()) {
                    deviceLibrary.setLocationUnit(sysCompanyDao.findById(devRecordEntity.getWhereUnit()).get().getCompanyName());
                }
                else {
                    deviceLibrary.setLocationUnit(devAcrossunitDao.findById(devRecordEntity.getWhereUnit()).get().getUnitname());
                }
            }
            if (devRecordEntity.getOwnUnit()!=null){
                if (sysCompanyDao.findById(devRecordEntity.getOwnUnit()).isPresent()) {
                    deviceLibrary.setOwnUnit(sysCompanyDao.findById(devRecordEntity.getOwnUnit()).get().getCompanyName());
                }
                else {
                    deviceLibrary.setOwnUnit(devAcrossunitDao.findById(devRecordEntity.getOwnUnit()).get().getUnitname());
                }
            }
            deviceLibrary.setMatchingRange(packingLibrary.getMatchingRange());
            deviceLibrary.setInvisibleRange(packingLibrary.getInvisibleRange());
            deviceLibrary.setType(packingLibrary.getType());
            if (devRecordEntity.getInstorageType()!=null) {
                switch (devRecordEntity.getInstorageType()) {
                    case 1:
                        deviceLibrary.setStorageType(2);
                        break;
                    case 2:
                        deviceLibrary.setStorageType(1);
                        break;
                    case 3:
                        deviceLibrary.setStorageType(3);
                        break;
                    case 4:
                        deviceLibrary.setStorageType(5);
                        break;
                    case 5:
                        deviceLibrary.setStorageType(4);
                        break;
                    default:
                        deviceLibrary.setStorageType(5);
                        break;
                }
            }
            if (devRecordEntity.getUseStatus()!=null) {
                switch (devRecordEntity.getUseStatus()) {
                    case 1:
                        deviceLibrary.setManageStatus(1);
                        break;
                    case 2:
                        deviceLibrary.setManageStatus(0);
                        break;
                    case 3:
                        deviceLibrary.setManageStatus(0);
                        break;
                    default:
                        deviceLibrary.setManageStatus(1);
                        break;
                }
            }
            if (devRecordEntity.getLifeStatus()!=null) {
                switch (devRecordEntity.getLifeStatus()) {
                    case 1:
                        deviceLibrary.setLifeStatus(2);
                        break;
                    case 2:
                        deviceLibrary.setLifeStatus(4);
                        break;
                    case 3:
                        deviceLibrary.setLifeStatus(7);
                        break;
                    case 4:
                        deviceLibrary.setLifeStatus(10);
                        break;
                    case 5:
                        deviceLibrary.setLifeStatus(12);
                        break;
                    case 6:
                        deviceLibrary.setLifeStatus(11);
                        break;
                    default:
                        deviceLibrary.setLifeStatus(1);
                        break;
                }
            }
            deviceLibrary.setLockStatus(devRecordEntity.getIslock());
            deviceLibrary.setDeleteTag(devRecordEntity.getIsDel());
            deviceLibraryDao.save(deviceLibrary);
        });
        List<DeviceLibrary> deviceLibraries = deviceLibraryDao.findAll();
        deviceLibraries.forEach(deviceLibrary -> {
            DevRecordEntity devRecordEntity = devRecordDao.findById(deviceLibrary.getOldId()).get();
            if (devRecordEntity.getPid()!=null&&devRecordEntity.getPid()>0){
                if (deviceLibraryDao.findByOldId(devRecordEntity.getPid())!=null) {
                    deviceLibrary.setPartParentId(deviceLibraryDao.findByOldId(devRecordEntity.getPid()).getId());
                }
                deviceLibraryDao.save(deviceLibrary);
            }
        });
        //装备日志
        List<DevOptlog> devOptlogs = devOptlogDao.findAll();
        devOptlogs.forEach(devOptlog -> {
            if (devOptlog.getIsValid()==1) {
                DeviceLog deviceLog = new DeviceLog();
                deviceLog.setCreateTime(devOptlog.getOptTime());
                if (devOptlog.getOptUser() != null) {
                    if (userDao.findByOldCode(devOptlog.getOptUser()) != null || userDao.findByOldId(devOptlog.getOptUser()) != null) {
                        deviceLog.setCreateUserId(userDao.findByOldCode(devOptlog.getOptUser()) == null ? userDao.findByOldId(devOptlog.getOptUser()).getUserId() : userDao.findByOldCode(devOptlog.getOptUser()).getUserId());
                    }
                }
                if (deviceLibraryDao.findByOldId(devOptlog.getDevId())!=null) {
                    deviceLog.setDeviceId(deviceLibraryDao.findByOldId(devOptlog.getDevId()).getId());
                }
                else {
                    deviceLog.setDeviceId(0);
                }
                deviceLog.setRemark(devOptlog.getOptcontent());
                deviceLog.setOldId(devOptlog.getId());
                deviceLog.setFileDetail("Ǵ");
                deviceLogDao.save(deviceLog);
            }
        });
    }

    /**
     * 列装排序
     */
    @Override
    public void sortPack() {
        List<PackingLibrary> packingLibraries = packingLibraryDao.findAllByIsRoot(1).stream().sorted(Comparator.nullsFirst(Comparator.comparing(PackingLibrary::getShowOrder))).collect(Collectors.toList());
        for (int i = 1;i<=packingLibraries.size();i++){
            PackingLibrary packingLibrary = packingLibraries.get(i-1);
            packingLibrary.setShowOrder(i);
            packingLibraryDao.save(packingLibrary);
        }
    }

    /**
     * 描述：生成装备的RFID表面号
     *
     * @param deviceType    装备类型 共10位
     * @param partType      配件类型 主体为0 共1位
     * @param deviceNumber  装备序列号 由用户填写
     * @param produceNumber 生产序列号 用户填写
     * @return 生成的RFID表面号
     */
    public String makeRfidNumber(String partType, String deviceNumber, String produceNumber, String deviceType) {
        //配件类型的长度只能为1
        if (partType.length() > 1) {
            throw new IllegalArgumentException("配件类型字段过长");
        }
        StringBuilder stringBuffer = new StringBuilder();
        if (deviceType.length() <= 10) {
            for (int i = 0; i < 10 - deviceType.length(); i++) {
                stringBuffer.append("0");
            }
            stringBuffer.append(deviceType);
        } else {
            stringBuffer.append(deviceType.substring(deviceType.length() - 10));
        }
        stringBuffer.append("p");
        stringBuffer.append(partType);

        if (deviceNumber.length() < 4) {
            for (int i = 0; i < 4 - deviceNumber.length(); i++) {
                stringBuffer.append("0");
            }
            stringBuffer.append(deviceNumber);
        } else {
            stringBuffer.append(deviceNumber.substring(deviceNumber.length() - 4));
        }

        if (produceNumber.length() < 4) {
            for (int i = 0; i < 4 - produceNumber.length(); i++) {
                stringBuffer.append("0");
            }
            stringBuffer.append(produceNumber);
        } else {
            stringBuffer.append(produceNumber.substring(produceNumber.length() - 4));
        }
        return stringBuffer.toString();
    }
}
