package com.usky.iot.service.impl;

import com.alibaba.nacos.common.utils.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.iot.domain.DmpSoftwareSubpackage;
import com.usky.iot.domain.DmpSoftwareUpgrade;
import com.usky.iot.mapper.DmpSoftwareUpgradeMapper;
import com.usky.iot.service.DmpSoftwareSubpackageService;
import com.usky.iot.service.DmpSoftwareUpgradeService;
import com.usky.iot.service.vo.DmpSoftwareUpgradeRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 软件升级信息表 服务实现类
 * </p>
 *
 * @author ya
 * @since 2022-10-08
 */
@Service
public class DmpSoftwareUpgradeServiceImpl extends AbstractCrudService<DmpSoftwareUpgradeMapper, DmpSoftwareUpgrade> implements DmpSoftwareUpgradeService {

    @Autowired
    private DmpSoftwareSubpackageService dmpSoftwareSubpackageService;

    @Override
    public void add(DmpSoftwareUpgrade dmpProductInfo, MultipartFile file) {
        dmpProductInfo.setPackageLength((int)file.getSize());
        try {
            dmpProductInfo.setCheckCode(MD5Utils.md5Hex(file.getBytes()));
        } catch (Exception e) {
            throw new BusinessException("获取文件失败");
        }
        this.save(dmpProductInfo);
        List<DmpSoftwareSubpackage> dmpSoftwareSubpackages = cutFile(dmpProductInfo, file, 1024);
        dmpSoftwareSubpackageService.saveBatch(dmpSoftwareSubpackages);
    }

    @Override
    public CommonPage<DmpSoftwareUpgrade> page(DmpSoftwareUpgradeRequest dsRequest) {
        IPage<DmpSoftwareUpgrade> page = new Page<>(dsRequest.getCurrent(), dsRequest.getSize());
        LambdaQueryWrapper<DmpSoftwareUpgrade> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery
                .like(StringUtils.isNotBlank(dsRequest.getName()),DmpSoftwareUpgrade::getVersionName,dsRequest.getName())
                .orderByDesc(DmpSoftwareUpgrade::getId);

        page = this.page(page,lambdaQuery);
        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getCurrent(),page.getSize());
    }


    private static List<DmpSoftwareSubpackage> cutFile(DmpSoftwareUpgrade dmpSoftwareUpgrade,MultipartFile multipartFile, int num) {
        InputStream inputStream = null;
        List<DmpSoftwareSubpackage> list = new ArrayList<>();
        try {
            inputStream = new BufferedInputStream(multipartFile.getInputStream());
            //创建规定大小的byte数组
            byte[] b = new byte[num];
            //name为以后的小文件命名做准备
            int name = 0;
            //遍历将大文件读入byte数组中，当byte数组读满后写入对应的小文件中
            int len = 0;
            while ((len = inputStream.read(b)) != -1) {
                int chk = 0x0000;
                for(int i=0;i<len;i++){
                    chk += b[i]&0x00ff;
                }
                DmpSoftwareSubpackage dmpSoftwareSubpackage = new DmpSoftwareSubpackage();
                dmpSoftwareSubpackage.setUpgradeId(dmpSoftwareUpgrade.getId());
                dmpSoftwareSubpackage.setSubpackageNumber(name);
                dmpSoftwareSubpackage.setApplyPackage(Arrays.copyOf(b, len));
                dmpSoftwareSubpackage.setSubpackageLength(String.valueOf(len));
                dmpSoftwareSubpackage.setCheckCode(String.format("%04x", chk& 0x0000ffff));
                list.add(dmpSoftwareSubpackage);
                name++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
