package cn.iocoder.yudao.module.system.service.home;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.home.vo.HomeServiceOrderPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.home.vo.HomeServiceOrderPageRespVO;
import cn.iocoder.yudao.module.system.controller.admin.home.vo.HomeServiceOrderRespVO;
import cn.iocoder.yudao.module.system.controller.admin.home.vo.HomeServiceOrderSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.home.HomeServiceOrderDO;
import cn.iocoder.yudao.module.system.dal.dataobject.home.HomeServiceOrderItemDO;
import cn.iocoder.yudao.module.system.dal.mysql.home.HomeServiceOrderItemMapper;
import cn.iocoder.yudao.module.system.dal.mysql.home.HomeServiceOrderMapper;
import cn.iocoder.yudao.module.system.dal.mysql.home.vo.HomeServiceOrderItemDetailVO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Validated
public class HomeServiceOrderServiceImpl implements HomeServiceOrderService {

    @Resource
    private HomeServiceOrderMapper homeServiceOrderMapper;
    @Resource
    private HomeServiceOrderItemMapper homeServiceOrderItemMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createHomeServiceOrder(HomeServiceOrderSaveReqVO createReqVO) {
        HomeServiceOrderDO orderDO = BeanUtils.toBean(createReqVO, HomeServiceOrderDO.class);
        homeServiceOrderMapper.insert(orderDO);
        saveOrderItems(orderDO.getId(), createReqVO.getServiceItemIds(), orderDO.getTenantId());
        return orderDO.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHomeServiceOrder(HomeServiceOrderSaveReqVO updateReqVO) {
        HomeServiceOrderDO orderDO = BeanUtils.toBean(updateReqVO, HomeServiceOrderDO.class);
        homeServiceOrderMapper.updateById(orderDO);
        if (updateReqVO.getServiceItemIds() != null) {
            homeServiceOrderItemMapper.delete(HomeServiceOrderItemDO::getHomeServiceOrderId, updateReqVO.getId());
            saveOrderItems(updateReqVO.getId(), updateReqVO.getServiceItemIds(), updateReqVO.getTenantId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHomeServiceOrder(Long id) {
        homeServiceOrderItemMapper.delete(HomeServiceOrderItemDO::getHomeServiceOrderId, id);
        homeServiceOrderMapper.deleteById(id);
    }

    @Override
    public HomeServiceOrderRespVO getHomeServiceOrder(Long id) {
        HomeServiceOrderDO orderDO = homeServiceOrderMapper.selectById(id);
        if (orderDO == null) {
            return null;
        }
        HomeServiceOrderRespVO respVO = BeanUtils.toBean(orderDO, HomeServiceOrderRespVO.class);
        List<HomeServiceOrderItemDO> items = homeServiceOrderItemMapper.selectList(
                new LambdaQueryWrapperX<HomeServiceOrderItemDO>()
                        .eq(HomeServiceOrderItemDO::getHomeServiceOrderId, id)
                        .orderByAsc(HomeServiceOrderItemDO::getId)
        );
        respVO.setServiceItemIds(CollectionUtils.convertList(items, HomeServiceOrderItemDO::getServiceItemId));
        return respVO;
    }

    @Override
    public PageResult<HomeServiceOrderPageRespVO> getHomeServiceOrderPage(HomeServiceOrderPageReqVO pageReqVO) {
        Page<HomeServiceOrderPageRespVO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        List<HomeServiceOrderPageRespVO> list = homeServiceOrderMapper.selectPageWithJoin(page, pageReqVO);
        List<Long> orderIds = list.stream().map(HomeServiceOrderPageRespVO::getId).collect(Collectors.toList());
        if (orderIds.isEmpty()) {
            return new PageResult<>(list, page.getTotal());
        }
        List<HomeServiceOrderItemDetailVO> homeServiceOrderItemDOS =
                homeServiceOrderItemMapper.selectListByOrderIds(orderIds.toArray(new Long[0]));
        Map<Long, String> itemsMap = homeServiceOrderItemDOS.stream()
                .collect(Collectors.groupingBy(HomeServiceOrderItemDetailVO::getHomeServiceOrderId,Collectors.mapping(HomeServiceOrderItemDetailVO::getItemName,Collectors.joining(","))));
        list.forEach(e->e.setItems(itemsMap.get(e.getId())));
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmHomeServiceOrders(Long[] orderIds) {
        if (orderIds == null || orderIds.length == 0) {
            return;
        }
        List<HomeServiceOrderDO> homeServiceOrderList = homeServiceOrderMapper.selectList(new LambdaQueryWrapperX<HomeServiceOrderDO>()
                .in(HomeServiceOrderDO::getId, Arrays.asList(orderIds)));
        for (HomeServiceOrderDO homeServiceOrderDO : homeServiceOrderList) {
            if (homeServiceOrderDO.getSubsidyArrivalDate() == null) {
                homeServiceOrderDO.setSubsidyArrivalDate(LocalDate.now());
            }
            homeServiceOrderDO.setStatus(1);
        }
        homeServiceOrderMapper.updateBatch(homeServiceOrderList);
    }

    private void saveOrderItems(Long orderId, List<Long> serviceItemIds, Long tenantId) {
        if (serviceItemIds == null || serviceItemIds.isEmpty()) {
            return;
        }
        List<HomeServiceOrderItemDO> itemDOs = CollectionUtils.convertList(serviceItemIds, itemId -> {
            HomeServiceOrderItemDO itemDO = new HomeServiceOrderItemDO();
            itemDO.setHomeServiceOrderId(orderId);
            itemDO.setServiceItemId(itemId);
            itemDO.setTenantId(tenantId);
            return itemDO;
        });
        homeServiceOrderItemMapper.insertBatch(itemDOs);
    }
}
