package com.izouma.jmrh.web;

import com.izouma.jmrh.domain.Conversation;
import com.izouma.jmrh.domain.OrgInfo;
import com.izouma.jmrh.domain.ResourceSupplyAndDemand;
import com.izouma.jmrh.dto.ConversationDTO;
import com.izouma.jmrh.dto.ConversationToAbutmentDTO;
import com.izouma.jmrh.dto.PageQuery;
import com.izouma.jmrh.dto.R;
import com.izouma.jmrh.enums.ConversationType;
import com.izouma.jmrh.enums.Exist;
import com.izouma.jmrh.enums.ResSnDType;
import com.izouma.jmrh.exception.BusinessException;
import com.izouma.jmrh.repo.ConversationRepo;
import com.izouma.jmrh.repo.OrgInfoRepo;
import com.izouma.jmrh.repo.ResourceSupplyAndDemandRepo;
import com.izouma.jmrh.service.ConversationService;
import com.izouma.jmrh.utils.ObjUtils;
import com.izouma.jmrh.utils.SecurityUtils;
import com.izouma.jmrh.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/conversation")
@AllArgsConstructor
@Slf4j
public class ConversationController extends BaseController {
    private ConversationService conversationService;
    private ConversationRepo            conversationRepo;
    private ResourceSupplyAndDemandRepo resourceSupplyAndDemandRepo;
    private OrgInfoRepo                 orgInfoRepo;

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Conversation save(@RequestBody Conversation record) {
        if (record.getId() == null) throw new BusinessException("id不能为空");
        Conversation orig = conversationRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
        ObjUtils.merge(orig, record);
        return conversationRepo.save(orig);
    }

    @PostMapping("/create")
    public void create(@RequestParam Long sndId, @RequestParam String orgName,
                       @RequestParam String contactName, @RequestParam String contactPhone,
                       @RequestParam(required = false) String email, @RequestParam String content, @RequestParam String description) {
        conversationService.create(SecurityUtils.getAuthenticatedUser().getId(),
                sndId, orgName, contactName, contactPhone, email, content, description);
    }

    //@PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public R all(PageQuery pageQuery) {
        //过滤已经终止并删除的对接
        ArrayList<Exist> exists = new ArrayList<>();
        exists.add(Exist.PUBLISHERS_DELETED);
        exists.add(Exist.ON_DELETED);
        pageQuery.getQuery().put("exist", exists);
        Map<String, Object> query = pageQuery.getQuery();
        String str = (String) query.get("typeStr");
        log.info(str);
        List<String> types = Arrays.asList(str.split(","));
        boolean b = types.contains("PRODUCT_SUPPLY");
        log.info("是否包含PRODUCT_SUPPLY{}", b);
        Page<Conversation> all = conversationRepo.findAll(toSpecification(pageQuery, Conversation.class), toPageRequest(pageQuery));
        List<Conversation> content = all.getContent();
        if (b) {
            List<Conversation> filteredList = content.stream()
                                                     .filter(x -> x.getType().equals(ConversationType.DOCKING)
                                                             && x.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())
                                                             && (x.getResSndType().equals(ResSnDType.PRODUCT_SUPPLY)
                                                             || x.getResSndType().equals(ResSnDType.TECH_SUPPLY)
                                                             || x.getResSndType().equals(ResSnDType.RES_SUPPLY)))
                                                            .collect(Collectors.toList());

            List<ConversationToAbutmentDTO> filteredListDto   =  filteredList.stream().map(conversation -> {
                ConversationToAbutmentDTO conversationToAbutmentDTO = new ConversationToAbutmentDTO();
                BeanUtils.copyProperties(conversation, conversationToAbutmentDTO);

                ResourceSupplyAndDemand snd = resourceSupplyAndDemandRepo.findById(conversation.getSndId())
                                                                         .orElseThrow(new BusinessException("供需不存在"));
                conversationToAbutmentDTO.setResourceName(snd.getName());
                conversationToAbutmentDTO.setResourceImag(snd.getImages());

                OrgInfo orgInfo = orgInfoRepo.findById(conversation.getOrgId())
                                             .orElseThrow(new BusinessException("无记录"));
                conversationToAbutmentDTO.setOrgName(orgInfo.getOrgName());

                return conversationToAbutmentDTO;
            }).collect(Collectors.toList());

            Page<ConversationToAbutmentDTO> filteredPage = new PageImpl<>(filteredListDto, all.getPageable(), filteredList.size());

            return R.success(filteredPage);
        } else {
            List<Conversation> filteredList = content.stream()
                                                     .filter(x -> x.getType().equals(ConversationType.DOCKING)
                                                             && x.getUserId().equals(SecurityUtils.getAuthenticatedUser().getId())
                                                             && (x.getResSndType().equals(ResSnDType.TECH_DEMAND)
                                                             || x.getResSndType().equals(ResSnDType.PRODUCT_DEMAND)
                                                             || x.getResSndType().equals(ResSnDType.FINANCING_DEMAND)))
                                                     .collect(Collectors.toList());

            List<ConversationToAbutmentDTO> filteredListDto   =  filteredList.stream().map(conversation -> {
                ConversationToAbutmentDTO conversationToAbutmentDTO = new ConversationToAbutmentDTO();
                BeanUtils.copyProperties(conversation, conversationToAbutmentDTO);

                ResourceSupplyAndDemand snd = resourceSupplyAndDemandRepo.findById(conversation.getSndId())
                                                                         .orElseThrow(new BusinessException("供需不存在"));
                conversationToAbutmentDTO.setResourceName(snd.getName());
                conversationToAbutmentDTO.setResourceImag(snd.getImages());

                OrgInfo orgInfo = orgInfoRepo.findById(conversation.getOrgId())
                                             .orElseThrow(new BusinessException("无记录"));
                conversationToAbutmentDTO.setOrgName(orgInfo.getOrgName());

                return conversationToAbutmentDTO;
            }).collect(Collectors.toList());

            Page<ConversationToAbutmentDTO> filteredPage = new PageImpl<>(filteredListDto, all.getPageable(), filteredList.size());

            return R.success(filteredPage);
        }


    }

    @GetMapping("/get/{id}")
    public ConversationDTO get(@PathVariable Long id) {
        return conversationService.get(id);
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        conversationRepo.deleteById(id);
    }

//    @GetMapping("/excel")
//    @ResponseBody
//    public void excel(HttpServletResponse response, PageQuery pageQuery) throws IOException {
//        List<Conversation> data = all(pageQuery).getContent();
//        ExcelUtils.export(response, data);
//    }

    @GetMapping("/my")
    @ApiOperation("我的对话")
    public List<ConversationDTO> my() {
        return conversationService.my(SecurityUtils.getAuthenticatedUser().getId());
    }
}

