package com.jeeplus.test.klgBase.question.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
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.google.common.collect.Lists;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.mapper.UserMapper;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.editor.domain.EditorFiles;
import com.jeeplus.test.editor.service.EditorFilesService;
import com.jeeplus.test.editor.service.dto.EditorFilesDTO;
import com.jeeplus.test.klgBase.question.domain.KlgBaseDispose;
import com.jeeplus.test.klgBase.question.domain.KlgBaseQuestions;
import com.jeeplus.test.klgBase.question.domain.KlgBaseQuestionsFocus;
import com.jeeplus.test.klgBase.question.domain.KlgBaseReply;
import com.jeeplus.test.klgBase.question.mapper.KlgBaseDisposeMapper;
import com.jeeplus.test.klgBase.question.mapper.KlgBaseQuestionsFocusMapper;
import com.jeeplus.test.klgBase.question.mapper.KlgBaseQuestionsMapper;
import com.jeeplus.test.klgBase.question.mapper.KlgBaseReplyMapper;
import com.jeeplus.test.klgBase.question.service.dto.KlgBaseQuestionsDTO;
import com.jeeplus.test.klgBase.question.service.mapstruct.KlgBaseDisposeWrapper;
import com.jeeplus.test.klgBase.question.service.mapstruct.KlgBaseQuestionsWrapper;
import com.jeeplus.test.klgBase.question.service.mapstruct.KlgBaseReplyWrapper;
import com.jeeplus.test.oss.service.OssService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
@Service
@Transactional
public class KlgBaseQuestionsService extends ServiceImpl<KlgBaseQuestionsMapper, KlgBaseQuestions> {

    @Resource
    private KlgBaseQuestionsMapper klgBaseQuestionsMapper;

    @Resource
    private KlgBaseDisposeMapper klgBaseDisposeMapper;

    @Resource
    private KlgBaseReplyMapper klgBaseReplyMapper;

    @Resource
    private OssService ossService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private EditorFilesService editorFilesService;

    @Resource
    private KlgBaseQuestionsFocusMapper klgBaseQuestionsFocusMapper;

    public IPage<KlgBaseQuestionsDTO> findList(Page<KlgBaseQuestionsDTO> page, KlgBaseQuestionsDTO klgBaseQuestionsDTO) throws Exception{
        QueryWrapper<KlgBaseQuestions> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( KlgBaseQuestionsWrapper.INSTANCE.toEntity(klgBaseQuestionsDTO), KlgBaseQuestions.class );
        queryWrapper.eq("kbq.del_flag","0");
        queryWrapper.orderByDesc("kbq.create_date");
        if (ObjectUtil.isNotEmpty(klgBaseQuestionsDTO)){
            if(ObjectUtil.isNotEmpty(klgBaseQuestionsDTO.getCreateDateBegin())&&ObjectUtil.isNotEmpty(klgBaseQuestionsDTO.getCreateDateEnd())){
                queryWrapper.between("kbq.create_date",klgBaseQuestionsDTO.getCreateDateBegin(),klgBaseQuestionsDTO.getCreateDateEnd());
            }
            if(StringUtils.isNotBlank(klgBaseQuestionsDTO.getStatus())) {
                if ("2".equals(klgBaseQuestionsDTO.getStatus())){
                    queryWrapper.eq("kbq.status","2").or().eq("kbq.status","5");
                }
            }
            if (ObjectUtil.isNotEmpty(klgBaseQuestionsDTO.getCreateBy())){
                if(StringUtils.isNotBlank(klgBaseQuestionsDTO.getCreateBy().getId())){
                    queryWrapper.eq("kbq.create_by",klgBaseQuestionsDTO.getCreateBy().getId());
                }
            }
            if (StringUtils.isNotBlank(klgBaseQuestionsDTO.getProgramName())) {
                queryWrapper.and(w->
                        w.like("ppli.name",klgBaseQuestionsDTO.getProgramName())
                            .or().like("cw_pr.project_name",klgBaseQuestionsDTO.getProgramName())
                );
            }
        }
        IPage<KlgBaseQuestionsDTO> list = klgBaseQuestionsMapper.findList(page, queryWrapper);
        list.getRecords().stream().forEach(item->{
            if(StringUtils.isNotBlank(item.getDisposeBy())) {
                String disposeByName = new String();
                String[] split = item.getDisposeBy().split(",");
                for (int i = 0; i < split.length; i++) {
                    User user = userMapper.selectById(split[i]);
                    if (i != split.length-1) {
                        disposeByName = disposeByName + user.getName() + ",";
                    } else {
                        if(null != user){
                            disposeByName = disposeByName + user.getName();
                        }
                    }
                }
                item.setDisposeByName(disposeByName);
            }
        });
        return list;
    }

    public IPage<KlgBaseQuestionsDTO> findListFocus(Page<KlgBaseQuestionsDTO> page, KlgBaseQuestionsDTO klgBaseQuestionsDTO) throws Exception{
        QueryWrapper<KlgBaseQuestions> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( KlgBaseQuestionsWrapper.INSTANCE.toEntity(klgBaseQuestionsDTO), KlgBaseQuestions.class );
        queryWrapper.eq("kbq.del_flag","0");
        queryWrapper.orderByDesc("kbq.create_date");
        if (ObjectUtil.isNotEmpty(klgBaseQuestionsDTO)){
            if(ObjectUtil.isNotEmpty(klgBaseQuestionsDTO.getCreateDateBegin())&&ObjectUtil.isNotEmpty(klgBaseQuestionsDTO.getCreateDateEnd())){
                queryWrapper.between("kbq.create_date",klgBaseQuestionsDTO.getCreateDateBegin(),klgBaseQuestionsDTO.getCreateDateEnd());
            }
            if(StringUtils.isNotBlank(klgBaseQuestionsDTO.getStatus())) {
                if ("2".equals(klgBaseQuestionsDTO.getStatus())){
                    queryWrapper.eq("kbq.status","2").or().eq("kbq.status","5");
                }
            }
            if (ObjectUtil.isNotEmpty(klgBaseQuestionsDTO.getCreateBy())){
                if(StringUtils.isNotBlank(klgBaseQuestionsDTO.getCreateBy().getId())){
                    queryWrapper.eq("kbq.create_by",klgBaseQuestionsDTO.getCreateBy().getId());
                }
            }
            queryWrapper.eq("kbqf.user_id",UserUtils.getCurrentUserDTO().getId());
        }
        IPage<KlgBaseQuestionsDTO> list = klgBaseQuestionsMapper.findListFocus(page, queryWrapper);
        list.getRecords().stream().forEach(item->{
            if(StringUtils.isNotBlank(item.getDisposeBy())) {
                String disposeByName = new String();
                String[] split = item.getDisposeBy().split(",");
                for (int i = 0; i < split.length; i++) {
                    User user = userMapper.selectById(split[i]);
                    if (i != split.length-1) {
                        disposeByName = disposeByName + user.getName() + ",";
                    } else {
                        disposeByName = disposeByName + user.getName();
                    }
                }
                item.setDisposeByName(disposeByName);
            }
        });
        return list;
    }

    public KlgBaseQuestionsDTO queryById(String id) {

        KlgBaseQuestionsDTO klgBaseQuestionsDTO = klgBaseQuestionsMapper.queryById(id);

        if (ObjectUtil.isNotEmpty(klgBaseQuestionsDTO)) {
            if(StringUtils.isNotBlank(klgBaseQuestionsDTO.getContent())){
                String newContent = editorFilesService.getNewContent(klgBaseQuestionsDTO.getContent(), id);
                klgBaseQuestionsDTO.setContent(newContent);
                KlgBaseQuestions k = new KlgBaseQuestions();
                k.setId(id);
                k.setContent(newContent);
                this.update(k, new QueryWrapper<KlgBaseQuestions>().lambda().eq(KlgBaseQuestions::getId, id));
                List<EditorFiles> list = editorFilesService.list(new QueryWrapper<EditorFiles>().lambda().eq(EditorFiles::getSourceId, id));
                List<EditorFilesDTO> editorFilesDTOList = new ArrayList<>();
                list.stream().forEach(item->{
                    EditorFilesDTO editorFilesDTO = new EditorFilesDTO();
                    editorFilesDTO.setSourceId(item.getSourceId());
                    editorFilesDTO.setTemporaryUrl(item.getTemporaryUrl());
                    editorFilesDTO.setUrl(item.getUrl());
                    editorFilesDTOList.add(editorFilesDTO);
                });
                klgBaseQuestionsDTO.setEditorFilesDTOList(editorFilesDTOList);
            }
            if (CollectionUtil.isNotEmpty(klgBaseQuestionsDTO.getKlgBaseReplyDTOList())){
                klgBaseQuestionsDTO.getKlgBaseReplyDTOList().stream().forEach(item->{
                    if (StringUtils.isNotBlank(item.getContent())){
                        String newC = editorFilesService.getNewContent(item.getContent(), item.getId());
                        KlgBaseReply kr = new KlgBaseReply();
                        kr.setId(item.getId());
                        kr.setContent(newC);
                        klgBaseReplyMapper.update(kr, new QueryWrapper<KlgBaseReply>().lambda().eq(KlgBaseReply::getId, item.getId()));
                        item.setContent(newC);
                        List<EditorFiles> list = editorFilesService.list(new QueryWrapper<EditorFiles>().lambda().eq(EditorFiles::getSourceId, item.getId()));
                        List<EditorFilesDTO> editorFilesDTOS = new ArrayList<>();
                        list.stream().forEach(i->{
                            EditorFilesDTO editorFilesDTO = new EditorFilesDTO();
                            editorFilesDTO.setSourceId(i.getSourceId());
                            editorFilesDTO.setTemporaryUrl(i.getTemporaryUrl());
                            editorFilesDTO.setUrl(i.getUrl());
                            editorFilesDTOS.add(editorFilesDTO);
                        });
                        item.setEditorFilesDTOList(editorFilesDTOS);
                    }
                });
            }
        }

        return klgBaseQuestionsDTO;
    }

    public String saveForm(KlgBaseQuestionsDTO klgBaseQuestionsDTO) throws Exception{
        KlgBaseQuestions klgBaseQuestions = KlgBaseQuestionsWrapper.INSTANCE.toEntity(klgBaseQuestionsDTO);
        this.saveOrUpdate(klgBaseQuestions);
        if (ObjectUtil.isNotEmpty(klgBaseQuestionsDTO)) {
            //问题内容
            editorFilesService.remove(new QueryWrapper<EditorFiles>().lambda().eq(EditorFiles::getSourceId,klgBaseQuestions.getId()));
            if (CollectionUtil.isNotEmpty(klgBaseQuestionsDTO.getEditorFilesDTOList())) {
                klgBaseQuestionsDTO.getEditorFilesDTOList().stream().forEach(item->{
                    editorFilesService.saveUrl(item.getTemporaryUrl(),item.getUrl(),klgBaseQuestions.getId());
                });
            }
            //附件
            ossService.saveOrUpdateFileList(klgBaseQuestionsDTO.getWorkAttachmentDtoList(),klgBaseQuestions.getId(),"klg_question");
            //处理人
            if(CollectionUtil.isNotEmpty(klgBaseQuestionsDTO.getKlgBaseDisposeDTOList())){
                klgBaseDisposeMapper.delete(new QueryWrapper<KlgBaseDispose>().lambda().eq(KlgBaseDispose::getQuestionId,klgBaseQuestions.getId()));
                klgBaseQuestionsDTO.getKlgBaseDisposeDTOList().stream().forEach(item->{
                    KlgBaseDispose klgBaseDispose = KlgBaseDisposeWrapper.INSTANCE.toEntity(item);
                    klgBaseDisposeMapper.insert(klgBaseDispose);
                });
            }else{
                klgBaseDisposeMapper.delete(new QueryWrapper<KlgBaseDispose>().lambda().eq(KlgBaseDispose::getQuestionId,klgBaseQuestions.getId()));
            }
            //回复
            if(CollectionUtil.isNotEmpty(klgBaseQuestionsDTO.getKlgBaseReplyDTOList())){
                String maxSortByQues = klgBaseQuestionsMapper.getMaxSortByQues(klgBaseQuestions.getId());
                klgBaseQuestionsDTO.getKlgBaseReplyDTOList().stream().forEach((item)->{
                    KlgBaseReply klgBaseReply = KlgBaseReplyWrapper.INSTANCE.toEntity(item);
                    if (StringUtils.isNotBlank(klgBaseReply.getId())) {
                        klgBaseReplyMapper.updateById(klgBaseReply);
                    } else {
                        if(StringUtils.isNotBlank(maxSortByQues)) {
                            int i = Integer.parseInt(maxSortByQues);
                            klgBaseReply.setSort(String.valueOf(i+1));
                        }else{
                            klgBaseReply.setSort("0");
                        }
                        klgBaseReply.setReplyBy(UserUtils.getCurrentUserDTO().getId());
                        klgBaseReply.setQuestionId(klgBaseQuestions.getId());
                        klgBaseReplyMapper.insert(klgBaseReply);
                    }
                    editorFilesService.remove(new QueryWrapper<EditorFiles>().lambda().eq(EditorFiles::getSourceId,klgBaseReply.getId()));
                    if (CollectionUtil.isNotEmpty(item.getEditorFilesDTOList())){
                        item.getEditorFilesDTOList().stream().forEach(file->{
                            editorFilesService.saveUrl(file.getTemporaryUrl(),file.getUrl(),klgBaseReply.getId());
                        });
                    }
                });
            }
        }
        return klgBaseQuestions.getId();
    }

    public ResponseEntity saveQuestion(KlgBaseQuestionsDTO klgBaseQuestionsDTO) throws Exception{
        this.saveForm(klgBaseQuestionsDTO);
        return ResponseEntity.ok("保存成功");
    }

    public ResponseEntity deleteByIds(String ids) {
        String idArray[] =ids.split(",");
        this.removeByIds (Lists.newArrayList (idArray));
        return ResponseEntity.ok ("删除成功");
    }

    public String updateStatusById(KlgBaseQuestionsDTO klgBaseQuestionsDTO) {
        KlgBaseQuestions klgBaseQuestions = KlgBaseQuestionsWrapper.INSTANCE.toEntity(klgBaseQuestionsDTO);
        klgBaseQuestionsMapper.update(klgBaseQuestions, new QueryWrapper<KlgBaseQuestions>().lambda().eq(KlgBaseQuestions::getId, klgBaseQuestions.getId()));
        return "操作成功";
    }

    public ResponseEntity focusByIds(String idList) {
        String ids[] =idList.split(",");
        UserDTO currentUserDTO = UserUtils.getCurrentUserDTO();
        for (String id : ids) {
            List<KlgBaseQuestionsFocus> klgBaseQuestionsFoci = klgBaseQuestionsFocusMapper.selectList(new QueryWrapper<KlgBaseQuestionsFocus>().lambda()
                    .eq(KlgBaseQuestionsFocus::getUserId, currentUserDTO.getId())
                    .eq(KlgBaseQuestionsFocus::getQuestionId, id));
            if(CollectionUtil.isEmpty(klgBaseQuestionsFoci)){
                KlgBaseQuestionsFocus klgBaseQuestionsFocus = new KlgBaseQuestionsFocus();
                klgBaseQuestionsFocus.setQuestionId(id);
                klgBaseQuestionsFocus.setUserId(currentUserDTO.getId());
                klgBaseQuestionsFocusMapper.insert(klgBaseQuestionsFocus);
            }
        }
        return ResponseEntity.ok ("关注成功");
    }
}
