package org.dromara.zhishu.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zhishu.domain.TFreight;
import org.dromara.zhishu.domain.bo.TDepotBo;
import org.dromara.zhishu.domain.bo.TFreightBo;
import org.dromara.zhishu.domain.vo.TDepotVo;
import org.dromara.zhishu.domain.vo.TFreightVo;
import org.dromara.zhishu.domain.vo.TShelvesVo;
import org.dromara.zhishu.mapper.TFreightMapper;
import org.dromara.zhishu.mapper.TShelvesMapper;
import org.dromara.zhishu.service.ITDepotService;
import org.dromara.zhishu.service.ITFreightService;
import org.dromara.zhishu.service.ITShelvesService;
import org.dromara.zhishu.service.IZhishuShopGoodsService;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;

/**
 * 三级货区管理Service业务层处理
 *
 * @author Lion Li
 * @date 2025-04-19
 */
@RequiredArgsConstructor
@Service
public class TFreightServiceImpl implements ITFreightService {

    private final TFreightMapper baseMapper;

    private final TShelvesMapper tShelvesMapper;

    private final ITShelvesService shelvesService;

    private final ITDepotService depotService;

    private final IZhishuShopGoodsService zhishuShopGoodsService;


    @Override
    public List<Map> selectDepotTree(){
        Long userId = LoginHelper.getUserId();
        TDepotBo depotBo = new TDepotBo();
        depotBo.setUserId(userId);
        List<Map> depotTree = new ArrayList<>();
        //获取一级货区
        List<TDepotVo> depotVoList = depotService.selectList(depotBo);
        for (TDepotVo depotVo : depotVoList){
            Map depotMap = new HashMap();
            depotMap.put("value",depotVo.getId());
            depotMap.put("label","货架编号："+depotVo.getCode()+";货架名称"+depotVo.getName());
            List<Map> depotChildren = new ArrayList<>();
            //获取二级货区
            List<TShelvesVo> shelvesVoList =  shelvesService.selectShelvesByDepotId(depotVo.getId().toString());
            for (TShelvesVo shelvesVo : shelvesVoList){
                Map shelvesMap = new HashMap();
                shelvesMap.put("value",shelvesVo.getId());
                shelvesMap.put("label","货架编号："+shelvesVo.getCode()+";货架名称"+shelvesVo.getName());

                List<Map> shelvesChildren = new ArrayList<>();
                //获取三级货区
                List<TFreightVo> freightVoList = selectByShelvesId(shelvesVo.getId());
                for (TFreightVo freightVo : freightVoList){
                    Map freightMap = new HashMap();
                    freightMap.put("value",freightVo.getId());
                    freightMap.put("label","货架编号："+freightVo.getCode()+";货架名称"+freightVo.getName());
                    shelvesChildren.add(freightMap);
                }
                shelvesMap.put("children",shelvesChildren);
                depotChildren.add(shelvesMap);
            }
            depotMap.put("children",depotChildren);
            depotTree.add(depotMap);
        }
        return depotTree;
    }

    @Override
    public List<TFreightVo> selectByShelvesId(Long shelvesId){
        return baseMapper.selectByShelvesId(shelvesId);
    }

    @Override
    public Map selectByFreightId(Long freightId){
        return baseMapper.selectByFreightId(freightId);
    }

    /**
     * 查询三级货区管理
     *
     * @param id 主键
     * @return 三级货区管理
     */
    @Override
    public TFreightVo queryById(Long id){
        TFreightVo vo=baseMapper.selectVoById(id);
        TFreight shelvesVo=baseMapper.selectSheName(id);
        vo.setShelvesName(shelvesVo.getName());
        vo.setShelvesCode(shelvesVo.getCode());
        return vo;
    }

    /**
     * 分页查询三级货区管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 三级货区管理分页列表
     */
    @Override
    public TableDataInfo<TFreightVo> queryPageList(TFreightBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        List<Long> depotids=baseMapper.selectV(userId);

        Page<TFreightVo> result = new Page<>();
        if(!depotids.isEmpty()){
            List<Long>  sheIds=baseMapper.selectShe(depotids);
            if(!sheIds.isEmpty()){
                result =baseMapper.selectVo(pageQuery.build(), bo,sheIds);
                for (int i = 0; i < result.getRecords().size(); i++) {
                    Long id = result.getRecords().get(i).getId();
                    String unit = result.getRecords().get(i).getUnit();
                    String name = result.getRecords().get(i).getName();
                    result.getRecords().get(i).setName(name+unit);
                     TShelvesVo vo = baseMapper.setShelvesName1(id);
                     String depotCode =baseMapper.selectDepotCode(vo.getDepotId());
                     result.getRecords().get(i).setComcode(depotCode+vo.getCode()+result.getRecords().get(i).getCode());
                    result.getRecords().get(i).setShelvesName(vo.getName()+vo.getUnit());
                }

            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的三级货区管理列表
     *
     * @param bo 查询条件
     * @return 三级货区管理列表
     */
    @Override
    public List<TFreightVo> queryList(TFreightBo bo) {
        LambdaQueryWrapper<TFreight> lqw = buildQueryWrapper(bo);
        Long userId = LoginHelper.getUserId();
        //获取三级货区
        List<TFreightVo> vo=new ArrayList<>();
        //获取当前用户下的一级货区id
        List<Long> depotids=baseMapper.selectV(userId);
        //判断是否为空
        if(!depotids.isEmpty()){
            //通过一级货区id查询出二级货区id
            List<Long> sheIds=baseMapper.selectShe(depotids);
            //判断二级货区是否为空
            if(!sheIds.isEmpty()) {
                   //查询出二级货区下的所有三级货区
                   vo=baseMapper.selectVoLists(sheIds);
                for (int i = 0; i < vo.size(); i++) {
                    //设置三级货区名称
                    vo.get(i).setName(vo.get(i).getName()+vo.get(i).getUnit());
                    //查询二级货区名称和单位
                    TShelvesVo vo1 = baseMapper.setShelvesName1(vo.get(i).getId());
                    //设置二级货区名称
                    vo.get(i).setShelvesName(vo1.getName()+vo1.getUnit());
                }
            }
            }


        return vo;
    }

    private LambdaQueryWrapper<TFreight> buildQueryWrapper(TFreightBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TFreight> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TFreight::getId);
        lqw.eq(bo.getShelvesId() != null, TFreight::getShelvesId, bo.getShelvesId());
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), TFreight::getCode, bo.getCode());
        lqw.like(StringUtils.isNotBlank(bo.getName()), TFreight::getName, bo.getName());
        lqw.eq(bo.getCapMax() != null, TFreight::getCapMax, bo.getCapMax());
        lqw.eq(StringUtils.isNotBlank(bo.getArtNo()), TFreight::getArtNo, bo.getArtNo());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TFreight::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增三级货区管理
     *
     * @param bo 三级货区管理
     * @return 是否新增成功
     */
    @Override
    public TFreightBo insertByBo(TFreightBo bo) {
//        Long userId = LoginHelper.getUserId();
        Long userId = bo.getUserId() != null ? bo.getUserId() : LoginHelper.getUserId();
        TFreight add = MapstructUtils.convert(bo, TFreight.class);
        validEntityBeforeSave(add);
        add.setTenantId("000000");
        // 获取货架编码
        String sheCode = baseMapper.selectByCode(add.getShelvesId());
        // 获取货架的depotId
        Long depotId = tShelvesMapper.selectDepotIdByShelvesId(add.getShelvesId());
        // 获取仓库编码
        String depotCode = null;
        if (depotId != null) {
            depotCode = baseMapper.selectDepotCode(String.valueOf(depotId));
        }
        
        // 判断shelvesCode和depotCode相加是否为四位
        if (sheCode != null && depotCode != null && (sheCode + depotCode).length() == 4) {
            // 如果是四位，判断用户输入的code是否为两位
            if (add.getCode() != null && add.getCode().length() >= 2) {
                throw new RuntimeException("货架编码错误，请输入正确的货架编码");
            }
        }
        
        if(sheCode != null && sheCode.length()==1){
            if(add.getCode().length()==1&& Character.isDigit(add.getCode().charAt(0)))  {
                add.setCode("0" + add.getCode()); // 补零
            }else if(add.getCode().matches("[a-zA-Z][0-9]")){
                add.setCode(add.getCode().toUpperCase());
            }else{
                add.setCode(add.getCode());
            }
        }

        if (StringUtils.isEmpty(add.getName())) {
            throw new RuntimeException("请稍后重试");
        }

        Integer message1 = baseMapper.selectFreName(add.getName(), add.getShelvesId(), null);
        Integer message2 =  baseMapper.selectFreName(null, add.getShelvesId(), add.getCode());
        if(message1!=0 || message2!=0){
            throw new RuntimeException("货区编码或名称已存在");
        }
        boolean flag = baseMapper.insertFre(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return bo;
    }

    /**
     * 修改三级货区管理
     *
     * @param bo 三级货区管理
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TFreightBo bo) {
        TFreight update = MapstructUtils.convert(bo, TFreight.class);
        validEntityBeforeSave(update);
        Integer message = baseMapper.selectByExcludeCurrent(bo.getName(), bo.getShelvesId(), bo.getId());
        if (message != 0) {
            throw new RuntimeException("货区名称重复");
        }

        /**
         * 如果修改了是否开启分销，则将该货架上的商品全部修改
         */
        if(StringUtils.isNotEmpty(bo.getAllowDistribution())){
            TFreightVo vo = queryById(bo.getId());
            if(!bo.getAllowDistribution().equals(vo.getAllowDistribution())){
                Long userId = LoginHelper.getUserId();
                Long limitNum = 1000L;
                /**
                 * 确认 分销 状态 修改
                 */
                //获取货号
                TShelvesVo shelvesVo = shelvesService.queryById(vo.getShelvesId());
                TDepotVo depotVo = depotService.queryById(Long.parseLong(shelvesVo.getDepotId()));
                //拼接货号前缀
                String artNoPrefix = depotVo.getCode() + shelvesVo.getCode() + vo.getCode();
                //根据货号前缀，将所有这个前缀的商品分销状态修改
                while (true){
                    int num = zhishuShopGoodsService.updateByArtNoPrefix(bo.getAllowDistribution(),artNoPrefix,userId,limitNum);
                    if (num == 0){
                        break;
                    }
                }
            }
        }
        return baseMapper.updateBydate(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TFreight entity){
        //TODO 做一些数据校验,如唯一约束
        if (StringUtils.isEmpty(entity.getName())) {
            throw new RuntimeException("请稍后重试");
        }
    }

    /**
     * 校验并批量删除三级货区管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid,Long LocalUserId) {
        Long userId = LocalUserId != null ? LocalUserId : LoginHelper.getUserId();

        List<TFreightVo> list=baseMapper.selectListVo(ids,userId);
        if(!list.isEmpty()){
            for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getSheNumber()>0){
                throw new RuntimeException("货区下有书品，请先删除书品");
            }else{
               baseMapper.deleteByIds(ids);    // 主表删除
                return  true;
            }
            }
        }

//        // 2. 批量查询货架编码（空值保护）
//        List<String> codes = baseMapper.selectCode(ids);
//        if (CollectionUtils.isEmpty(codes))  {
////            log.warn(" 未查询到有效货架编码: ids={}", ids);
//            return false;
//        }
//        // 4. 批量校验占用状态（优化数据库交互）
//        Map<String, Integer> occupiedMap = codes.stream()
//                .collect(Collectors.toMap(
//                        code -> code,
//                        code -> code.length()  == 2 ?
//                                baseMapper.selectByCount2(userId,  code) :
//                                baseMapper.selectByCount1(userId,  code)
//                ));
//        // 5. 统一决策（全部未被占用才允许删除）
//        boolean allUnoccupied = occupiedMap.values().stream()
//                .allMatch(count -> count == 0);
//        if (allUnoccupied) {
//            baseMapper.deleteByIds(ids);    // 主表删除
//            return true;
//        }
        return false;
    }

    @Override
    public List<TShelvesVo> querySheNameList() {
        //获取当前用户id
        Long userId = LoginHelper.getUserId();
        List<Long> depotIdList =  baseMapper.selectDepotId(userId);
        List<TShelvesVo> list=new ArrayList<>();
        if(!depotIdList.isEmpty()){
             list=  baseMapper.selectByList(depotIdList);
             for (TShelvesVo vo:list){
                 vo.setLevel(3);
             }
        }
        return list;
    }

    /**
     * 根据三级获取名称获取获取信息
     * @param freightName
     * @param shelvesId
     * @return
     */
    @Override
    public TFreightVo selectByFreightName(String freightName, Long shelvesId){
        return baseMapper.selectByFreightName(freightName,shelvesId);
    }

}
