package com.njcn.device.device.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.biz.enums.DeviceResponseEnum;
import com.njcn.device.device.mapper.ProgramVersionMapper;
import com.njcn.device.device.mapper.VersionMapper;
import com.njcn.device.device.service.ProgramVersionService;
import com.njcn.device.pq.pojo.param.ProgramParam;
import com.njcn.device.pq.pojo.po.Version;
import com.njcn.device.pq.pojo.vo.ShowVersionVO;
import com.njcn.device.pq.pojo.vo.VersionVO;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @version 1.0.0
 * @author: chenchao
 * @date: 2022/05/19 16:39
 */
@Service
@AllArgsConstructor
public class ProgramVersionServiceImpl extends ServiceImpl<VersionMapper, Version> implements ProgramVersionService {

    private final ProgramVersionMapper programVersionMapper;

    private final VersionMapper versionMapper;

    @Override
    public Page<VersionVO> getProgramVersion(ProgramParam programParam) {
        Page<VersionVO> page = new Page<>();
        page.setSize(programParam.getPageSize());
        page.setCurrent(programParam.getPageNum());

        List<VersionVO> version = programVersionMapper.getVersion(programParam);
        if (!CollectionUtils.isEmpty(version)) {
            for (VersionVO vo: version) {
                if (vo.getVersionType().isEmpty()) {
                    vo.setVersionType("通用");
                }
            }
            //待分页数据总量
            page.setTotal(version.size());
            //分页总页数
            int pages = (int)Math.ceil(version.size()*1.0/programParam.getPageSize());
            page.setPages(pages);
            List<List<VersionVO>> partition = Lists.partition(version, programParam.getPageSize());
            List<VersionVO> versionVOS = partition.get(programParam.getPageNum() - 1);
            page.setRecords(versionVOS);
        }
        return page;
    }

    @Override
    public boolean addProgramVersion(String name, String protocol, LocalDate date, String devType, String remark, String versionType, String fileName,MultipartFile file) {
        check(null,name,false);
        Version version = new Version();
        version.setName(name);
        version.setProtocol(protocol);
        version.setDate(date);
        version.setDevType(devType);
        version.setRemark(remark);
        if (!versionType.equals("null")) {
            version.setVersionType(versionType);
        } else {
            version.setVersionType("");
        }
        if(ObjectUtil.isNotNull(file)){
            byte[] b = null, bytes = null;
            try {
                b = file.getBytes();

                InputStream in = file.getInputStream();
                bytes = FileCopyUtils.copyToByteArray(in);
            } catch (IOException e) {
                e.printStackTrace();
            }
            version.setFile(b);
        }
        version.setFileName(fileName);
        version.setVersionFlag(DataStateEnum.ENABLE.getCode());
        version.setState(DataStateEnum.ENABLE.getCode());
        version.setCreateBy(RequestUtil.getUserIndex());
        version.setCreateTime(LocalDateTime.now());
        version.setUpdateBy(RequestUtil.getUserIndex());
        version.setUpdateTime(LocalDateTime.now());
        versionMapper.insert(version);
        return true;
    }

    @Override
    public boolean getProgramVersionById(String id) {
        ShowVersionVO showVersionVO = programVersionMapper.getProgramVersionById(id);
        return !Objects.isNull(showVersionVO);
    }

    @Override
    public boolean updateProgramVersion(String id, String name, String protocol, LocalDate date, String devType, String remark, String versionType, String fileName,MultipartFile file) {
        check(id,name,true);
        Version version = new Version();
        version.setId(id);
        version.setName(name);
        version.setProtocol(protocol);
        version.setDate(date);
        version.setDevType(devType);
        version.setRemark(remark);
        if (!versionType.equals("null")) {
            version.setVersionType(versionType);
        } else {
            version.setVersionType("");
        }
        if(ObjectUtil.isNotNull(file)){
            byte[] b = null;
            try {
                b = file.getBytes();
            } catch (IOException e) {
                e.printStackTrace();
            }
            version.setFile(b);
        }
        version.setFileName(fileName);
        version.setUpdateBy(RequestUtil.getUserIndex());
        version.setUpdateTime(LocalDateTime.now());
        versionMapper.updateById(version);
        return true;
    }


    @Override
    public boolean updateVersionFlag(String id, Integer flag) {
        Version version = new Version();
        version.setId(id);
        version.setVersionFlag(flag);
        versionMapper.updateById(version);
        return true;
    }

    @Override
    public boolean delProgramVersion(String id) {
        programVersionMapper.updateVersionState(id);
        return true;
    }

    @Override
    public List<VersionVO> getVersion(ProgramParam.Version param) {
        return versionMapper.selectVersion(param);
    }


    private Boolean judgeFileType(String subffix) {
        boolean result = false;
        if ("bin".equals(subffix)) {
            result = true;
        }
        return result;
    }

    /**
     * 校验参数，检查是否存在相同编码的字典类型
     */
    private void check(String id, String name, boolean isExcludeSelf) {
        LambdaQueryWrapper<Version> nodeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        nodeLambdaQueryWrapper
                .eq(Version::getName, name)
                .eq(Version::getState, DataStateEnum.ENABLE.getCode());
        //更新的时候，需排除当前记录
        if (isExcludeSelf) {
            nodeLambdaQueryWrapper.ne(Version::getId, id);
        }
        int countByAccount = this.count(nodeLambdaQueryWrapper);
        //大于等于1个则表示重复
        if (countByAccount >= 1) {
            throw new BusinessException(DeviceResponseEnum.FLOW_SAME_NAME);
        }
    }

}
