package com.shkj.wms.service.impl;

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.annotation.DataScopeConsignor;
import com.shkj.common.core.domain.Result;
import com.shkj.common.enums.IsDelEnum;
import com.shkj.common.utils.SecurityUtils;
import com.shkj.common.utils.StringUtils;
import com.shkj.system.service.ISysUserService;
import com.shkj.wms.bo.*;
import com.shkj.wms.config.ValidList;
import com.shkj.wms.domain.BaseArea;
import com.shkj.wms.domain.BaseStorage;
import com.shkj.wms.enums.YesAndNoEnum;
import com.shkj.wms.mapper.BaseAreaMapper;
import com.shkj.wms.service.IBaseAreaService;
import com.shkj.wms.service.IBaseStorageService;
import com.shkj.wms.vo.BaseAreaListVo;
import com.shkj.wms.vo.BaseAreaNoOtherVo;
import com.shkj.wms.vo.BaseAreaVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 区域资料Service业务层处理
 *
 * @author lch
 * @date 2022-05-13
 */
@Slf4j
@Service
public class BaseAreaServiceImpl extends ServiceImpl<BaseAreaMapper, BaseArea> implements IBaseAreaService {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private IBaseStorageService iBaseStorageService;

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

    @Override
    public List<BaseAreaVo> queryList(BaseAreaQueryBo bo) {
        LambdaQueryWrapper<BaseArea> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getStorageId() != null, BaseArea::getStorageId, bo.getStorageId());
        lqw.eq(StrUtil.isNotBlank(bo.getAreaCode()), BaseArea::getAreaCode, bo.getAreaCode());
        lqw.like(StrUtil.isNotBlank(bo.getAreaName()), BaseArea::getAreaName, bo.getAreaName());
        lqw.eq(StrUtil.isNotBlank(bo.getPickmode()), BaseArea::getPickmode, bo.getPickmode());
        lqw.eq(StrUtil.isNotBlank(bo.getTaskmode()), BaseArea::getTaskmode, bo.getTaskmode());
        lqw.eq(StrUtil.isNotBlank(bo.getPickgroup()), BaseArea::getPickgroup, bo.getPickgroup());
        lqw.eq(StrUtil.isNotBlank(bo.getIsDouboper()), BaseArea::getIsDouboper, bo.getIsDouboper());
        lqw.eq(StrUtil.isNotBlank(bo.getExtend1()), BaseArea::getExtend1, bo.getExtend1());
        lqw.eq(StrUtil.isNotBlank(bo.getExtend2()), BaseArea::getExtend2, bo.getExtend2());
        lqw.eq(StrUtil.isNotBlank(bo.getExtend3()), BaseArea::getExtend3, bo.getExtend3());
        lqw.eq(StrUtil.isNotBlank(bo.getExtend4()), BaseArea::getExtend4, bo.getExtend4());
        lqw.eq(StrUtil.isNotBlank(bo.getExtend5()), BaseArea::getExtend5, bo.getExtend5());
        lqw.eq(bo.getBranchId() != null, BaseArea::getBranchId, bo.getBranchId());
        lqw.eq(StrUtil.isNotBlank(bo.getIsDel()), BaseArea::getIsDel, bo.getIsDel());
        lqw.eq(BaseArea::getIsDel, IsDelEnum.NORMAL.getValue());
        lqw.orderByDesc(BaseArea::getCreateTime);
        List<BaseAreaVo> voList = entity2Vo(this.list(lqw));
        return voList;

    }

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

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> insertByAddBo(BaseAreaAddBo bo) {
        BaseArea add = BeanUtil.toBean(bo, BaseArea.class);
        this.save(add);
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> updateByEditBo(BaseAreaEditBo bo) {
        BaseArea one = getById(bo.getId());
        if (one == null) {
            return Result.err().msg("不存在");
        }
        BaseArea update = BeanUtil.toBean(bo, BaseArea.class);
        this.updateById(update);
        return Result.ok();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<Boolean> deleteWithValidById(List<Long> ids, Boolean isValid) {
        BaseArea del = new BaseArea();
        del.setIsDel(IsDelEnum.DELETED.getValue());
        LambdaQueryWrapper<BaseArea> wrapper = new LambdaQueryWrapper<BaseArea>().in(BaseArea::getId, ids)
                .eq(BaseArea::getBranchId, SecurityUtils.getCurrentBranchId());
        this.update(del, wrapper);
        return Result.ok();
    }


    /**
     * 获取当前仓的所有区域信息（带库别简单信息)
     *
     * @return
     */
    @Override
    public List<BaseAreaListVo> queryBaseAreaAndStorageList() {
        return this.getBaseMapper().queryBaseAreaAndStorageList(SecurityUtils.getCurrentBranchId());
    }

  /*  @Override
    public List<BaseAreaVo> queryBaseAreaAndStorageListByIds(List<Long> ids){
        LambdaQueryWrapper<BaseArea> lqw = new LambdaQueryWrapper<BaseArea>();
        lqw.in(BaseArea::getId,ids);
        lqw.eq(BaseArea::getIsDel, DeleteFlagEnum.NORMAL.getValue());
        lqw.eq(BaseArea::getBranchId,SecurityUtils.getCurrentBranchId());
        List<BaseAreaVo> list = entity2Vo(list(lqw));
        list.stream().forEach(s->s.setBaseStorage(iBaseStorageService.getById(s.getStorageId())));
        return list;
    }*/

    /**
     * 根据提交的数据新增或者修改复核台资料
     *
     * @param list 复核台资料集合
     * @return
     */
    @Override
    public Result<Boolean> saveOrUpdateBaseAreas(ValidList<BaseAreaSaveOrUpdateBo> list) {
        List<BaseArea> addList = new ArrayList<>();
        List<BaseArea> updList = new ArrayList<>();

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

        for (BaseAreaSaveOrUpdateBo bo : list) {
            bo.setIsActivity(StringUtils.isBlank(bo.getIsActivity()) ? YesAndNoEnum.YES.getValue() : bo.getIsActivity());
            if (bo.getId() != null) {
                BaseArea one = getById(bo.getId());
                if (one == null) {
                    return Result.err().msg("区域id传递异常");
                }

                BaseArea update = BeanUtil.toBean(bo, BaseArea.class);

                BaseStorage storage = iBaseStorageService.getById(update.getStorageId());
                if (storage == null) {
                    return Result.err().msg("库房传递异常");
                }

                update.setBranchId(storage.getBranchId());
                Result result = checkEntity(update);
                if (!Result.isOk(result)) {
                    return Result.err().msg(result.getMsg());
                }
                updList.add(update);
            } else {
                BaseArea add = BeanUtil.toBean(bo, BaseArea.class);
                BaseStorage storage = iBaseStorageService.getById(add.getStorageId());
                if (storage == null) {
                    return Result.err().msg("库房传递异常");
                }
                add.setBranchId(storage.getBranchId());
                Result result = checkEntity(add);
                if (!Result.isOk(result)) {
                    return Result.err().msg(result.getMsg());
                }
                addList.add(add);
            }
        }
        this.updateBatchById(updList);
        this.saveBatch(addList);
        return Result.ok();
    }

    /**
     * 校验数据 (相同工号、相同作业类型、作业顺序不允许重复)
     *
     * @param entity
     * @return
     */
    private Result checkEntity(BaseArea entity) {
        Long id = entity.getId() != null ? entity.getId() : -1L;
        LambdaQueryWrapper<BaseArea> wrapper = new LambdaQueryWrapper<BaseArea>()
                .eq(BaseArea::getBranchId, entity.getBranchId())
                .eq(BaseArea::getStorageId, entity.getStorageId())
                .eq(BaseArea::getAreaCode, entity.getAreaCode())
                .eq(BaseArea::getIsDel, IsDelEnum.NORMAL.getValue());
        BaseArea one = getOne(wrapper);
        if (one != null && !id.equals(one.getId())) {
            log.info("存在重复数据：" + entity.toString());
            return Result.err().msg("存在重复数据");
        }
        return Result.ok();
    }

    /**
     * 按照权限获取区域集合
     *
     * @return
     */
    @DataScopeConsignor(branchAlias = "ba")
    @Override
    public List<BaseAreaNoOtherVo> queryBaseAreaList(BaseAreaQueryListBo bo) {
        return this.getBaseMapper().queryBaseAreaList(bo);
    }


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