package com.njcn.csharmonic.service.impl;

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.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.RoleEngineerDevFeignClient;
import com.njcn.csdevice.constant.DataParam;
import com.njcn.csharmonic.constant.HarmonicConstant;
import com.njcn.csharmonic.mapper.CsConfigurationMapper;
import com.njcn.csharmonic.param.CsConfigurationParm;
import com.njcn.csharmonic.pojo.po.CsConfigurationPO;
import com.njcn.csharmonic.pojo.vo.CsConfigurationVO;
import com.njcn.csharmonic.service.CsConfigurationService;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
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.util.CollectionUtils;
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 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();
        String projects = "";
        if (!CollectionUtils.isEmpty(projectIds)) {
            projects = String.join(",", projectIds);
        }
        csConfigurationPO.setProjectIds(projects);
        //排序不填给个100往后排
        csConfigurationPO.setOrderBy(Objects.isNull(csConfigurationParm.getOrderBy()) ? 100 : csConfigurationParm.getOrderBy());
        csConfigurationPO.setImagePath(csConfigurationParm.getFileContent());

        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("存在相同的组态项目名称在其他工程项目中，无法新建");
        }
        return save;
    }

    @Override
    public boolean audit(CsConfigurationParm.CsConfigurationAuditParam auditParm) {
        CsConfigurationPO csConfigurationPO = new CsConfigurationPO();
        if (Objects.equals(auditParm.getStatus(), "0")) {
            csConfigurationPO.setId(auditParm.getId());
            csConfigurationPO.setStatus("0");
            boolean b = this.updateById(csConfigurationPO);
            return b;
        }
        Integer count = this.lambdaQuery().eq(CsConfigurationPO::getName, auditParm.getName()).ne(CsConfigurationPO::getId, auditParm.getId()).eq(CsConfigurationPO::getStatus, "1").count();
        if (count > 0) {
            throw new BusinessException("修改名称失败,存在相同的组态项目");
        }
        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())) {
            String s = fileStorageUtil.uploadStream(writeJsonStringToInputStream(auditParm.getFileContent()), HarmonicConstant.CONFIGURATIONPATH, HarmonicConstant.CONFIGURATIONNAME);
            csConfigurationPO.setImagePath(s);
        }

        boolean b = this.updateById(csConfigurationPO);

        return b;
    }

    @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 = roleEngineerDevFeignClient.getRoleProject().getData();
//        if (CollectionUtils.isEmpty(data1)) {
//            return returnpage;
//        }
        //+无线项目id
        data1.add(DataParam.WIRELESS_PROJECT_ID);
        String userId = csConfigurationQueryParam.getCurrentUserId();
        String roleCode = csConfigurationQueryParam.getRoleCode();
        if (roleCode.contains("operation_manager")) {
            userId = null;
        }
        Page<CsConfigurationPO> csConfigurationPOPage = this.getBaseMapper().queryPage(temppage, csConfigurationQueryParam, data1, userId);
//        QueryWrapper<CsConfigurationPO> query = new QueryWrapper<>();
//        query.like(StringUtils.isNotBlank(csConfigurationQueryParam.getSearchValue()),CsConfigurationPO.COL_NAME,csConfigurationQueryParam.getSearchValue()).
//                le (StringUtils.isNotBlank (csConfigurationQueryParam.getSearchEndTime()), CsConfigurationPO.COL_CREATE_TIME, csConfigurationQueryParam.getSearchEndTime ( )).
//                ge (StringUtils.isNotBlank (csConfigurationQueryParam.getSearchBeginTime()),  CsConfigurationPO.COL_CREATE_TIME, csConfigurationQueryParam.getSearchBeginTime ( )).
//                eq ("status",1).orderByAsc("order_by").orderByDesc(CsConfigurationPO.COL_CREATE_TIME);
//        Page<CsConfigurationPO> csConfigurationPOPage = this.getBaseMapper().selectPage(temppage, query);
        List<String> collect1 = csConfigurationPOPage.getRecords().stream().map(CsConfigurationPO::getCreateBy).collect(Collectors.toList());
        Map<String, String> collect2;
        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 {
                InputStream fileStream = fileStorageUtil.getFileStream(page.getImagePath());
                String text = new BufferedReader(
                        new InputStreamReader(fileStream, StandardCharsets.UTF_8))
                        .lines()
                        .collect(Collectors.joining("\n"));
                csDevModelPageVO.setFileContent(text);
            }


            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, HarmonicConstant.CONFIGURATIONPATH));
    }

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