package com.fs.qw;


import com.fs.common.annotation.Log;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.StringUtils;
import com.fs.qw.domain.QwGroupChatUser;
import com.fs.qw.param.QwExternalContactVOTime;
import com.fs.qw.param.SopExternalContactInfo;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.qw.service.IQwGroupChatUserService;
import com.fs.sop.domain.SopUserLogsInfo;
import com.fs.sop.params.BatchSopUserLogsInfoParam;
import com.fs.sop.params.SendUserLogsInfoMsgParam;
import com.fs.sop.service.ISopUserLogsInfoService;
import com.fs.voice.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * sopUserLogsInfoController
 *
 * @author fs
 * @date 2024-12-27
 */
@RestController
@RequestMapping("/qwSop/sopUserLogsInfo")
public class SopUserLogsInfoController extends BaseController {
    @Autowired
    private ISopUserLogsInfoService sopUserLogsInfoService;

    @Autowired
    private IQwExternalContactService iQwExternalContactService;

    @Autowired
    private IQwGroupChatUserService qwGroupChatUserService;

    /**
     * 查询sopUserLogsInfo列表
     */
    @PreAuthorize("@ss.hasPermi('qw:sop:list')")
    @GetMapping("/list")
    public TableDataInfo list(SopUserLogsInfo sopUserLogsInfo) {
        startPage();
        if (sopUserLogsInfo.getFilterMode() == 1) {
            List<SopUserLogsInfo> list = sopUserLogsInfoService.selectSopUserLogsInfoList(sopUserLogsInfo);

            if (!list.isEmpty()) {

                List<Long> externalIdList = list.stream()
                        .map(SopUserLogsInfo::getExternalId) // 提取 externalId
                        .filter(Objects::nonNull) // 过滤掉 null 值，防止 NullPointerException
                        .collect(Collectors.toList()); // 收集到 List

                List<QwExternalContactVOTime> qwExternalContactVOTimes = iQwExternalContactService.selectQwExternalContactListVOByIds(externalIdList);


                // 先将 qwExternalContactVOTimes 转换为 Map，key 为 id，value 为 ExternalContactInfo（包含 createTime 和 tagIds）
                Map<Long, SopExternalContactInfo> externalContactInfoMap = qwExternalContactVOTimes.stream()
                        .collect(Collectors.toMap(
                                QwExternalContactVOTime::getId,
                                item -> new SopExternalContactInfo(item.getCreateTime(), item.getTagIds(), item.getRemark())
                        ));

                // 遍历 list，赋值 inComTime 和 tagIds
                list.forEach(item -> {
                    SopExternalContactInfo info = externalContactInfoMap.getOrDefault(item.getExternalId(), new SopExternalContactInfo("无进线时间", "无标签", "无备注"));
                    item.setInComTime(info.getCreateTime());
                    item.setTagIds(info.getTagIds());
                    item.setRemark(info.getRemark());
                });

            }

            if ((sopUserLogsInfo.getTagIds() != null && !sopUserLogsInfo.getTagIds().isEmpty())
                    || !StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getRemark())) {
                list = list.stream()
                        .filter(item ->
                                (sopUserLogsInfo.getTagIds() == null || sopUserLogsInfo.getTagIds().isEmpty() || item.getTagIds().contains(sopUserLogsInfo.getTagIds()))
                                        && (StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getRemark()) || item.getRemark().contains(sopUserLogsInfo.getRemark()))
                        )
                        .collect(Collectors.toList());
            }

            return getDataTable(list);
        } else {
            List<QwGroupChatUser> list = qwGroupChatUserService.selectByChatId(sopUserLogsInfo);


            if (!list.isEmpty()) {

                List<String> externalIdList = list.stream()
                        .map(QwGroupChatUser::getUserId) // 提取 externalId
                        .filter(StringUtils::isNotEmpty) // 过滤掉 null 值，防止 NullPointerException
                        .distinct()
                        .collect(Collectors.toList()); // 收集到 List

                List<QwExternalContactVOTime> qwExternalContactVOTimes = iQwExternalContactService.selectQwExternalContactListVOByUserIds(externalIdList);


                // 先将 qwExternalContactVOTimes 转换为 Map，key 为 id，value 为 ExternalContactInfo（包含 createTime 和 tagIds）
                Map<String, SopExternalContactInfo> externalContactInfoMap = qwExternalContactVOTimes.stream()
                        .collect(Collectors.toMap(
                                QwExternalContactVOTime::getExternalUserId,
                                item -> new SopExternalContactInfo(item.getCreateTime(), item.getTagIds(), item.getRemark())
                        ));

                // 遍历 list，赋值 inComTime 和 tagIds
                list.forEach(item -> {
                    SopExternalContactInfo info = externalContactInfoMap.getOrDefault(item.getUserId(), new SopExternalContactInfo("无进线时间", "无标签", "无备注"));
                    item.setInComTime(info.getCreateTime());
                    item.setTagIds(info.getTagIds());
                    item.setRemark(info.getRemark());
                });

            }

            if ((sopUserLogsInfo.getTagIds() != null && !sopUserLogsInfo.getTagIds().isEmpty())
                    || !StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getRemark())) {
                list = list.stream()
                        .filter(item ->
                                (sopUserLogsInfo.getTagIds() == null || sopUserLogsInfo.getTagIds().isEmpty() || item.getTagIds().contains(sopUserLogsInfo.getTagIds()))
                                        && (StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getRemark()) || item.getRemark().contains(sopUserLogsInfo.getRemark()))
                        )
                        .collect(Collectors.toList());
            }
            return getDataTable(list);
        }

//        if (sopUserLogsInfo.getTagIds() != null && !sopUserLogsInfo.getTagIds().isEmpty()) {
//            list = list.stream()
//                    .filter(item -> item.getTagIds().contains(sopUserLogsInfo.getTagIds()))
//                    .collect(Collectors.toList());
//        }
//        if (!StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getRemark())) {
//            list = list.stream()
//                    .filter(item -> item.getRemark().contains(sopUserLogsInfo.getRemark()))
//                    .collect(Collectors.toList());
//        }
    }

//    /**
//     * 导出sopUserLogsInfo列表
//     */
//    @PreAuthorize("@ss.hasPermi('sopUserLogsInfo:sopUserLogsInfo:export')")
//    @Log(title = "sopUserLogsInfo", businessType = BusinessType.EXPORT)
//    @GetMapping("/export")
//    public AjaxResult export(SopUserLogsInfo sopUserLogsInfo)
//    {
//        List<SopUserLogsInfo> list = sopUserLogsInfoService.selectSopUserLogsInfoList(sopUserLogsInfo);
//        ExcelUtil<SopUserLogsInfo> util = new ExcelUtil<SopUserLogsInfo>(SopUserLogsInfo.class);
//        return util.exportExcel(list, "sopUserLogsInfo数据");
//    }
//

    /**
     * 获取sopUserLogsInfo详细信息
     */
    @PreAuthorize("@ss.hasPermi('qw:sop:list')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(sopUserLogsInfoService.selectSopUserLogsInfoById(id));
    }

    /**
     * 修改sopUserLogsInfo 修改营期
     */
    @PreAuthorize("@ss.hasPermi('qw:sopUserLogsInfo:edit')")
    @Log(title = "updateSopUserLogsInfo", businessType = BusinessType.UPDATE)
    @PostMapping("/batchUpdateSopUserLogsInfoToTime")
    public R edit(@RequestBody BatchSopUserLogsInfoParam param) {
        return sopUserLogsInfoService.batchUpdateSopUserLogsInfoToTime(param);
    }

    /**
     * 一键群发sopUserLogsInfo
     */
    @PreAuthorize("@ss.hasPermi('qw:sopUserLogsInfo:msg')")
    @Log(title = "sendMsgSopUserLogsInfo", businessType = BusinessType.INSERT, isSaveRequestData = false)
    @PostMapping("/sendUserLogsInfoMsg")
    @RepeatSubmit
    public R sendUserLogsInfoMsg(@RequestBody SendUserLogsInfoMsgParam param) {
        return sopUserLogsInfoService.sendUserLogsInfoMsg(param);
    }

    /**
     * 删除sopUserLogsInfo
     */
    @PreAuthorize("@ss.hasPermi('qw:sopUserLogsInfo:remove')")
    @Log(title = "deleteSopUserLogsInfo", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(sopUserLogsInfoService.deleteSopUserLogsInfoByIds(ids));
    }
}
