package com.storlead.sales.service.impl.customer;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.HtmlUtils;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.sales.enums.QueryRangeTypeEnum;
import com.storlead.sales.pojo.dto.customer.WorkDynamicsSearchDTO;
import com.storlead.sales.pojo.entity.customer.CustomerEntity;
import com.storlead.sales.pojo.entity.customer.LiaisonEntity;
import com.storlead.sales.pojo.entity.customer.WorkDynamicsEntity;
import com.storlead.sales.pojo.vo.customer.LiaisonListVO;
import com.storlead.sales.pojo.vo.customer.WorkDynamicsListVO;
import com.storlead.sales.mapper.customer.WorkDynamicsMapper;
import com.storlead.sales.service.customer.CustomerService;
import com.storlead.sales.service.customer.WorkDynamicsService;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.user.pojo.entity.JobEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IJobService;
import com.storlead.user.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 工作动态表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2025-05-28
 */
@Service
public class WorkDynamicsServiceImpl extends MyBaseServiceImpl<WorkDynamicsMapper, WorkDynamicsEntity> implements WorkDynamicsService {

    @Resource
    private CustomerService customerService;
    @Resource
    private IJobService  jobService;
    @Resource
    private IUserService userService;
    @Override
    public Result<?> addOrEdit(WorkDynamicsEntity workDynamics) {
        return null;
    }

    @Override
    public Result<?> selectListVO(WorkDynamicsSearchDTO workDynamicsSearchDTO) {
        if (ObjectUtils.isEmpty(workDynamicsSearchDTO.getSortMethod())) {
            workDynamicsSearchDTO.setSortMethod("desc");
        }
        if (ObjectUtils.isEmpty(workDynamicsSearchDTO.getCommonQueryOrderBy())){
            workDynamicsSearchDTO.setCommonQueryOrderBy("id");
        }
        Long loginUserId = LoginUserUtil.getCurrentUserId();

        IPage<WorkDynamicsListVO> pageVO = new Page<>(workDynamicsSearchDTO.getPageIndex(), workDynamicsSearchDTO.getPageSize());
        IPage<WorkDynamicsEntity> page = new Page<>(workDynamicsSearchDTO.getPageIndex(), workDynamicsSearchDTO.getPageSize());
        LambdaQueryWrapper<WorkDynamicsEntity> wrapper = new LambdaQueryWrapper<>();


        wrapper.eq(!ObjectUtils.isEmpty(workDynamicsSearchDTO.getCustomerId()), WorkDynamicsEntity::getCustomerId, workDynamicsSearchDTO.getCustomerId());
        wrapper.eq(WorkDynamicsEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
//        wrapper.orderByDesc(LiaisonEntity::getHasPrimaryLialison,LiaisonEntity::getId);
        if (Objects.nonNull(workDynamicsSearchDTO.getQueryRangeType())) {
            String queryRangeSql = QueryRangeTypeEnum.getQueryRangeSql(workDynamicsSearchDTO.getQueryRangeType(),LoginUserUtil.getCurrentUserId());
            if (StrUtil.isNotBlank(queryRangeSql)) {
                wrapper.apply(queryRangeSql);
            }
        }

        List<Long> customerIds = customerService.getCustomerIdList(loginUserId);
        String customerIdString = customerIds.stream().map(String::valueOf).collect(Collectors.joining(","));

        StringBuilder mergeSql = new StringBuilder();

        String v1 = StrUtil.isBlank(customerIdString) ? "" : " customer_id in ( "+customerIdString +") or ";
        mergeSql.append(v1);

        String v2 = "owner_by in (select id from `user` WHERE  FIND_IN_SET("+loginUserId+",managers))";
        mergeSql.append(v2);

        IPage<WorkDynamicsEntity> pageList = this.pageWithScope(page, wrapper,workDynamicsSearchDTO,mergeSql.toString());
        if (CollectionUtils.isEmpty(pageList.getRecords())){
            return Result.result(pageList);
        }
        //去除内容和标题的html标签
//        pageList.getRecords().forEach(e->{
//            e.setContent(HtmlUtils.clearContent(e.getContent()));
//            e.setTitle(HtmlUtils.clearContent(e.getTitle()));
//        });
//        List<LiaisonListVO> list = new ArrayList<>();
        //复制list给VO类
        pageVO = SysBaseField.page(page, WorkDynamicsListVO.class);
        Set<Long> userIdList = pageList.getRecords().stream().filter(e->e.getOwnerBy()!=null).map(WorkDynamicsEntity::getOwnerBy).collect(Collectors.toSet());
        if (!CollectionUtils.isEmpty(userIdList)){
            Map<Long, UserEntity> userMap = userService.IdListToUserMap(userIdList.stream().collect(Collectors.toList()));
            Collection<UserEntity> users = userService.listByIds(userIdList);

            Map<Long, JobEntity> jobMap = jobService.getJobMap(users);
            if (Objects.nonNull(jobMap)) {
                for (WorkDynamicsListVO workDynamicsListVO : pageVO.getRecords()) {
                    if (Objects.nonNull(workDynamicsListVO.getOwnerBy())) {
                        UserEntity user = userMap.get(workDynamicsListVO.getOwnerBy());
                        if (Objects.nonNull(user)) {
                            JobEntity job = jobMap.get(user.getJobId());
                            if (Objects.nonNull(job)) {
                                workDynamicsListVO.setOwnerByJobName(job.getName());
                            }
                        }
                    }
                }
            }
        }
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());

        return Result.result(pageVO);
    }
}
