package com.shkj.wms.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.shkj.common.core.domain.Result;
import com.shkj.common.enums.IsDelEnum;
import com.shkj.common.utils.SecurityUtils;
import com.shkj.wms.bo.BaseLogicAreaQueryBo;
import com.shkj.wms.bo.BaseLogicAreaQueryListBo;
import com.shkj.wms.bo.BaseLogicAreaSaveOrUpdateBo;
import com.shkj.wms.config.ValidList;
import com.shkj.wms.domain.BaseLogicArea;
import com.shkj.wms.domain.BaseStorage;
import com.shkj.wms.mapper.BaseLogicAreaMapper;
import com.shkj.wms.service.IBaseLogicAreaService;
import com.shkj.wms.vo.BaseLogicAreaVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 逻辑区域Service业务层处理
 *
 * @author zjx
 * @date 2023-04-18
 */
@Service
public class BaseLogicAreaServiceImpl extends ServiceImpl<BaseLogicAreaMapper, BaseLogicArea> implements IBaseLogicAreaService {

    @Autowired
    private BaseLogicAreaMapper baseLogicAreaMapper;

    @Override
    public Result<Boolean> saveOrUpdateBaseLogicArea(ValidList<BaseLogicAreaSaveOrUpdateBo> list) {
        List<BaseLogicArea> addList = new ArrayList<>();
        List<BaseLogicArea> updList = new ArrayList<>();

        Set<String> listGroup = list.stream().collect(Collectors.groupingBy(item ->
                item.getLogicAreaNo())).keySet();
        if (listGroup.size() != list.size()) {
            log.error("请求参数存在重复数据");
            return Result.err().msg("请求参数存在重复数据");
        }

        for (BaseLogicAreaSaveOrUpdateBo bo : list) {
            if (bo.getId() != null) {
                BaseLogicArea one = getById(bo.getId());
                if (one == null) {
                    log.error("逻辑区域信息不存在:" + bo.toString());
                    return Result.err().msg("逻辑区域信息不存在");
                }

                BaseLogicArea update = BeanUtil.toBean(bo, BaseLogicArea.class);
                update.setBranchId(SecurityUtils.getCurrentBranchId());
                updList.add(update);
            } else {
                LambdaQueryWrapper<BaseLogicArea> wrapper = new LambdaQueryWrapper<BaseLogicArea>()
                        .eq(BaseLogicArea::getLogicAreaNo, bo.getLogicAreaNo())
                         .or().eq(BaseLogicArea::getLogicAreaName,bo.getLogicAreaName()).last("limit 1");
                BaseLogicArea one = getOne(wrapper);
                if ( one!= null && one.getLogicAreaNo().equals(bo.getLogicAreaNo())) {
                    return Result.err().msg("逻辑区域编号已经存在");
                }
                if ( one!= null && one.getLogicAreaName().equals(bo.getLogicAreaName())) {
                    return Result.err().msg("逻辑区域名称已经存在");
                }
                BaseLogicArea add = BeanUtil.toBean(bo, BaseLogicArea.class);
                add.setBranchId(SecurityUtils.getCurrentBranchId());
                addList.add(add);
            }
        }
        this.updateBatchById(updList);
        this.saveBatch(addList);
        return Result.ok();
    }

    @Override
    public Result<BaseLogicAreaVo> queryById(Long id) {
        BaseLogicArea baseLogicArea = this.baseMapper.selectById(id);
        BaseLogicAreaVo vo = BeanUtil.toBean(baseLogicArea,BaseLogicAreaVo.class);
        return  Result.ok().data(vo);
    }

    @Override
    public List<BaseLogicAreaVo> queryList(BaseLogicAreaQueryBo bo) {
        LambdaQueryWrapper<BaseLogicArea> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getLogicAreaNo()),BaseLogicArea::getLogicAreaNo,bo.getLogicAreaNo());
        lqw.like(StrUtil.isNotBlank(bo.getLogicAreaName()),BaseLogicArea::getLogicAreaName,bo.getLogicAreaName());
        lqw.eq(StrUtil.isNotBlank(bo.getIsDel()),BaseLogicArea::getIsDel,bo.getIsDel());
        lqw.eq(StrUtil.isNotBlank(bo.getIsActivity()),BaseLogicArea::getIsActivity,bo.getIsActivity());
        List<BaseLogicAreaVo> voList =entity2Vo(this.list(lqw));
        return voList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> deleteWithValidById(Long id) {
        BaseLogicArea del = new BaseLogicArea();
        del.setIsDel(IsDelEnum.DELETED.getValue());
        LambdaQueryWrapper<BaseLogicArea> wrapper = new LambdaQueryWrapper<BaseLogicArea>().in(BaseLogicArea::getId,id);
        this.update(del,wrapper);
        return Result.ok();
    }

    @Override
    public List<BaseLogicArea> queryBaseLogicAreaList(BaseLogicAreaQueryListBo bo) {
        return  this.getBaseMapper().queryBaseLogicAreaList(bo);
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<BaseLogicAreaVo> entity2Vo(Collection<BaseLogicArea> collection) {
        List<BaseLogicAreaVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, BaseLogicAreaVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<BaseLogicArea> page = (Page<BaseLogicArea>) collection;
            Page<BaseLogicAreaVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Result<Boolean> switchStatus(Long id, String status) {
        BaseLogicArea logicArea = new BaseLogicArea();
        logicArea.setId(id).setIsActivity(status);
        return this.updateById(logicArea) ? Result.ok() : Result.err();
    }

}
