package com.fs.wxUser.service.impl;

import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.R;
import com.fs.common.utils.DateUtils;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.param.CompanyWxUserAddGroupParam;
import com.fs.qwApi.domain.QwResult;
import com.fs.qwApi.param.QwEditUserTagParam;
import com.fs.sop.domain.QwSopLogs;
import com.fs.sop.mapper.QwSopLogsMapper;
import com.fs.voice.utils.StringUtil;
import com.fs.wxUser.domain.CompanyWxUser;
import com.fs.wxUser.domain.CompanyWxUserGroup;
import com.fs.wxUser.mapper.CompanyWxUserGroupMapper;
import com.fs.wxUser.mapper.CompanyWxUserMapper;
import com.fs.wxUser.param.CompanyWxUserBindFsUserParam;
import com.fs.wxUser.param.CompanyWxUserParam;
import com.fs.wxUser.service.ICompanyWxUserService;
import com.fs.wxUser.vo.CompanyWxUserVO;
import com.fs.wxUser.vo.QwSopLogsVo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 个微用户Service业务层处理
 *
 * @author fs
 * @date 2024-10-22
 */
@Service
@AllArgsConstructor
public class CompanyWxUserServiceImpl implements ICompanyWxUserService
{
    private final CompanyWxUserMapper companyWxUserMapper;
    private final CompanyWxUserGroupMapper companyWxUserGroupMapper;
    private final QwSopLogsMapper qwSopLogsMapper;

    /**
     * 查询个微用户
     *
     * @param userId 个微用户主键
     * @return 个微用户
     */
    @Override
    public CompanyWxUser selectCompanyWxUserByUserId(Long userId)
    {
        return companyWxUserMapper.selectCompanyWxUserByUserId(userId);
    }

    /**
     * 查询个微用户列表
     *
     * @param companyWxUser 个微用户
     * @return 个微用户
     */
    @Override
    public List<CompanyWxUser> selectCompanyWxUserList(CompanyWxUser companyWxUser)
    {
        return companyWxUserMapper.selectCompanyWxUserList(companyWxUser);
    }

    @Override
    public List<CompanyWxUserVO> selectCompanyWxUserListVO(CompanyWxUserParam param) {

        //查询分组
        CompanyWxUserGroup wxUserGroup=new CompanyWxUserGroup();
        wxUserGroup.setGroupName(param.getGroupName());
        wxUserGroup.setCompanyId(param.getCompanyId());

        if (!StringUtil.strIsNullOrEmpty(param.getGroupName())){
            List<CompanyWxUserGroup> companyWxUserGroups = companyWxUserGroupMapper.selectCompanyWxUserGroupList(wxUserGroup);
            if(companyWxUserGroups!=null && companyWxUserGroups.size()>0){
                // 使用Stream API提取groupId，去重，并收集到新的列表中
             List<Long>   uniqueGroupIds = companyWxUserGroups.stream()
                        .map(CompanyWxUserGroup::getGroupId) // 假设CompanyWxUserGroup类有getGroupId()方法
                        .distinct() // 去重
                        .collect(Collectors.toList()); // 收集到列表

                param.setUniqueGroupIds(uniqueGroupIds);
            }
        }

        return companyWxUserMapper.selectCompanyWxUserListVO(param);
    }

    /**
     * 新增个微用户
     *
     * @param companyWxUser 个微用户
     * @return 结果
     */
    @Override
    public int insertCompanyWxUser(CompanyWxUser companyWxUser)
    {
        companyWxUser.setCreateTime(DateUtils.getNowDate());
        return companyWxUserMapper.insertCompanyWxUser(companyWxUser);
    }

    /**
     * 修改个微用户
     *
     * @param companyWxUser 个微用户
     * @return 结果
     */
    @Override
    public int updateCompanyWxUser(CompanyWxUser companyWxUser)
    {
        return companyWxUserMapper.updateCompanyWxUser(companyWxUser);
    }

    /**
     * 批量删除个微用户
     *
     * @param userIds 需要删除的个微用户主键
     * @return 结果
     */
    @Override
    public int deleteCompanyWxUserByUserIds(Long[] userIds)
    {
        return companyWxUserMapper.deleteCompanyWxUserByUserIds(userIds);
    }

    /**
     * 删除个微用户信息
     *
     * @param userId 个微用户主键
     * @return 结果
     */
    @Override
    public int deleteCompanyWxUserByUserId(Long userId)
    {
        return companyWxUserMapper.deleteCompanyWxUserByUserId(userId);
    }

    @Override
    public CompanyWxUser selectCompanyWxUserByWeixinId(String weixinId) {
        return companyWxUserMapper.selectCompanyWxUserByWeixinId(weixinId);
    }

    @Override
    public R updateCompanyWxUserBindFsUser(CompanyWxUserBindFsUserParam param) {

        CompanyWxUser companyWxUser=new CompanyWxUser();
        companyWxUser.setUserId(param.getUserId());
        companyWxUser.setFsUserId(param.getFsUserId());
        int i = companyWxUserMapper.updateCompanyWxUser(companyWxUser);

        if(i>0){
            return R.ok("绑定成功");
        }else {
            return R.error("绑定失败");
        }
    }

    @Override
    public R addGroup(CompanyWxUserAddGroupParam param) {

        int suc = 0;
        List<Long> userIds = param.getUserIds();
        for (Long userId : userIds) {

            CompanyWxUser wxUser = companyWxUserMapper.selectCompanyWxUserByUserId(userId);

            String groupIds = wxUser.getGroupId();

            if (groupIds != null && groupIds != "") {
                    List<String> ids = JSON.parseArray(groupIds, String.class);
                    for (String tagId : param.getGroupIds()) {
                        ids.add(tagId);
                    }
                    Set<String> uniqueIds = new HashSet<>(ids);

                    wxUser.setGroupId(JSON.toJSONString(uniqueIds));

                } else {
                    wxUser.setGroupId(JSON.toJSONString(param.getGroupIds()));

                }
                wxUser.setUserId(userId);

                suc++;
                companyWxUserMapper.updateCompanyWxUser(wxUser);
            }


        return R.ok("成功：" + suc );
    }

    /**
    * 批量移除分组
    */
    @Override
    public R delGroup(CompanyWxUserAddGroupParam param) {
        int suc = 0;
        List<Long> userIds = param.getUserIds();
        for (Long userId : userIds) {
            CompanyWxUser wxUser = companyWxUserMapper.selectCompanyWxUserByUserId(userId);

            String groupIds = wxUser.getGroupId();

                if (groupIds != null && groupIds != "") {
                    List<String> ids = JSON.parseArray(groupIds, String.class);
                    for (String tagId : param.getGroupIds()) {
                        ids.removeIf(str -> str.equals(tagId));
                    }

                    wxUser.setGroupId(JSON.toJSONString(ids));

                    companyWxUserMapper.updateCompanyWxUser(wxUser);

                    suc++;
                }


            }

        return R.ok("成功：" + suc );
    }

    @Override
    public List<QwSopLogs> getMsg(long accountId, LocalDateTime now) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<QwSopLogs> sopLogs = qwSopLogsMapper.getWxMsgByAccountId(accountId);
//        List<QwSopLogs> expirationList = sopLogs.stream().filter(e -> isTimeExceeded(now, LocalDateTime.parse(e.getExpirationTime(), formatter))).collect(Collectors.toList());
//        qwSopLogsMapper.batchUpdateQwSopLogsByCancel(expirationList);
        return sopLogs.stream().filter(e -> isTimeInRange(now, LocalDateTime.parse(e.getSendTime(), formatter), LocalDateTime.parse(e.getExpirationTime(), formatter))).collect(Collectors.toList());
    }


    /**
     * 判断时间是否在区间内（包含边界）
     * @param time 待检查的时间
     * @param start 开始时间
     * @param end 结束时间
     * @return true=在区间内，false=不在
     */
    public static boolean isTimeInRange(LocalDateTime time, LocalDateTime start, LocalDateTime end) {
        // 处理跨天区间（如 22:00 到 02:00）
        if (end.isBefore(start)) {
            return !time.isBefore(start) || !time.isAfter(end);
        } else {
            return !time.isBefore(start) && !time.isAfter(end);
        }
    }

    /**
     * 判断时间是否超过结束时间（且不在区间内）
     * @param time 待检查的时间
     * @param end 结束时间
     * @return true=超过结束时间，false=未超过
     */
    public static boolean isTimeExceeded(LocalDateTime time, LocalDateTime end) {
        // 当天区间：超过 end 的条件是 time > end
        return time.isAfter(end);
    }

}
