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

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.product.cnzutai.zutai.mapper.CsPagePOMapper;
import com.njcn.product.cnzutai.zutai.pojo.po.CsPagePO;
import com.njcn.product.cnzutai.zutai.pojo.po.CsSubConfigurationAss;
import com.njcn.product.cnzutai.zutai.service.CsConfigurationService;
import com.njcn.product.cnzutai.zutai.mapper.CsConfigurationMapper;
import com.njcn.product.cnzutai.zutai.pojo.param.CsConfigurationParm;
import com.njcn.product.cnzutai.zutai.pojo.po.CsConfigurationPO;
import com.njcn.product.cnzutai.zutai.pojo.vo.CsConfigurationVO;
import com.njcn.product.cnzutai.zutai.service.CsSubConfigurationAssService;
import com.njcn.product.terminal.mysqlTerminal.mapper.LineMapper;
import com.njcn.product.terminal.mysqlTerminal.mapper.PqStationMapper;
import com.njcn.product.terminal.mysqlTerminal.pojo.po.Line;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * Description:
 * Date: 2023/5/31  10:53【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class CsConfigurationServiceImpl extends ServiceImpl<CsConfigurationMapper, CsConfigurationPO> implements CsConfigurationService {

    private final FileStorageUtil fileStorageUtil;
    private final CsPagePOMapper csPagePOMapper;
    private final CsSubConfigurationAssService csSubConfigurationAssService;
    private final LineMapper lineMapper;

    //private final UserFeignClient userFeignClient;

    //private final RoleEngineerDevFeignClient roleEngineerDevFeignClient;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean add(CsConfigurationParm csConfigurationParm) {
        CsConfigurationPO csConfigurationPO = new CsConfigurationPO();

        BeanUtils.copyProperties(csConfigurationParm,csConfigurationPO);

        List<String> projectIds = csConfigurationParm.getProjectIds();
        if(CollectionUtils.isEmpty(projectIds)){
            throw new BusinessException("请选择项目");
        }
        String projects = String.join(",", projectIds);

        csConfigurationPO.setProjectIds(projects);
        //排序不填给个100往后排
        csConfigurationPO.setOrderBy(Objects.isNull(csConfigurationParm.getOrderBy())?100:csConfigurationParm.getOrderBy());
        csConfigurationPO.setImagePath(csConfigurationParm.getFileContent());
        csConfigurationPO.setActive(0);
        csConfigurationPO.setStatus("1");
        boolean save = this.save(csConfigurationPO);


        String name = csConfigurationPO.getName();
        Integer count = this.lambdaQuery().eq(CsConfigurationPO::getName, name).eq(CsConfigurationPO::getStatus, "1").count();
        if(count>1){
            throw new BusinessException("存在相同的组态项目名称");
        }

        //添加变电站绑定
        if(!CollectionUtils.isEmpty(csConfigurationParm.getSubstionIds())){
            List<CsSubConfigurationAss> list = csSubConfigurationAssService.lambdaQuery().in(CsSubConfigurationAss::getSubId, csConfigurationParm.getSubstionIds()).list();
            if (!CollectionUtils.isEmpty(list)){
                List<Line> stationResult = lineMapper.selectList(new LambdaQueryWrapper<Line>().in(Line::getId,list));
                String subNameList = stationResult.stream().map(Line::getName).collect(Collectors.joining(StrUtil.COMMA));

                throw new BusinessException("变电站"+subNameList+"已绑定其他项目请修改");
            }else {
                List<CsSubConfigurationAss> csSubConfigurationAsses = csConfigurationParm.getSubstionIds().stream().map(temp -> {
                    CsSubConfigurationAss csSubConfigurationAss = new CsSubConfigurationAss();
                    csSubConfigurationAss.setSubId(temp);
                    csSubConfigurationAss.setConfigId(csConfigurationPO.getId());
                    return csSubConfigurationAss;
                }).collect(Collectors.toList());

                csSubConfigurationAssService.saveBatch(csSubConfigurationAsses);
            }
        }
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean audit(CsConfigurationParm.CsConfigurationAuditParam auditParm) {
        CsConfigurationPO tem  = this.getById(auditParm.getId());
        if(Objects.isNull(tem)){
            throw new BusinessException(CommonResponseEnum.FAIL,"未查询到项目信息，无法操作！");
        }
        //删除关联表信息
        csSubConfigurationAssService.lambdaUpdate().eq(CsSubConfigurationAss::getConfigId,tem.getId()).remove();

        CsConfigurationPO csConfigurationPO = new CsConfigurationPO();
        if(Objects.equals(auditParm.getStatus(),"0")){
            csConfigurationPO.setId(auditParm.getId());
            csConfigurationPO.setStatus("0");
            boolean b = this.updateById(csConfigurationPO);

            if(StrUtil.isNotBlank(tem.getImagePath())){
                fileStorageUtil.deleteFile(tem.getImagePath());
            }

            CsPagePO csPagePO = new CsPagePO();
            csPagePO.setStatus("0");
            csPagePOMapper.update(csPagePO,new LambdaUpdateWrapper<CsPagePO>().eq(CsPagePO::getPid,csConfigurationPO.getId()));
            return b;
        }

        BeanUtils.copyProperties(auditParm,csConfigurationPO);
        List<String> projectIds = auditParm.getProjectIds();
        if(!CollectionUtils.isEmpty(projectIds)){
            String projects = String.join(",", projectIds);
            csConfigurationPO.setProjectIds(projects);

        }
        if(!Objects.isNull(auditParm.getOrderBy())){
            csConfigurationPO.setOrderBy(auditParm.getOrderBy()==0?100:auditParm.getOrderBy());
        }

        if(!Objects.isNull(auditParm.getFileContent())){
            if(StrUtil.isNotBlank(tem.getImagePath())){
                fileStorageUtil.deleteFile(tem.getImagePath());
            }

            String s = fileStorageUtil.uploadStream(writeJsonStringToInputStream(auditParm.getFileContent()), OssPath.CONFIGURATIONPATH, OssPath.CONFIGURATIONNAME);
            csConfigurationPO.setImagePath(s);
        }

        boolean b = this.updateById(csConfigurationPO);

        //添加变电站绑定
        if(!CollectionUtils.isEmpty(auditParm.getSubstionIds())){
            List<CsSubConfigurationAss> list = csSubConfigurationAssService.lambdaQuery().in(CsSubConfigurationAss::getSubId, auditParm.getSubstionIds()).list();
            if (!CollectionUtils.isEmpty(list)){
                List<Line> stationResult = lineMapper.selectList(new LambdaQueryWrapper<Line>().in(Line::getId,list));
                String subNameList = stationResult.stream().map(Line::getName).collect(Collectors.joining(StrUtil.COMMA));

                throw new BusinessException("变电站"+subNameList+"已绑定其他项目请修改");
            }else {
                List<CsSubConfigurationAss> csSubConfigurationAsses = auditParm.getSubstionIds().stream().map(temp -> {
                    CsSubConfigurationAss csSubConfigurationAss = new CsSubConfigurationAss();
                    csSubConfigurationAss.setSubId(temp);
                    csSubConfigurationAss.setConfigId(csConfigurationPO.getId());
                    return csSubConfigurationAss;
                }).collect(Collectors.toList());

                csSubConfigurationAssService.saveBatch(csSubConfigurationAsses);
            }
        }

        return b;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean active(String id) {
        CsConfigurationPO csConfigurationPO = this.lambdaQuery().eq(CsConfigurationPO::getId,id).one();
        if(Objects.isNull(csConfigurationPO)){
            throw new BusinessException("未查询到项目组态图");
        }
        this.lambdaUpdate().set(CsConfigurationPO::getActive,0).update();
        this.lambdaUpdate().set(CsConfigurationPO::getActive,1).eq(CsConfigurationPO::getId, id).update();
        return true;
    }

    @Override
    public CsConfigurationPO getActive() {
       CsConfigurationPO csConfigurationPO = this.lambdaQuery().eq(CsConfigurationPO::getActive,1).one();
        return csConfigurationPO;
    }


    @Override
    public IPage<CsConfigurationVO> queryPage(CsConfigurationParm.CsConfigurationQueryParam csConfigurationQueryParam) {
        Page<CsConfigurationVO> returnpage = new Page<> (csConfigurationQueryParam.getPageNum(), csConfigurationQueryParam.getPageSize ( ));
        Page<CsConfigurationPO> temppage = new Page<> (csConfigurationQueryParam.getPageNum(), csConfigurationQueryParam.getPageSize ( ));

        List<String> data1 = new ArrayList<>();  //roleEngineerDevFeignClient.getRoleProject().getData();
   /*     if(CollectionUtils.isEmpty(data1)){
            return  returnpage;
        }*/
        //+无线项目id
        //data1.add(DataParam.WIRELESS_PROJECT_ID);
        Page<CsConfigurationPO> csConfigurationPOPage = this.getBaseMapper().queryPage(temppage,csConfigurationQueryParam);

        List<String> collect1 = csConfigurationPOPage.getRecords().stream().map(CsConfigurationPO::getCreateBy).collect(Collectors.toList());
        Map<String, String> collect2 = new HashMap<>();
  /*      if(!CollectionUtils.isEmpty(collect1)){
            List<User> data = userFeignClient.appuserByIdList(collect1).getData();
            collect2 = data.stream().collect(Collectors.toMap(User::getId, User::getName, (e1, e2) -> e1 + "," + e2));

        } else {
            collect2 = new HashMap<>();
        }*/

        List<CsConfigurationVO> collect = csConfigurationPOPage.getRecords().stream().map(page -> {
            CsConfigurationVO csDevModelPageVO = new CsConfigurationVO();
            BeanUtils.copyProperties(page, csDevModelPageVO);

            if(StringUtils.isEmpty(page.getProjectIds())){
                csDevModelPageVO.setProjectIds(new ArrayList<>());
            }else {
                csDevModelPageVO.setProjectIds( Arrays.asList(page.getProjectIds().split(",")));

            }
            if(Objects.isNull(page.getImagePath())){
                csDevModelPageVO.setFileContent(null);

            }else {

                try {
                    InputStream fileStream = fileStorageUtil.getFileStream(page.getImagePath());
                    String text = new BufferedReader(
                            new InputStreamReader(fileStream, StandardCharsets.UTF_8))
                            .lines()
                            .collect(Collectors.joining("\n"));
                    csDevModelPageVO.setFileContent(text);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
            List<CsSubConfigurationAss> csSubConfigurationAssList = csSubConfigurationAssService.lambdaQuery().eq(CsSubConfigurationAss::getConfigId, page.getId()).list();
            if(!CollectionUtils.isEmpty(csSubConfigurationAssList)){
                List<String> subIds = csSubConfigurationAssList.stream().map(CsSubConfigurationAss::getSubId).collect(Collectors.toList());

                csDevModelPageVO.setSubstionIds(subIds);
//                List<Line> stationResult = lineMapper.selectList(new LambdaQueryWrapper<Line>().in(Line::getId,subIds));
//                csDevModelPageVO.setSubstionName();
            }

            csDevModelPageVO.setOperater(collect2.get(csDevModelPageVO.getCreateBy()));
            return csDevModelPageVO;
        }).collect(Collectors.toList());
        returnpage.setRecords(collect);
        returnpage.setTotal(csConfigurationPOPage.getTotal());



        return returnpage;
    }

    @Override
    public String uploadImage(MultipartFile issuesFile) {
        return fileStorageUtil.getFileUrl( fileStorageUtil.uploadMultipart(issuesFile, OssPath.CONFIGURATIONPATH));
    }

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