package com.yiqi.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiqi.common.core.domain.entity.SysUser;
import com.yiqi.common.enums.SysBoolType;
import com.yiqi.common.exception.GlobalException;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.common.utils.SecurityUtils;
import com.yiqi.core.domain.ClothHanger;
import com.yiqi.core.domain.ClothHangerDetail;
import com.yiqi.core.domain.vo.ClothHangerVO;
import com.yiqi.core.mapper.ClothHangerMapper;
import com.yiqi.core.service.IClothHangerDetailService;
import com.yiqi.core.service.IClothHangerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 挂架管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-05
 */
@Service
public class ClothHangerServiceImpl extends ServiceImpl<ClothHangerMapper, ClothHanger> implements IClothHangerService {

    @Autowired
    IClothHangerDetailService clothHangerDetailService;

    /**
     * 查询挂架管理
     *
     * @param id 挂架管理主键
     * @return 挂架管理
     */
    @Override
    public ClothHanger selectClothHangerById(Long id) {
        return baseMapper.selectClothHangerById(id);
    }

    /**
     * 查询挂架管理列表
     *
     * @param clothHangerVO 挂架管理
     * @return 挂架管理
     */
    @Override
    public List<ClothHangerVO> selectClothHangerList(ClothHangerVO clothHangerVO) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 工厂/门店需要登陆人信息,去查询本工厂/本门店的数据
        if (!"00".equals(user.getUserType())){
            clothHangerVO.setSourceType(user.getUserType());
            if ("01".equals(clothHangerVO.getSourceType())){
                clothHangerVO.setOrgId(user.getFactoryId());
            }
            if ("02".equals(clothHangerVO.getSourceType())){
                clothHangerVO.setOrgId(user.getStoreId());
            }
        }
        return baseMapper.selectClothHangerList(clothHangerVO);
    }

    /**
     * 新增挂架管理
     *
     * @param clothHanger 挂架管理
     * @return 结果
     */
    @Override
    public int insertClothHanger(ClothHanger clothHanger) {
        if ("0".equals(clothHanger.getEndNum().toString())){
            throw new GlobalException("尾数不能为0");
        }
        if (clothHanger.getEndNum() < clothHanger.getFirstNum()){
            throw new GlobalException("尾数不能小于首数");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        clothHanger.setCreateTime(DateUtils.getNowDate());
        clothHanger.setSourceType(user.getUserType());
        if ("01".equals(clothHanger.getSourceType())){
            clothHanger.setOrgId(user.getFactoryId());
        }
        if ("02".equals(clothHanger.getSourceType())){
            clothHanger.setOrgId(user.getStoreId());
        }
        clothHanger.setStatus("0");
        clothHanger.setDelFlag("0");
        baseMapper.insertClothHanger(clothHanger);
        // 保存位置详情
        this.saveHangerDetail(clothHanger, null);
        return clothHanger.getEndNum() - clothHanger.getFirstNum() + 1;
    }

    /**
     * 修改挂架管理
     *
     * @param clothHanger 挂架管理
     * @return 结果
     */
    @Override
    public int updateClothHanger(ClothHanger clothHanger) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if ("0".equals(clothHanger.getEndNum().toString())){
            throw new GlobalException("尾数不能为0");
        }
        if (clothHanger.getEndNum() < clothHanger.getFirstNum()){
            throw new GlobalException("尾数不能小于首数");
        }
        clothHanger.setUpdateTime(DateUtils.getNowDate());

        // 查询首尾数以外的是否存在上挂的位置
        if(clothHangerDetailService.count(new QueryWrapper<ClothHangerDetail>().lambda()
                .eq(ClothHangerDetail::getHangerId,clothHanger.getId())
                .eq(ClothHangerDetail::getIsHanger, SysBoolType.YES.getCode())
                .and(wrapper -> wrapper.lt(ClothHangerDetail::getCode,clothHanger.getFirstNum()).or()
                        .gt(ClothHangerDetail::getCode,clothHanger.getEndNum())))> 0){
            throw new GlobalException("修改的首尾数存在已上挂的,无法操作修改");
        }
        // 删除未上挂的位置,不分首尾内外
        clothHangerDetailService.remove(new QueryWrapper<ClothHangerDetail>().lambda()
                .eq(ClothHangerDetail::getHangerId,clothHanger.getId())
                .eq(ClothHangerDetail::getIsHanger,SysBoolType.NO.getCode()));

        // 筛选出已上挂的位置数量
        List<ClothHangerDetail> details = clothHangerDetailService.list(new QueryWrapper<ClothHangerDetail>().lambda()
                .eq(ClothHangerDetail::getHangerId, clothHanger.getId())
                .eq(ClothHangerDetail::getIsHanger, SysBoolType.YES.getCode()));
        if(details.size() == 0){
            this.saveHangerDetail(clothHanger, null);
            return baseMapper.updateClothHanger(clothHanger);
        }
        // 取出对象中的code
        Set<String> isYHangerList = details.stream().map(ClothHangerDetail::getCode).collect(Collectors.toSet());
        this.saveHangerDetail(clothHanger, isYHangerList);
        return baseMapper.updateClothHanger(clothHanger);
    }

    /**
     *  V2 的作用就是用来剔除已上挂的序号,不需要重新新建
     * @param clothHanger
     * @param isYHangerList  已上挂的位置序号   codeList
     */
    public void saveHangerDetail(ClothHanger clothHanger, Set<String> isYHangerList){
        // 保存位置详情
        ArrayList<ClothHangerDetail> detailList = new ArrayList<>();
        for (int i = clothHanger.getFirstNum(); i <= clothHanger.getEndNum(); i++) {
            if (CollUtil.isNotEmpty(isYHangerList) && isYHangerList.contains(String.valueOf(i))){
                continue;
            }
            ClothHangerDetail clothHangerDetail = new ClothHangerDetail();
            clothHangerDetail.setHangerId(clothHanger.getId());
            clothHangerDetail.setOrgId(clothHanger.getOrgId());
            clothHangerDetail.setSourceType(clothHanger.getSourceType());
            clothHangerDetail.setIsHanger("N");
            clothHangerDetail.setCode(String.valueOf(i));
            clothHangerDetail.setCreateBy(clothHanger.getCreateBy());
            clothHangerDetail.setCreateById(clothHanger.getCreateById());
            clothHangerDetail.setCreateTime(clothHanger.getCreateTime());
            detailList.add(clothHangerDetail);
        }
        clothHangerDetailService.saveBatch(detailList);
    }

    /**
     * 批量删除挂架管理
     *
     * @param ids 需要删除的挂架管理主键
     * @return 结果
     */
    @Override
    public int deleteClothHangerByIds(Long[] ids) {
        for (Long id : ids){
            // 查询更新的挂架的位置详情信息
            List<ClothHangerDetail> details = clothHangerDetailService.list(new QueryWrapper<ClothHangerDetail>().lambda()
                    .eq(ClothHangerDetail::getHangerId, id)
                    .eq(ClothHangerDetail::getIsHanger, SysBoolType.YES.getCode()));
            if (CollUtil.isNotEmpty(details)){
                throw new GlobalException("该挂架存在已上挂的位置,不能操作删除");
            }
        }
        return baseMapper.deleteClothHangerByIds(ids);
    }

    /**
     * 删除挂架管理信息
     *
     * @param id 挂架管理主键
     * @return 结果
     */
    @Override
    public int deleteClothHangerById(Long id) {
        // 查询更新的挂架的位置详情信息
        List<ClothHangerDetail> details = clothHangerDetailService.list(new QueryWrapper<ClothHangerDetail>().lambda()
                .eq(ClothHangerDetail::getHangerId, id)
                .eq(ClothHangerDetail::getIsHanger, SysBoolType.YES.getCode()));
        if (CollUtil.isNotEmpty(details)){
            throw new GlobalException("该挂架存在已上挂的位置,不能操作删除");
        }
        return baseMapper.deleteClothHangerById(id);
    }

    /**
     * 修改挂架管理状态
     *
     * @param clothHanger 挂架管理
     * @return 结果
     */
    @Override
    public int updateClothHangerStatus(ClothHanger clothHanger) {
        clothHanger.setUpdateById(SecurityUtils.getUserId());
        clothHanger.setUpdateBy(SecurityUtils.getUsername());
        clothHanger.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateClothHanger(clothHanger);
    }


}
