package com.fs.company.controller.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.qw.param.QwExternalContactVOTime;
import com.fs.qw.param.QwTagSearchParam;
import com.fs.qw.param.SopExternalContactInfo;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.qw.service.IQwTagService;
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 com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
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.Optional;
import java.util.function.Predicate;
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 IQwTagService iQwTagService;

    private static final Gson GSON = new Gson();

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

        if (!list.isEmpty()) {
            // 使用并行流提取externalId
            List<Long> externalIdList = list.parallelStream()
                    .map(SopUserLogsInfo::getExternalId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

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

            // 构建联系人信息映射
            Map<Long, SopExternalContactInfo> externalContactInfoMap = qwExternalContactVOTimes.stream()
                    .collect(Collectors.toMap(
                            QwExternalContactVOTime::getId,
                            item -> new SopExternalContactInfo(item.getCreateTime(), item.getTagIds(), item.getRemark())
                    ));

            // 设置联系信息
            list.forEach(item -> {
                SopExternalContactInfo info = externalContactInfoMap.getOrDefault(
                        item.getExternalId(),
                        new SopExternalContactInfo("无进线时间", "无标签", "无备注"));
                item.setInComTime(info.getCreateTime());
                item.setTagIds(info.getTagIds());
                item.setRemark(info.getRemark());
            });
        }

        // 优化过滤条件
        boolean isRemarkEmpty = StringUtil.strIsNullOrEmpty(sopUserLogsInfo.getRemark());
        Predicate<SopUserLogsInfo> tagFilter = item ->
                sopUserLogsInfo.getTagIds() == null ||
                        sopUserLogsInfo.getTagIds().isEmpty() ||
                        item.getTagIds().contains(sopUserLogsInfo.getTagIds());

        Predicate<SopUserLogsInfo> remarkFilter = item ->
                isRemarkEmpty ||
                        item.getRemark().contains(sopUserLogsInfo.getRemark());

        if (sopUserLogsInfo.getTagIds() != null || !isRemarkEmpty) {
            list = list.stream()
                    .filter(tagFilter.and(remarkFilter))
                    .collect(Collectors.toList());
        }

        // 处理标签名称
        list.parallelStream().forEach(item -> {
            if (item.getTagIds() != null && !item.getTagIds().equals("[]") && !item.getTagIds().equals("无标签")) {
                List<String> tagIds = GSON.fromJson(item.getTagIds(), new TypeToken<List<String>>() {}.getType());
                QwTagSearchParam param = new QwTagSearchParam();
                param.setTagIds(tagIds);
                item.setTagIdsName(iQwTagService.selectQwTagListByTagIds(param));
            }
        });

        return getDataTable(list);
//        startPage();
//        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());
//        }
//
//
//        list.forEach(item->{
//
//            if (!Objects.equals(item.getTagIds(), "[]") && !Objects.equals(item.getTagIds(), "无标签") && item.getTagIds()!=null) {
//                QwTagSearchParam param = new QwTagSearchParam();
//                Gson gson = new Gson();
//                List<String> tagIds = gson.fromJson(
//                        item.getTagIds(),
//                        new TypeToken<List<String>>() {
//                        }.getType()
//                );
//
//                param.setTagIds(tagIds);
//
//                item.setTagIdsName(iQwTagService.selectQwTagListByTagIds(param));
//            }
//        });
//
//        return getDataTable(list);
    }


//    /**
//     * 导出sopUserLogsInfo列表
//     */
//    @PreAuthorize("@ss.hasPermi('qw:sop:export')")
//    @Log(title = "sopUserLogsInfo", businessType = BusinessType.EXPORT)
//    @GetMapping("/export")
//    public AjaxResult export(SopUserLogsInfo sopUserLogsInfo)
//    {
//        List<SopUserLogsInfoVOE> list = sopUserLogsInfoService.selectSopUserLogsInfoListVO(sopUserLogsInfo);
//
//        if (!list.isEmpty()){
//
//            List<Long> externalIdList = list.stream()
//                    .map(SopUserLogsInfoVOE::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, SopExternalContactInfoEx> externalContactInfoMap = qwExternalContactVOTimes.stream()
//                    .collect(Collectors.toMap(
//                            QwExternalContactVOTime::getId,
//                            item -> new SopExternalContactInfoEx(item.getCreateTime(),item.getRemark(),item.getFsUserId(),item.getAvatar())
//                    ));
//
//            // 遍历 list，赋值 inComTime 和 tagIds
//            list.forEach(item -> {
//                SopExternalContactInfoEx info = externalContactInfoMap.getOrDefault(item.getExternalId(), new SopExternalContactInfoEx("无进线时间","无备注","未绑定小程序账号","无头像"));
//                item.setInComTime(info.getCreateTime());
//                item.setRemark(info.getRemark());
//                item.setFsUserId(info.getFsUserId());
//                item.setAvatar(info.getAvatar());
//            });
//
//        }
//
//        ExcelUtil<SopUserLogsInfoVOE> util = new ExcelUtil<SopUserLogsInfoVOE>(SopUserLogsInfoVOE.class);
//        return util.exportExcel(list, "营期数据");
//    }

    /**
     * 获取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));
    }
}
