package com.cf.imes.module.manage.service.plate;

import cn.hutool.core.collection.CollUtil;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.exception.util.ServiceExceptionUtil;
import com.cf.imes.module.manage.controller.admin.plate.vo.plate.PlateImportExcelVO;
import com.cf.imes.module.manage.controller.admin.plate.vo.plate.PlateImportRespVO;
import com.cf.imes.module.manage.controller.admin.plate.vo.plate.PlatePageReqVO;
import com.cf.imes.module.manage.controller.admin.plate.vo.plate.PlateSaveReqVO;
import com.cf.imes.module.system.enums.ErrorCodeConstants;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import com.cf.imes.module.manage.dal.dataobject.plate.PlateDO;
import com.cf.imes.framework.datapermission.core.util.DataPermissionUtils;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.object.BeanUtils;

import com.cf.imes.module.manage.dal.mysql.plate.PlateMapper;

import javax.annotation.Resource;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.PLATE_NOT_EXISTS;

/**
 * 板材信息表 plate_{N} Service 实现类
 *
 * @author 晨丰科技
 */
@Service
@Validated
public class PlateServiceImpl implements PlateService {

    @Resource
    private PlateMapper plateMapper;

    @Override
    public Long createPlate(PlateSaveReqVO createReqVO) {
        // 插入
        PlateDO plate = BeanUtils.toBean(createReqVO, PlateDO.class);
        plateMapper.insert(plate);
        // 返回
        return plate.getId();
    }

    @Override
    public void updatePlate(PlateSaveReqVO updateReqVO) {
        // 校验存在
        validatePlateExists(updateReqVO.getId());
        // 更新
        PlateDO updateObj = BeanUtils.toBean(updateReqVO, PlateDO.class);
        plateMapper.updateById(updateObj);
    }

    @Override
    public void deletePlate(Long id) {
        // 校验存在
        validatePlateExists(id);
        // 删除
        plateMapper.deleteById(id);
    }

    private void validatePlateExists(Long id) {
        if (plateMapper.selectById(id) == null) {
            throw exception(PLATE_NOT_EXISTS);
        }
    }

    @Override
    public PlateDO getPlate(Long id) {
        return plateMapper.selectById(id);
    }

    @Override
    public PageResult<PlateDO> getPlatePage(PlatePageReqVO pageReqVO) {
        return plateMapper.selectPage(pageReqVO);
    }


    private void validatePlateForCreateOrUpdate(PlateImportExcelVO importPlate) {
        // 关闭数据权限，避免因为没有数据权限，查询不到数据，进而导致唯一校验不正确
        DataPermissionUtils.executeIgnore(() -> {

        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public PlateImportRespVO importPlateList(List<PlateImportExcelVO> importPlates, boolean isUpdateSupport) {
        if (CollUtil.isEmpty(importPlates)) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.PLATE_IMPORT_LIST_IS_EMPTY);
        }
        PlateImportRespVO respVO = PlateImportRespVO.builder().createPlateNames(new ArrayList<>())
                .updatePlateNames(new ArrayList<>()).failurePlateNames(new LinkedHashMap<>()).build();
        importPlates.forEach(importPlate -> {
            // 校验，判断是否有不符合的原因 校验全部是否为空
            try {
                validatePlateForCreateOrUpdate(importPlate);
            } catch (ServiceException ex) {
                respVO.getFailurePlateNames().put(importPlate.getGoodsName() , ex.getMessage());
                return;
            }
            // 判断如果不存在，在进行插入
            PlateDO existPlate = plateMapper.selectByGoodID(importPlate.getGoodsId());
            if (existPlate == null) {
                plateMapper.insert(BeanUtils.toBean(importPlate, PlateDO.class));
                respVO.getCreatePlateNames().add(importPlate.getGoodsName());
                return;
            }
            // 如果存在，判断是否允许更新
            if (!isUpdateSupport) {
                respVO.getFailurePlateNames().put(importPlate.getGoodsName(), ErrorCodeConstants.PLATE_EXISTS.getMsg());
                return;
            }
            PlateDO updateUser = BeanUtils.toBean(importPlate, PlateDO.class);
            updateUser.setId(existPlate.getId());
            plateMapper.updateById(updateUser);
            respVO.getUpdatePlateNames().add(importPlate.getGoodsName());
        });
        return respVO;
    }




}