package com.njcn.product.cnzutai.zutai.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.product.cnzutai.zutai.service.CsPagePOService;
import com.njcn.product.cnzutai.zutai.mapper.CsConfigurationMapper;
import com.njcn.product.cnzutai.zutai.mapper.CsPagePOMapper;
import com.njcn.product.cnzutai.zutai.pojo.param.CsPageParm;
import com.njcn.product.cnzutai.zutai.pojo.po.CsConfigurationPO;
import com.njcn.product.cnzutai.zutai.pojo.po.CsPagePO;
import com.njcn.product.cnzutai.zutai.pojo.vo.CsPageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
 *
 * Description:
 * Date: 2023/5/31  14:31【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class CsPagePOServiceImpl extends ServiceImpl<CsPagePOMapper, CsPagePO> implements CsPagePOService {
    private final FileStorageUtil fileStorageUtil;
    private final CsConfigurationMapper csConfigurationMapper;
   // private final UserFeignClient userFeignClient;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean add(CsPageParm csPageParm) {
        QueryWrapper<CsPagePO> csPagePOQueryWrapper = new QueryWrapper<>();
        String pid = csPageParm.getPid();
        csPagePOQueryWrapper.eq("pid",pid);
        List<CsPagePO> csPagePOList = this.baseMapper.selectList(csPagePOQueryWrapper);
        if(CollUtil.isNotEmpty(csPagePOList)){
            //先删除旧的json文件
            for(CsPagePO csPagePO : csPagePOList){
                if(StrUtil.isNotBlank(csPagePO.getPath())){
                    fileStorageUtil.deleteFile(csPagePO.getPath());
                }
            }
        }
        this.getBaseMapper().delete(csPagePOQueryWrapper);
        InputStream inputStream = null;
        MultipartFile multipartFile = csPageParm.getMultipartFile();
        try {
            inputStream = multipartFile.getInputStream(); // 获取文件的输入流
            String text = new BufferedReader(
                    new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                    .lines()
                    .collect(Collectors.joining("\n"));
            List<CsPagePO> csPagePOS = JSONUtil.toList(text, CsPagePO.class);
            // 倒序排列
            csPagePOS.forEach(temp->{
                String s = fileStorageUtil.uploadStream(writeJsonStringToInputStream(temp.getPath()), OssPath.CONFIGURATIONPATH, OssPath.CONFIGURATIONNAME);
                temp.setPid(pid);
                temp.setStatus("1");
                temp.setPath(s);
                temp.setCreateTime(LocalDateTime.now());
                temp.setUpdateTime(LocalDateTime.now());
                this.save(temp);
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean audit(CsPageParm.CsPageParmAuditParam auditParm) {
//        CsPagePO csPagePO = new CsPagePO();
//        CsPagePO byId = this.getById(auditParm.getId());
//        fileStorageUtil.deleteFile(byId.getPath());
//        BeanUtils.copyProperties(auditParm, csPagePO);
//        String s = fileStorageUtil.uploadMultipart(auditParm.getMultipartFile(), HarmonicConstant.CONFIGURATIONPATH);
//
//        csPagePO.setPath(s);
//
//        return this.updateById(csPagePO);
        return true;
    }

    @Override
    public IPage<CsPageVO> queryPage(CsPageParm.CsPageParmQueryParam csPageParam) {
        Page<CsPageVO> returnpage = new Page<> (csPageParam.getPageNum(), csPageParam.getPageSize ( ));
        QueryWrapper<CsPagePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank (csPageParam.getPid()),CsPagePO.COL_PID,csPageParam.getPid()).
                like(StrUtil.isNotBlank (csPageParam.getSearchValue()),CsPagePO.COL_NAME,csPageParam.getSearchValue()).
                eq ("status",1).
                orderByAsc("sort");

        IPage<CsPagePO> pageData = this.page(new Page<>(csPageParam.getPageNum(), csPageParam.getPageSize()), queryWrapper);

        List<CsPageVO> collect = pageData.getRecords().stream().map(temp -> {
            CsPageVO csPageVO = new CsPageVO();
            CsConfigurationPO csConfigurationPO = csConfigurationMapper.selectById(temp.getPid());
            BeanUtils.copyProperties(temp, csPageVO);
            csPageVO.setConfigurationName(csConfigurationPO.getName());
            InputStream fileStream = fileStorageUtil.getFileStream(temp.getPath());
            String text = new BufferedReader(
                    new InputStreamReader(fileStream, StandardCharsets.UTF_8))
                    .lines()
                    .collect(Collectors.joining("\n"));
            csPageVO.setPath(text);
//            csPageVO.setOperater(collect2.get(csPageVO.getCreateBy()));
            return csPageVO;
        }).collect(Collectors.toList());
        returnpage.setRecords(collect);
        returnpage.setTotal(pageData.getTotal());

        return returnpage;
    }

    @Override
    public CsPagePO queryById(String id) {
        return this.lambdaQuery().eq(CsPagePO::getId,id).one();
    }


    /*将strin写入Json文件，返回一个InputStream*/
    public  InputStream writeJsonStringToInputStream(String jsonString) {
        // 转换为输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8));
        return inputStream;
    }


}
