package com.eitc.patient.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eitc.common.annotation.Anonymous;
import com.eitc.common.annotation.Log;
import com.eitc.common.core.controller.BaseController;
import com.eitc.common.core.domain.AjaxResult;
import com.eitc.common.enums.BusinessType;
import com.eitc.common.utils.JWTUtil;
import com.eitc.common.utils.MinioUtils;
import com.eitc.patient.domain.ChatDisease;
import com.eitc.patient.domain.ChatDiseaseInfo;
import com.eitc.patient.domain.ChatHistory;
import com.eitc.patient.service.IAppUserService;
import com.eitc.patient.service.IChatDiseaseInfoService;
import com.eitc.patient.service.IChatDiseaseService;
import com.eitc.patient.service.IChatHistoryService;
import com.eitc.patient.vo.AppUserVo;
import com.eitc.patient.vo.SysUserVo;
import com.eitc.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;










@Api(tags = "App聊天消息接口")
@RestController
@RequestMapping("app/chat")
public class AppChatController extends BaseController {

    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IChatDiseaseService chatDiseaseService;
    @Autowired
    private IChatDiseaseInfoService chatDiseaseInfoService;
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private IChatHistoryService chatHistoryService;
    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * 患者获取医生聊天列表
     * @param userId
     * @return
     */
    @GetMapping("/getChatList")
    @ApiOperation("患者获取医生聊天列表")
    @Anonymous
    public AjaxResult getUserList(String userId) {
        List<ChatHistory> list = chatHistoryService.list(Wrappers.<ChatHistory>lambdaQuery()
//                .eq(ChatHistory::getIsRead, 0)
                .eq(ChatHistory::getAppUserId, userId).or().eq(ChatHistory::getUserId, userId));
        List<SysUserVo> appUserList = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            Map<String, List<ChatHistory>> map = list.stream().filter(d -> d.getIsRead() == 0).collect(Collectors.groupingBy(ChatHistory::getAppUserId));
            List<String> collect = list.stream().map(ChatHistory::getAppUserId).distinct().collect(Collectors.toList());
            collect.removeAll(Collections.singletonList(null));
            List<String> userList = list.stream().map(ChatHistory::getUserId).distinct().collect(Collectors.toList());
            userList.removeAll(Collections.singletonList(null));
            collect.addAll(userList);
            if (!collect.isEmpty()){
                appUserList = sysUserService.selectSysUserList(collect).stream().map(x -> {
                    SysUserVo sysUserVo = new SysUserVo();
                    BeanUtils.copyProperties(x, sysUserVo);
                    if (map.get(x.getUserId()) != null) {
                        sysUserVo.setNumber(map.get(x.getUserId()).size());
                    }
                    return sysUserVo;
                }).collect(Collectors.toList());
            }
        }
        return AjaxResult.success(appUserList);
    }

    /**
     * 问诊资料保存
     */
    @Log(title = "问诊资料保存", businessType = BusinessType.UPDATE)
    @PutMapping("editChatDisease")
    @ApiOperation("问诊资料保存")
    @Anonymous
    public AjaxResult edit(@Validated @RequestBody ChatDisease chatDisease) {
        if (chatDisease.getPatientId() == null) {
            throw new RuntimeException("参数错误");
        }
        List<ChatDisease> list = chatDiseaseService.list(Wrappers.<ChatDisease>lambdaQuery()
                .eq(ChatDisease::getPatientId, chatDisease.getPatientId()));
        ChatDisease chatDiseasesave = new ChatDisease();

//            BeanUtils.copyProperties(list.get(0),chatDiseasesave);
        BeanUtils.copyProperties(chatDisease, chatDiseasesave);
        if (list != null && !list.isEmpty())
            chatDiseasesave.setId(list.get(0).getId());
        // 上传图片

        String[] split = chatDisease.getUrl().split(",");
        chatDiseasesave.setCreateUser(JWTUtil.getAppUserId());
        chatDiseasesave.setUpdateUser(JWTUtil.getAppUserId());
        chatDiseaseService.saveOrUpdate(chatDiseasesave);
        // 先删除
        Collection<ChatDiseaseInfo> relist = chatDiseaseInfoService.list(Wrappers.<ChatDiseaseInfo>lambdaQuery()
                .eq(ChatDiseaseInfo::getChatDiseaseId, chatDiseasesave.getId()));
        if (relist != null && !relist.isEmpty()){
            minioUtils.removeFiles(bucketName, relist.stream().map(ChatDiseaseInfo::getUrl).collect(Collectors.toList()));
        }

        chatDiseaseInfoService.remove(Wrappers.<ChatDiseaseInfo>lambdaQuery()
                .eq(ChatDiseaseInfo::getChatDiseaseId, chatDiseasesave.getId()));

        for (String str : split) {

            ChatDiseaseInfo chatDiseaseInfo = new ChatDiseaseInfo();
            chatDiseaseInfo.setChatDiseaseId(chatDiseasesave.getId());
            chatDiseaseInfo.setUrl(str.trim());
            chatDiseaseInfo.setCreateUser(JWTUtil.getAppUserId());
            chatDiseaseInfo.setUpdateUser(JWTUtil.getAppUserId());
            chatDiseaseInfoService.save(chatDiseaseInfo);
        }

        return success();
    }


    /**
     * 问诊资料查询
     */
    @Log(title = "问诊资料查询", businessType = BusinessType.UPDATE)
    @GetMapping("getChatDisease")
    @ApiOperation("问诊资料查询")
    @Anonymous
    public AjaxResult getChatDisease(String patientId) {
        if (patientId == null) {
            throw new RuntimeException("参数错误");
        }
        List<ChatDisease> list = chatDiseaseService.list(Wrappers.<ChatDisease>lambdaQuery()
                .eq(ChatDisease::getPatientId, patientId));
        if (list != null && !list.isEmpty()) {
            ChatDisease chatDisease = list.get(0);
            String collect = chatDiseaseInfoService.list(Wrappers.<ChatDiseaseInfo>lambdaQuery()
                    .eq(ChatDiseaseInfo::getChatDiseaseId, chatDisease.getId())).stream().map(ChatDiseaseInfo::getUrl).collect(Collectors.joining(","));
            chatDisease.setUrl(collect);
            return success(chatDisease);
        } else {
            return success();
        }
    }


    /**
     * 医生获取患者列表
     * @param dockerId
     * @return
     */
    @GetMapping("/getChatPatientList")
    @ApiOperation("医生获取患者列表")
    @Anonymous
    public AjaxResult getChatPatientList(String dockerId) {
        List<ChatHistory> list = chatHistoryService.list(Wrappers.<ChatHistory>lambdaQuery()
//                .eq(ChatHistory::getIsRead, 0)
                .eq(ChatHistory::getUserId, dockerId));
        List<AppUserVo> appUserList = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            Map<String, List<ChatHistory>> map = list.stream().filter(d -> d.getIsRead() == 0).collect(Collectors.groupingBy(ChatHistory::getAppUserId));
            List<String> collect = list.stream().map(ChatHistory::getAppUserId).distinct().collect(Collectors.toList());
            collect.removeAll(Collections.singletonList(null));
            appUserList = appUserService.listByIds(collect).stream().map(x -> {
                AppUserVo appUserVo = new AppUserVo();
              BeanUtils.copyProperties(x, appUserVo);
                if (map.get(x.getId()) != null) {
                    appUserVo.setMsgNumber((long) map.get(x.getId()).size());
                }
                return appUserVo;
            }).collect(Collectors.toList());
        }
        return AjaxResult.success(appUserList);
    }

}
