package com.njcn.cssystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.cssystem.mapper.CsFeedbackChatMapper;
import com.njcn.cssystem.mapper.CsFeedbackMapper;
import com.njcn.cssystem.pojo.param.CsFeedbackAddParm;
import com.njcn.cssystem.pojo.param.CsFeedbackAuditParm;
import com.njcn.cssystem.pojo.param.CsFeedbackQueryParm;
import com.njcn.cssystem.pojo.po.CsFeedbackChatPO;
import com.njcn.cssystem.pojo.po.CsFeedbackPO;
import com.njcn.cssystem.pojo.po.CsFilePathPO;
import com.njcn.cssystem.pojo.vo.CsFeedbackDetailVO;
import com.njcn.cssystem.pojo.vo.CsFeedbackVO;
import com.njcn.cssystem.service.CsFeedbackService;
import com.njcn.cssystem.service.CsFilePathService;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
import com.njcn.web.utils.RequestUtil;
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 java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * Description:
 * 接口文档访问地址：http://serverIP:port/swagger-ui.html
 * Date: 2023/4/6  11:39【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class CsFeedbackServiceImpl extends ServiceImpl<CsFeedbackMapper, CsFeedbackPO> implements CsFeedbackService {

    private final FileStorageUtil fileStorageUtil;
    private final CsFilePathService csFilePathService;
    private final CsFeedbackChatMapper csFeedbackChatMapper;
    private final UserFeignClient userFeignClient;
    private final RoleEngineerDevFeignClient roleEngineerDevFeignClient;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addFeedBack(CsFeedbackAddParm csFeedbackAddParm) {
        if (Objects.isNull(csFeedbackAddParm.getEngineeringId())) {
            throw new BusinessException("请选择工程后,再进行反馈！");
        }
        CsFeedbackPO csFeedbackPO = new CsFeedbackPO ();
        BeanUtils.copyProperties (csFeedbackAddParm, csFeedbackPO);
        csFeedbackPO.setUserId(RequestUtil.getUserIndex());
        csFeedbackPO.setStatus ("1");
        boolean save = this.save (csFeedbackPO);
        boolean flag= true;
        if(!Objects.isNull (csFeedbackAddParm.getFiles ( ))){
            List<CsFilePathPO> csFilePathPOS= new ArrayList<> ();
            for (int i = 0; i < csFeedbackAddParm.getFiles ( ).length; i++) {

                CsFilePathPO csFilePathPO = new CsFilePathPO( );
                csFilePathPO.setId (csFeedbackPO.getId ());
                String filePath = fileStorageUtil.uploadMultipart (csFeedbackAddParm.getFiles ( )[i], OssPath.FEEDBACK);
                csFilePathPO.setFileName (csFeedbackAddParm.getFiles ( )[i].getOriginalFilename ( ));
                csFilePathPO.setFilePath (filePath);
                csFilePathPO.setStatus ("1");
                csFilePathPOS.add (csFilePathPO);
            }
            flag = csFilePathService.saveBatch (csFilePathPOS);
        }


        return save&&flag;
    }

    @Override
    public Page<CsFeedbackVO> queryFeedBackPage(CsFeedbackQueryParm csFeedbackQueryParm) {
        Page<CsFeedbackPO> page = new Page<> (csFeedbackQueryParm.getPageNum ( ), csFeedbackQueryParm.getPageSize ( ));
        Page<CsFeedbackVO> returnpage = new Page<> (csFeedbackQueryParm.getPageNum ( ), csFeedbackQueryParm.getPageSize ( ));
        List<String> data = roleEngineerDevFeignClient.getRoleengineer().getData();
        if(CollectionUtils.isEmpty(data)){
           return returnpage;
        }
        QueryWrapper<CsFeedbackPO> queryWrapper = new QueryWrapper<> ();
        queryWrapper.
                eq (StringUtils.isNotBlank (csFeedbackQueryParm.getType ()),"type",csFeedbackQueryParm.getType ()).
                in("engineering_id",data).
                ge(StringUtils.isNotBlank(csFeedbackQueryParm.getSearchBeginTime()), "create_time",csFeedbackQueryParm.getSearchBeginTime()).
                le(StringUtils.isNotBlank(csFeedbackQueryParm.getSearchEndTime()),"create_time",csFeedbackQueryParm.getSearchEndTime()).
                like(StringUtils.isNotBlank(csFeedbackQueryParm.getSearchValue()),"title",csFeedbackQueryParm.getSearchValue()).
                eq(StringUtils.isNotBlank (csFeedbackQueryParm.getStatus ()),"status",csFeedbackQueryParm.getStatus ()).orderByDesc("create_time");
        Page<CsFeedbackPO> csFeedbackPOPage = this.getBaseMapper ( ).selectPage (page, queryWrapper);
        QueryWrapper<CsFeedbackChatPO> csFeedbackChatPOQueryWrapper = new QueryWrapper<> ();
        List<CsFeedbackVO> collect = csFeedbackPOPage.getRecords ( ).stream ( ).map (temp -> {
            CsFeedbackVO csFeedbackVO = new CsFeedbackVO ( );
            BeanUtils.copyProperties (temp, csFeedbackVO);
//            csFeedbackChatPOQueryWrapper.clear ();
//            csFeedbackChatPOQueryWrapper.eq ("id",temp.getId ()).
//                    ne ("user_id",temp.getUserId ()).
//                    eq ("chat_status","0").
//                    eq ("status", "1");
//            int count = csFeedbackChatService.count (csFeedbackChatPOQueryWrapper );
//            csFeedbackVO.setChatCount (count);
            return csFeedbackVO;
        }).collect (Collectors.toList ( ));
        returnpage.setRecords (collect);
        returnpage.setTotal(csFeedbackPOPage.getTotal());
        return returnpage;
    }

    @Override
    public CsFeedbackDetailVO queryFeedBackDetail(String id) {
        CsFeedbackDetailVO csFeedbackDetailVO = new CsFeedbackDetailVO();
        CsFeedbackPO byId = this.getById (id);
        BeanUtils.copyProperties (byId, csFeedbackDetailVO);
        QueryWrapper<CsFilePathPO> queryWrapper = new QueryWrapper();
        queryWrapper.eq ("id", id).eq ("status", "1");
        List<CsFilePathPO> list = csFilePathService.list (queryWrapper);
        List<String> collect = list.stream ( ).map (temp->{
            return temp.getFilePath ();
        }).collect (Collectors.toList ( ));
        csFeedbackDetailVO.setImageUrls (collect);
        QueryWrapper<CsFeedbackChatPO> csFeedbackChatPOQueryWrapper = new QueryWrapper();
        csFeedbackChatPOQueryWrapper.eq ("id", id).eq ("status", "1").orderByDesc ("create_time");
        List<CsFeedbackChatPO> list1 = csFeedbackChatMapper.selectList (csFeedbackChatPOQueryWrapper);

        List<String> collect1 = list1.stream().map(CsFeedbackChatPO::getUserId).distinct().collect(Collectors.toList());
        Map<String, String> collect2;
        if(!CollectionUtils.isEmpty(collect1)){
            List<User> userTem = userFeignClient.appuserByIdList(collect1).getData();
            collect2 = userTem.stream().collect(Collectors.toMap(User::getId, User::getName, (e1, e2) -> e1 + "," + e2));

        } else {
            collect2 = new HashMap<>();
        }
        list1.stream().forEach(temp ->{
            temp.setUserName(collect2.get(temp.getUserId()));
        });

            csFeedbackDetailVO.setCsFeedbackChatPOList (list1);
        return csFeedbackDetailVO;
    }

    @Override
    public Boolean auditFeedBack(CsFeedbackAuditParm csFeedbackAuditParm) {
        boolean update = this.lambdaUpdate().eq(CsFeedbackPO::getId, csFeedbackAuditParm.getId()).set(CsFeedbackPO::getStatus, csFeedbackAuditParm.getStatus()).update();
        return update;
    }
}
