package com.njcn.csharmonic.service.impl;

import com.alibaba.fastjson.JSON;
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.csharmonic.constant.HarmonicConstant;
import com.njcn.csharmonic.mapper.CsConfigurationMapper;
import com.njcn.csharmonic.mapper.CsPagePOMapper;
import com.njcn.csharmonic.param.CsPageParm;
import com.njcn.csharmonic.pojo.po.CsConfigurationPO;
import com.njcn.csharmonic.pojo.po.CsPagePO;
import com.njcn.csharmonic.pojo.vo.CsPageVO;
import com.njcn.csharmonic.service.CsPagePOService;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.user.api.UserFeignClient;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
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.util.ArrayList;
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) {
        List<CsPageVO> list = new ArrayList<>();

        QueryWrapper<CsPagePO> csPagePOQueryWrapper = new QueryWrapper<>();
        String pid = csPageParm.getPid();
        csPagePOQueryWrapper.eq("pid",pid);
        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 = JSON.parseArray(text, CsPagePO.class);
            csPagePOS.forEach(temp->{
                String s = fileStorageUtil.uploadStream(writeJsonStringToInputStream(temp.getPath()),HarmonicConstant.CONFIGURATIONPATH, HarmonicConstant.CONFIGURATIONNAME);

                temp.setPid(pid);
                temp.setStatus("1");
                temp.setPath(s);
                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(StringUtils.isNotBlank (csPageParam.getPid()),CsPagePO.COL_PID,csPageParam.getPid()).
                like(StringUtils.isNotBlank (csPageParam.getSearchValue()),CsPagePO.COL_NAME,csPageParam.getSearchValue()).
                eq ("status",1).
                orderByAsc(CsPagePO.SORT);

        IPage<CsPagePO> pageData = this.page(new Page<>(csPageParam.getPageNum(), csPageParam.getPageSize()), queryWrapper);
        List<String> collect1 = pageData.getRecords().stream().map(CsPagePO::getCreateBy).collect(Collectors.toList());
//        Map<String, String> collect2;
//        if(!CollectionUtils.isEmpty(collect1)){
//            List<User> data = userFeignClient.getUserByIdList(collect1).getData();
//            collect2 = data.stream().collect(Collectors.toMap(User::getId, User::getName, (e1, e2) -> e1 + "," + e2));
//
//        } else {
//            collect2 = new HashMap<>();
//        }
        List<CsPageVO> collect = pageData.getRecords().stream().map(temp -> {
            CsPageVO csPageVO = new CsPageVO();
            CsConfigurationPO csConfigurationPO = csConfigurationMapper.selectById(temp.getPid());
            BeanUtils.copyProperties(temp, csPageVO);
//            csPageVO.setKId(temp.getKId());
            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;
    }


}
