package org.dromara.zhishu.service.impl;

import cn.hutool.core.collection.ConcurrentHashSet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zhishu.domain.TDepot;
import org.dromara.zhishu.domain.bo.TDepotBo;
import org.dromara.zhishu.domain.vo.TDepotVo;
import org.dromara.zhishu.domain.vo.TFreightVo;
import org.dromara.zhishu.domain.vo.TLogisticsVo;
import org.dromara.zhishu.domain.vo.TShelvesVo;
import org.dromara.zhishu.mapper.TDepotMapper;
import org.dromara.zhishu.mapper.TShelvesMapper;
import org.dromara.zhishu.service.ITDepotService;
import org.dromara.zhishu.service.ITLogisticsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 仓库信息设置Service业务层处理
 *
 * @author Lion Li
 * @date 2025-03-26
 */
@RequiredArgsConstructor
@Service
public class TDepotServiceImpl implements ITDepotService {

    private final TDepotMapper baseMapper;
    private final TShelvesMapper shelvesMapper;
    private final ITLogisticsService tLogisticsService;

    private static final char FIRST_LETTER = 'A';
    private static final char LAST_LETTER = 'Z';
    private static final Set<String> usedCodes = new ConcurrentHashSet<>();

    /**
     * 查询仓库信息设置
     *
     * @param id 主键
     * @return 仓库信息设置
     */
    @Override
    public TDepotVo queryById(Long id) {
        TDepotVo record = baseMapper.selectVoById(id);
//      通过record.getTemplateId获取到对应的name
        TLogisticsVo tLogisticsVo = tLogisticsService.queryById(record.getTemplateId());
        if (tLogisticsVo != null) {
            record.setTemplateName(tLogisticsVo.getTemplateName());
        }
        return record;
    }

    /**
     * 根据仓库code查询仓库信息
     *
     * @param code
     * @return
     */
    @Override
    public TDepotVo selectDepotByCode(String artNo) {
        return baseMapper.selectDepotByCode(artNo);
    }

    /**
     * 分页查询仓库信息设置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 仓库信息设置分页列表
     */
    @Override
    public TableDataInfo<TDepotVo> queryPageList(TDepotBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        String userName = baseMapper.selectByName(userId);
        bo.setUserId(userId);
        LambdaQueryWrapper<TDepot> lqw = buildQueryWrapper(bo);
        Page<TDepotVo> result = baseMapper.selectVo1(pageQuery.build(), bo);
        // 动态添加当前用户信息
        if (result != null) {
            result.getRecords().forEach(vo -> {
                if (vo.getInventory() == null) {
                    vo.setInventory(0L);
                }
                vo.setName(vo.getName() + vo.getUnit());
                vo.setUserId(userId);
                vo.setUserName(userName);
                vo.setLevel(1);
                String temName = baseMapper.selectTemName(vo.getTemplateId());
                vo.setTemplateName(temName);
                List<String> list = baseMapper.selectByShe(vo.getId());
                if (!list.isEmpty()) {
                    vo.setHasChildren(true);
                } else {
                    vo.setHasChildren(false);
                }
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的仓库信息设置列表
     *
     * @param bo 查询条件
     * @return 仓库信息设置列表
     */
    @Override
    public List<TDepotVo> queryList(TDepotBo bo) {
        // 查询当前用户id并查询出昵称，赋值给bo中的userId
        Long userId = LoginHelper.getUserId();
        bo.setUserId(userId);
        LambdaQueryWrapper<TDepot> lqw = buildQueryWrapper(bo);
        List<TDepotVo> list = baseMapper.selectVoList(lqw);
        //获取当前用户id并查询出昵称，赋值给list中userName

        list.forEach(vo -> {
            vo.setName(vo.getName() + vo.getUnit());
            Long sheNumber = baseMapper.selectSheCount(vo.getId());
            vo.setSheNumber(sheNumber);
            vo.setUserName(baseMapper.selectByName(userId));
        });
        return list;
    }

    @Override
    public List<TDepotVo> selectList(TDepotBo bo) {
        LambdaQueryWrapper<TDepot> lqw = buildQueryWrapper(bo);
        List<TDepotVo> list = baseMapper.selectVoList(lqw);
        return list;
    }

    private LambdaQueryWrapper<TDepot> buildQueryWrapper(TDepotBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TDepot> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), TDepot::getCode, bo.getCode());
        lqw.eq(bo.getUserId() != null, TDepot::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), TDepot::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), TDepot::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getManager()), TDepot::getManager, bo.getManager());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TDepot::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增仓库信息设置
     *
     * @param bo 仓库信息设置
     * @return 是否新增成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(TDepotBo bo) {
        TDepot add = MapstructUtils.convert(bo, TDepot.class);
        validEntityBeforeSave(add);
        //查询仓库code是否存在
//        Long userId = LoginHelper.getUserId();
        Long userId = bo.getUserId() != null ? bo.getUserId() : LoginHelper.getUserId();
        add.setUserId(userId);
        add.setTenantId("000000");
//       将字母变成大写
        String depotCode = add.getCode().toUpperCase();
        add.setCode(depotCode);

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

        //查询是否存在仓库名称
        Integer message = baseMapper.selectByUser(userId, null, bo.getName());
        if (message != 0) {
            throw new RuntimeException("仓库名称重复");
//            return false;
        }
        //查询是否存在仓库编码
        Integer message1 = baseMapper.selectByUser(userId, add.getCode(), null);
        if (message1 != 0) {
            throw new RuntimeException("仓库编码已存在");
        }
        //查询是否存在仓库名称和编码
        Integer code = baseMapper.selectByUser(userId, add.getCode(), bo.getName());
        if (code != 0) {
            throw new RuntimeException("仓库名称和编码已存在");
        } else {
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
            }
            return flag;
        }
    }

//    // 生成A-Z或0-9的随机字符
//    public static String generateRandomChar() {
//        int randomChoice = ThreadLocalRandom.current().nextInt(36);  // 0-35
//        if (randomChoice < 26) {
//            // 生成A-Z（ASCII码65-90）
//            String str = String.valueOf((char)(randomChoice + 65));
////            String str=Integer.toString(randomChoice + 65);
//            System.out.println(str);
//            return  str;
//        } else {
//            // 生成0-9（ASCII码48-57），或直接数字转字符
//            String str=String.valueOf((char)(randomChoice - 26 + 48));
////            Integer.toString(randomChoice - 26 + 48);
//            System.out.println(str);
//            return  str;
//        }
//    }

    /**
     * 修改仓库信息设置
     *
     * @param bo 仓库信息设置
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TDepotBo bo) {
        TDepot update = MapstructUtils.convert(bo, TDepot.class);
        validEntityBeforeSave(update);

        Long userId = bo.getUserId() != null ? bo.getUserId() : LoginHelper.getUserId();

        // 检查名称是否重复，排除当前正在修改的仓库
        Integer message = baseMapper.selectByUserAndExcludeCurrent(userId, update.getName(), update.getId());
        if (message != 0) {
            throw new RuntimeException("仓库名称重复");
        }

        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TDepot entity) {
        //TODO 做一些数据校验,如唯一约束

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

    }

    /**
     * 校验并批量删除仓库信息设置信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid, Long LocalUserId) {
        if (isValid) {
            Long userId = LocalUserId != null ? LocalUserId : LoginHelper.getUserId();
            //查询仓库下是否有书品
            Integer message = baseMapper.selectCount(userId, ids);


            //查询仓库code
//            List<String> codeList=baseMapper.selectByCodes(userId,ids);
            //查询仓库中是否有商品，有商品则不删除货位
//            Integer message1=baseMapper.selectCounts(userId,codeList);
            //通过shelist查询货位中是否存在货号
            //判断message是否为空，为空则进行删除操作，否则不进行删除操作
            if (message == 0) {
                List<Long> sheList = baseMapper.selectByids(ids);
                //删除货位中的货号
                if (!sheList.isEmpty()) {
                    baseMapper.deleteByIdFre(sheList);
                    //删除货位
                    baseMapper.deleteByIdShe(ids);
                }
                baseMapper.deleteByIds(ids);
            } else {
                throw new RuntimeException("货区下有书品，请先删除书品");
            }
        }
        return true;

    }

    @Override
    public List<TDepotVo> queryNameList(String phoneNumber) {
        Long userId = LoginHelper.getUserId();
        String status = "0";
        return baseMapper.nameList(userId, phoneNumber, status);
    }

    @Override
    public List<TShelvesVo> querySheNameList(String depotId) {
        return baseMapper.querySheNameList(depotId);
    }

    @Override
    public List<TFreightVo> queryFreNameList(String sheId) {
        return baseMapper.queryFreNameList(sheId);
    }

    @Override
    public Map<String, Object> getIds(String depotName, String freightName, String shelvesName) {
        return baseMapper.getIdsByNames(depotName, freightName, shelvesName);
    }

    @Override
    public List<TShelvesVo> queryShelvesList(Long id) {
        List<TShelvesVo> list = baseMapper.selectSheList(id);
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
//            Integer message= baseMapper.selectFreCount(list.get(i).getId());
                if (list.get(i).getInventory() == null) {
                    list.get(i).setInventory(0L);
                }
                if (list.get(i).getSheNumber() > 0) {
                    list.get(i).setHasChildren(true);
                } else {
                    list.get(i).setHasChildren(false);
                }
                list.get(i).setLevel(2);
            }
        }
        return list;
    }

    @Override
    public List<TFreightVo> queryTFreightList(Long id) {
        List<TFreightVo> list = baseMapper.selectFreList(id);
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getInventory() == null) {
                    list.get(i).setInventory(0L);
                }
//                //通过货位id查询货架数据
//                List<TShelves> shelvesList = new LambdaQueryChainWrapper<>(shelvesMapper).eq(ObjectUtil.isNotNull(list.get(i).getId()), TShelves::getId, list.get(i).getShelvesId()).list();
//               //通过货架id查询仓库信息
//                if(!shelvesList.isEmpty()){
//                    List<TDepot> depotList = new LambdaQueryChainWrapper<>(baseMapper).eq(ObjectUtil.isNotNull(list.get(i)), TDepot::getId, shelvesList.get(0).getDepotId()).list();
//                   if(!depotList.isEmpty()){
//                       String artNo=depotList.get(0).getCode()+shelvesList.get(0).getCode()+list.get(i).getCode();
//                       Long message=baseMapper.selectGoodsCount(artNo,depotList.get(0).getUserId());
//                       list.get(i).setSheNumber(message);
//                   }else{
//                       list.get(i).setSheNumber(0L);
//                   }
//                }else{
//                    list.get(i).setSheNumber(0L);
//                }
//               //根据artNo查询商品数量
//                list.get(i).setName(list.get(i).getName()+list.get(i).getUnit());
                list.get(i).setLevel(3);
            }
        }
        return list;
    }

    @Override
    public List<TDepotVo> queryListAll() {
        List<TDepotVo> tDepotVos = baseMapper.selectVoList();
        return tDepotVos;
    }

    @Override
    public List<TDepotVo> selectDepotIdByUserIdAndCode(Long userId, String code) {
        return baseMapper.selectDepotIdByUserIdAndCode(userId, code);
    }

    @Override
    public List<String> selectArtNoLists(Long userId) {
        return baseMapper.selectArtNoLists(userId);
    }
}
