package com.cf.imes.module.executor.service.orderParts;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.exception.util.ServiceExceptionUtil;
import com.cf.imes.framework.datapermission.core.util.DataPermissionUtils;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.executor.controller.admin.plate.vo.PlateRespVO;
import com.cf.imes.module.executor.controller.admin.plate.vo.PlateTermsPageReqVO;
import com.cf.imes.module.system.enums.ErrorCodeConstants;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import com.cf.imes.module.executor.controller.admin.orderParts.vo.*;
import com.cf.imes.module.executor.dal.dataobject.orderParts.OrderPartsDO;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.pojo.PageParam;
import com.cf.imes.framework.common.util.object.BeanUtils;

import com.cf.imes.module.executor.dal.mysql.orderParts.OrderPartsMapper;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.framework.security.core.util.SecurityFrameworkUtils.getUserOrganId;
import static com.cf.imes.module.executor.enums.ErrorCodeConstants.*;

/**
 * 生产单配件表 order_parts_{N} Service 实现类
 *
 * @author 晨丰科技
 */
@Service
@Validated
public class OrderPartsServiceImpl implements OrderPartsService {

    @Resource
    private OrderPartsMapper orderPartsMapper;

    @Override
    public Long createOrderParts(OrderPartsSaveReqVO createReqVO) {
        // 插入
        OrderPartsDO orderParts = BeanUtils.toBean(createReqVO, OrderPartsDO.class);
        orderPartsMapper.insert(orderParts);
        // 返回
        return orderParts.getId();
    }

    @Override
    public void updateOrderParts(OrderPartsSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderPartsExists(updateReqVO.getId());
        // 更新
        OrderPartsDO updateObj = BeanUtils.toBean(updateReqVO, OrderPartsDO.class);
        orderPartsMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderParts(Long id) {
        // 校验存在
        validateOrderPartsExists(id);
        // 删除
        orderPartsMapper.deleteById(id);
    }

    private void validateOrderPartsExists(Long id) {
        if (orderPartsMapper.selectById(id) == null) {
            throw exception(ORDER_PARTS_NOT_EXISTS);
        }
    }

    @Override
    public OrderPartsDO getOrderParts(Long id) {
        return orderPartsMapper.selectById(id);
    }

    @Override
    public PageResult<OrderPartsDO> getOrderPartsPage(OrderPartsPageReqVO pageReqVO) {
        return orderPartsMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public OrderPartsImportRespVO importOrderPartsList(List<OrderPartsSaveReqVO> importOrderParts, Long orderId) {
        if (CollUtil.isEmpty(importOrderParts)) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.ORDER_PARTS_IMPORT_LIST_IS_EMPTY);
        }
        OrderPartsImportRespVO respVO = OrderPartsImportRespVO.builder().createOrderParts(new ArrayList<OrderPartsSaveReqVO>())
                .updateOrderParts(new ArrayList<>()).failureOrderParts(new LinkedHashMap<>()).build();
        importOrderParts.forEach(orderParts -> {
            try{
                Long id = (long) orderPartsMapper.insert(BeanUtils.toBean(orderParts, OrderPartsDO.class)
                        .setOrderId(orderId));
                respVO.getCreateOrderParts().add(orderParts);
            }catch (ServiceException ex){
                respVO.getFailureOrderParts().put(orderParts.getName(), ex.getMessage());
            }
        });
        return respVO;
    }

    @Override
    public PageResult<OrderPartsRespVO> getPartsPageByTerms(PlateTermsPageReqVO pageReqVO) {
        PageDTO<OrderPartsRespVO> page = new PageDTO<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        IPage<OrderPartsRespVO> pageRes = orderPartsMapper.selectProductList(page, pageReqVO.getOrderId(), pageReqVO.getRoomId(), pageReqVO.getBodyId(),getUserOrganId());
        return new PageResult<OrderPartsRespVO>(pageRes.getRecords(), pageRes.getTotal());
    }

}