package com.bonus.canteen.core.device.manage.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bonus.canteen.core.device.manage.dto.BasicsAppUpdateDTO;
import com.bonus.canteen.core.device.manage.mapper.BasicsAppUpdateMapper;
import com.bonus.canteen.core.device.manage.model.BasicsAppUpdate;
import com.bonus.common.houqin.utils.id.Id;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipFile;

@Service
public class BasicsAppUpdateService {
   private static final Logger log = LoggerFactory.getLogger(BasicsAppUpdateService.class);
   @Autowired
   private BasicsAppUpdateMapper basicsAppUpdateMapper;
//   @Autowired
//   private SysFileService sysFileService;
//   @Autowired
//   private DeviceUpdateInSystemService deviceUpdateInSystemService;

   public BasicsAppUpdate appNowVersion(Integer sourceType, String deviceModel) {
      LambdaQueryWrapper<BasicsAppUpdate> queryWrapper = Wrappers.lambdaQuery(BasicsAppUpdate.class)
              .eq(BasicsAppUpdate::getSourceType, sourceType);
      if (deviceModel == null) {
         queryWrapper.isNull(BasicsAppUpdate::getDeviceModel);
      } else {
         queryWrapper.eq(BasicsAppUpdate::getDeviceModel, deviceModel);
      }

      return this.basicsAppUpdateMapper.selectOne(queryWrapper);
   }

   public void saveAppVersion(BasicsAppUpdateDTO basicsAppUpdateDto) {
      BasicsAppUpdate currentAppVersion = this.basicsAppUpdateMapper.selectOne(Wrappers.lambdaQuery(BasicsAppUpdate.class)
              .eq(BasicsAppUpdate::getSourceType, basicsAppUpdateDto.getSourceType())
              .eq(StrUtil.isNotEmpty(basicsAppUpdateDto.getDeviceModel()),
                      BasicsAppUpdate::getDeviceModel,
                      basicsAppUpdateDto.getDeviceModel()));
      if (currentAppVersion != null) {
         currentAppVersion.setAppVersionCode(basicsAppUpdateDto.getAppVersionCode());
         currentAppVersion.setAppVersionName(basicsAppUpdateDto.getAppVersionName());
         currentAppVersion.setAppUpdateUrl(basicsAppUpdateDto.getAppUpdateUrl());
         this.basicsAppUpdateMapper.updateById(currentAppVersion);
      } else {
         basicsAppUpdateDto.setId(Id.next());
         this.basicsAppUpdateMapper.insert(basicsAppUpdateDto.convertToEntity());
      }

   }

//   public ApkInfo uploadAppVersion(MultipartFile file, String uploadKey, Integer deviceType, String scene) {
//      Assert.notBlank(file.getOriginalFilename(), () -> {
//         return new LeException("文件名异常");
//      });
//      String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
//      if (!FileNameSuffixEnum.getAllFileNameList().contains(suffix.toUpperCase())) {
//         throw new LeException("接收参数错误,请上传正确的文件格式");
//      } else if (StringUtils.isEmpty(uploadKey)) {
//         throw new LeException("接收参数错误,请重试 ^_^");
//      } else {
//         List<String> uploadKeyList = FileUploadSourceEnum.getAllEnumsKeyList();
//         if (!uploadKeyList.contains(uploadKey)) {
//            throw new LeException("目前只支持指定文件路径的上传,请重试 ^_^");
//         } else {
//            SysFileUploadVO sysFileUploadVO = this.sysFileService.uploadFile(file, uploadKey);
//
//            try {
//               ZipFile zipFile = this.transferToFile(file);
//               ZipEntry entry = zipFile.getEntry("AndroidManifest.xml");
//               if (entry == null) {
//                  throw new LeException("文件格式错误,请上传正确的apk文件");
//               } else {
//                  InputStream inputStream = zipFile.getInputStream(entry);
//                  byte[] data = readAll(inputStream);
//                  ByteBuffer buffer = ByteBuffer.wrap(data);
//                  ApkInfo apkInfo = new ApkInfo();
//                  BinaryXmlParser bindParser = new BinaryXmlParser(buffer, apkInfo);
//                  bindParser.parse();
//                  DeviceUpdateInSystem deviceUpdateInSystem = new DeviceUpdateInSystem();
//                  deviceUpdateInSystem.setDeviceType(deviceType);
//                  deviceUpdateInSystem.setScene(scene);
//                  deviceUpdateInSystem.setVersionCode(apkInfo.getVersionCode());
//                  deviceUpdateInSystem.setVersionName(apkInfo.getVersionName());
//                  deviceUpdateInSystem.setPackageName(apkInfo.getPackageName());
//                  deviceUpdateInSystem.setAppUpdateUrl(sysFileUploadVO.getFileNameUrl());
//                  this.deviceUpdateInSystemService.saveDeviceUpdateInSystem(deviceUpdateInSystem);
//                  return apkInfo;
//               }
//            } catch (IOException var16) {
//               throw new RuntimeException(var16);
//            }
//         }
//      }
//   }

   public static byte[] readAll(InputStream in) throws IOException {
      byte[] buf = new byte[8192];
      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      byte[] var4;
      try {
         int len;
         while((len = in.read(buf)) != -1) {
            bos.write(buf, 0, len);
         }

         var4 = bos.toByteArray();
      } catch (Throwable var6) {
         try {
            bos.close();
         } catch (Throwable var5) {
            var6.addSuppressed(var5);
         }

         throw var6;
      }

      bos.close();
      return var4;
   }

   private ZipFile transferToFile(MultipartFile multipartFile) {
      File tempFile = null;

      try {
         tempFile = File.createTempFile(Id.nextString(), ".apk");
         multipartFile.transferTo(tempFile);
         ZipFile zipFile = new ZipFile(tempFile, StandardCharsets.UTF_8);
         ZipFile var4 = zipFile;
         return var4;
      } catch (Exception var14) {
         log.error("失败", var14);
      } finally {
         try {
            if (tempFile != null && tempFile.exists() && tempFile.delete()) {
               log.info("删除临时文件： {} ", tempFile);
            }
         } catch (Exception var13) {
            log.error("删除文件失败", var13);
         }

      }

      return null;
   }
}
