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.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.enums.QueryRangeTypeEnum;
import com.storlead.sales.pojo.dto.customer.SendRecordSearchDTO;
import com.storlead.sales.pojo.entity.customer.*;
import com.storlead.sales.pojo.vo.customer.*;
import com.storlead.sales.pojo.vo.customer.SendRecordDetailVO;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.mapper.customer.SendRecordMapper;
import com.storlead.sales.service.customer.CustomerFollowUpService;
import com.storlead.sales.service.customer.CustomerService;
import com.storlead.sales.service.customer.LiaisonService;
import com.storlead.sales.service.customer.SendRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.storlead.system.pojo.dto.DictExtQueryParam;
import com.storlead.system.pojo.entity.SysDictDetailEntity;
import com.storlead.system.service.SysDictDetailService;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IUserService;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 寄样记录表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-04-25
 */
@Service
public class SendRecordServiceImpl extends MyBaseServiceImpl<SendRecordMapper, SendRecordEntity> implements SendRecordService {

    @Resource
    private IUserService userService;
    @Resource
    private LiaisonService liaisonService;
    @Resource
    private CustomerService customerService;
    @Resource
    private SysDictDetailService dictDetailService;
    @Resource
    private CustomerFollowUpService customerFollowUpService;
    @Override
    public Result<?> selectListVO(SendRecordSearchDTO sendRecordSearchDTO) {

        //当前用户
        Long currentUserId = LoginUserUtil.getCurrentUserId();

        IPage<SendRecordListVO> pageVO =new Page<>(sendRecordSearchDTO.getPageIndex(), sendRecordSearchDTO.getPageSize());
        IPage<SendRecordEntity> page = new Page<>(sendRecordSearchDTO.getPageIndex(), sendRecordSearchDTO.getPageSize());
        LambdaQueryWrapper<SendRecordEntity> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(sendRecordSearchDTO.getBlurry())) {
            wrapper.and(w ->w.like(SendRecordEntity::getSendProduct,sendRecordSearchDTO.getBlurry()).or().like(SendRecordEntity::getProductDescription,sendRecordSearchDTO.getBlurry()));
        }
        wrapper.like(!ObjectUtils.isEmpty(sendRecordSearchDTO.getSendProduct()), SendRecordEntity::getSendProduct, sendRecordSearchDTO.getSendProduct());
        wrapper.ge(!ObjectUtils.isEmpty(sendRecordSearchDTO.getSendRecordBeginTime()), SendRecordEntity::getSendRecordTime, sendRecordSearchDTO.getSendRecordBeginTime());
        wrapper.le(!ObjectUtils.isEmpty(sendRecordSearchDTO.getSendRecordEndTime()), SendRecordEntity::getSendRecordTime, sendRecordSearchDTO.getSendRecordEndTime());
        wrapper.eq(!ObjectUtils.isEmpty(sendRecordSearchDTO.getCustomerId()),SendRecordEntity::getCustomerId, sendRecordSearchDTO.getCustomerId());
        wrapper.eq(!ObjectUtils.isEmpty(sendRecordSearchDTO.getResourceTypeId()),SendRecordEntity::getResourceTypeId, sendRecordSearchDTO.getResourceTypeId());
        wrapper.eq(!ObjectUtils.isEmpty(sendRecordSearchDTO.getResourceType()),SendRecordEntity::getResourceType, sendRecordSearchDTO.getResourceType());
        wrapper.eq(!ObjectUtils.isEmpty(sendRecordSearchDTO.getSendMemberId()),SendRecordEntity::getSendMemberId, sendRecordSearchDTO.getSendMemberId());
        wrapper.in(!CollectionUtils.isEmpty(sendRecordSearchDTO.getOwnerByIds()),SendRecordEntity::getOwnerBy, sendRecordSearchDTO.getOwnerByIds());
        wrapper.eq(SendRecordEntity::getIsDelete, CommonConstant.DEL_FLAG_0);

        if (QueryRangeTypeEnum.QUERY_MY_OWNERBY_SQL.getCode().equals(sendRecordSearchDTO.getQueryRangeType())) {
            wrapper.eq(SendRecordEntity::getSendMemberId,currentUserId);
        } else if (QueryRangeTypeEnum.QUERY_SUBORDINATE_SQL.getCode().equals(sendRecordSearchDTO.getQueryRangeType())) {
           wrapper.apply(" send_member_id in (select id from `user` WHERE  FIND_IN_SET("+currentUserId+",managers)) ");
        }

        Long loginUserId = LoginUserUtil.getCurrentUserId();
        StringBuilder mergeSql = new StringBuilder();
        List<Long> customerIds = customerService.getCustomerIdList(loginUserId);
        String customerIdString = customerIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        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);

//        wrapper.orderByDesc(SendRecordEntity::getSendRecordTime);
        page = pageWithScope(page, wrapper,sendRecordSearchDTO, mergeSql.toString());
        if (CollectionUtils.isEmpty(page.getRecords())){
            return Result.result(page);
        }
        DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<SendRecordListVO> sendRecordListVOList = mapperFactory.getMapperFacade().mapAsList(page.getRecords(),SendRecordListVO.class);
        //添加客户信息customerName
        Set<Long> customerIdList = sendRecordListVOList.stream().filter(e->e.getCustomerId()!=null).map(SendRecordListVO::getCustomerId).collect(Collectors.toSet());
        Map<Long, CustomerEntity> customerMap = customerService.getCustomerMap(customerIdList);
        for (SendRecordListVO sendRecordVo : sendRecordListVOList) {
            if (!ObjectUtils.isEmpty(customerMap.get(sendRecordVo.getCustomerId()))) {
                sendRecordVo.setCustomerName(customerMap.get(sendRecordVo.getCustomerId()).getCustomerName());
            }
        }
//        获取联系人信息
        List<Long> liaisonList = sendRecordListVOList.stream().map(SendRecordListVO::getReceiveLiaisonId).collect(Collectors.toList());
        Map<Long, LiaisonEntity> liaisonMap = liaisonService.idListToLiaisonMap(liaisonList);
        if (!CollectionUtils.isEmpty(liaisonList) && !CollectionUtils.isEmpty(liaisonMap)) {
            sendRecordListVOList.forEach(sendRecordListVO -> {
                LiaisonEntity liaisonEntity = liaisonMap.get(sendRecordListVO.getReceiveLiaisonId());
                if (ObjectUtils.isEmpty(liaisonEntity)) {
                    return;
                }
                sendRecordListVO.setReceiveLiaisonName(liaisonEntity.getName());
            });
        }
                pageVO.setTotal(page.getTotal());
        pageVO.setPages(page.getPages());
        pageVO.setRecords(sendRecordListVOList);
        pageVO.setCurrent(page.getCurrent());
        SysBaseField.orgFileds(sendRecordListVOList);
        SysBaseField.dictFileds(pageVO.getRecords());

        return Result.result(pageVO);
    }

    @Override
    public SendRecordDetailVO getSendRecordVOById(Long id) {
        SendRecordEntity sendRecord = getById(id);
        if (!ObjectUtils.isEmpty(sendRecord)){
            SendRecordDetailVO sendRecordVO = new SendRecordDetailVO();
            BeanUtils.copyProperties(sendRecord, sendRecordVO);
//            sendRecordVO.setRecordAmount(sendRecordVO.getRecordAmount().setScale(2, RoundingMode.HALF_UP));
//            DecimalFormat decimalFormat = new DecimalFormat("#.00"); // 注意这里的模式字符串
//            sendRecordVO.setRecordAmount(decimalFormat.format(sendRecordVO.getRecordAmount()));
            //添加客户名称
            CustomerEntity customer = customerService.getById(sendRecord.getCustomerId());
            if (Objects.nonNull(customer)) {
                sendRecordVO.setCustomerName(customer.getCustomerName());
            }
            //添加收样人员姓名
            LiaisonEntity liaison = liaisonService.getById(sendRecord.getReceiveLiaisonId());
            if (!ObjectUtils.isEmpty(liaison)) {
                sendRecordVO.setReceiveLiaisonName(liaison.getName());
            }
            sendRecordVO.dictFiled();
            SysBaseField.orgFileds(sendRecordVO);

            //添加下一个id
            SendRecordEntity next = getNextById(id, new LambdaQueryWrapper<SendRecordEntity>().eq(SendRecordEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
            if (!ObjectUtils.isEmpty(next)){
                sendRecordVO.setNextId(next.getId());
            }
            //添加上一个id
            SendRecordEntity previous = getPreviousById(id, new LambdaQueryWrapper<SendRecordEntity>().eq(SendRecordEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
            if (!ObjectUtils.isEmpty(previous)){
                sendRecordVO.setPreviousId(previous.getId());
            }

            Map<String, SysDictDetailEntity> dictMap = dictDetailService.getDictDetailByCode("work_data_group");
            if (!CollectionUtils.isEmpty(dictMap)) {
                Gson gson = new Gson();

                if (Objects.isNull(sendRecordVO.getResourceType())) {
                    return sendRecordVO;
                }
                //返回资源类型名称
                sendRecordVO.setResourceTypeName(ResourceTypeEnum.getDescByCode(sendRecordVO.getResourceType()));
                String resourceName = customerFollowUpService.getResourceTyepName(sendRecordVO.getResourceType(), sendRecordVO.getResourceTypeId());

                sendRecordVO.setResourceName(resourceName);
            }

            return sendRecordVO;
        }
        return null;
    }
}
