package com.bonus.material.book.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.constant.MaterialConstants;
import com.bonus.common.biz.domain.BmFileInfo;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.book.domain.BookCarInfoDto;
import com.bonus.material.book.domain.BookCarVo;
import com.bonus.material.book.domain.CompanyPersonPhoneKey;
import com.bonus.material.book.mapper.BookCarMapper;
import com.bonus.material.book.service.BookCarService;
import com.bonus.material.device.domain.vo.DevInfoVo;
import com.bonus.material.device.mapper.BmFileInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author：liang.chao
 * @Date：2024/11/22 - 16:53
 */
@Slf4j
@Service
public class BookCarServiceImpl implements BookCarService {
    @Resource
    private BookCarMapper bookCarMapper;

    @Resource
    private BmFileInfoMapper bmFileInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addBookCar(BookCarInfoDto bookCarInfoDto) {
        Long userId = SecurityUtils.getLoginUser().getUserid();
        bookCarInfoDto.setCreater(userId.toString());
        bookCarInfoDto.setOrderUser(userId);
        //先根据设备id查询设备信息
        DevInfoVo devInfoVo = bookCarMapper.selectDevInfoByMaId(bookCarInfoDto.getMaId(), userId, bookCarInfoDto.getDevType());
        if (devInfoVo != null) {
            return AjaxResult.error("该设备已添加到预约车，请勿重复添加");
        }
        Integer result = bookCarMapper.addBookCarDetail(bookCarInfoDto);
        if (result > 0) {
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    @Override
    public AjaxResult getBookCarDetails(BookCarInfoDto bookCarInfoDto) {
        List<BookCarVo> list = new ArrayList<>();
        Long userId = SecurityUtils.getLoginUser().getUserid();
        bookCarInfoDto.setOrderUser(userId);
        List<DevInfoVo> bookCarDetails = new ArrayList<>();
        bookCarDetails = bookCarMapper.getBookCarDetails(bookCarInfoDto);
        // 如果 bookCarDetails 不为空，处理文件信息
        if (CollectionUtils.isNotEmpty(bookCarDetails)) {
            // 为每个 DevInfoVo 设置文件信息
            for (DevInfoVo bookCarDetail : bookCarDetails) {
                BmFileInfo bmFileInfo = new BmFileInfo();
                bmFileInfo.setModelId(bookCarDetail.getMaId());
                bmFileInfo.setTaskType(MaterialConstants.MATERIAL_FILE_TYPE_CODE);
                bmFileInfo.setFileType(0L);
                List<BmFileInfo> mainFileInfoList = bmFileInfoMapper.selectBmFileInfoList(bmFileInfo);
                if (!CollectionUtils.isEmpty(mainFileInfoList)) {
                    bookCarDetail.setPicUrl(mainFileInfoList.get(0).getFileUrl());
                }
            }

            // 根据 companyName, person, personPhone 进行分组
            Map<CompanyPersonPhoneKey, List<DevInfoVo>> groupedByKey = bookCarDetails.stream()
                    .collect(Collectors.groupingBy(bookCarDetail -> new CompanyPersonPhoneKey(
                            bookCarDetail.getCompanyName(),
                            bookCarDetail.getCompanyId(),
                            bookCarDetail.getPerson(),
                            bookCarDetail.getPersonPhone()
                    )));

            // 遍历分组，创建每个分组的 BookCarVo 对象，并设置相关信息
            for (Map.Entry<CompanyPersonPhoneKey, List<DevInfoVo>> entry : groupedByKey.entrySet()) {
                CompanyPersonPhoneKey key = entry.getKey();
                List<DevInfoVo> groupedList = entry.getValue();
                // 创建新的 BookCarVo 对象
                BookCarVo carVo = new BookCarVo();
                carVo.setCompanyPersonPhoneKey(key);
                carVo.setDevInfoVoList(groupedList);

                // 将当前分组的 BookCarVo 添加到 list 中
                list.add(carVo);
            }
        }
        // 返回最终结果
        return AjaxResult.success(list);
    }

    /**
     * 删除预约车
     *
     * @param devInfo
     * @return
     */
    @Override
    public AjaxResult deleteById(BookCarInfoDto devInfo) {
        if (devInfo == null || devInfo.getId() == null) {
            return AjaxResult.error("传入设备ID为空，请刷新后重试");
        }
        int result = bookCarMapper.deleteById(devInfo.getId());
        return result > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    @Override
    public AjaxResult deleteByIds(BookCarInfoDto devInfo) {
        if (ArrayUtils.isEmpty(devInfo.getIds())) {
            return AjaxResult.error("传入设备IDs为空，请刷新后重试");
        }
        int result = bookCarMapper.deleteByIds(devInfo.getIds());
        return result > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    /**
     * 查询立即承租详情
     *
     * @param devInfo
     * @return
     */
    @Override
    public AjaxResult getBookCarDetailByMaId(BookCarInfoDto devInfo) {
        log.info("查询立即承租详情{}", devInfo);
        Long userId = SecurityUtils.getLoginUser().getUserid();
        devInfo.setOrderUser(userId);
        List<DevInfoVo> bookCarDetails = bookCarMapper.getBookCarDetails(devInfo);
        BmFileInfo bmFileInfo = new BmFileInfo();
        bmFileInfo.setModelId(Long.parseLong(devInfo.getMaId()));
        bmFileInfo.setTaskType(MaterialConstants.MATERIAL_FILE_TYPE_CODE);
        bmFileInfo.setFileType(0L);
        List<BmFileInfo> mainFileInfoList = bmFileInfoMapper.selectBmFileInfoList(bmFileInfo);
        if (CollectionUtils.isNotEmpty(mainFileInfoList) && CollectionUtils.isNotEmpty(bookCarDetails)) {
            bookCarDetails.get(0).setPicUrl(mainFileInfoList.get(0).getFileUrl());
        }
        return AjaxResult.success(bookCarDetails);
    }
}
