package cn.com.ty.lift.ud.dataBank.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import cn.com.ty.lift.ud.dataBank.controller.query.LiftCategoryQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.ty.lift.ud.dataBank.mapper.LiftBrandMapper;
import cn.com.ty.lift.ud.dataBank.mapper.LiftCategoryMapper;
import cn.com.ty.lift.ud.dataBank.mapper.entity.LiftBrandEntity;
import cn.com.ty.lift.ud.dataBank.mapper.entity.LiftCategoryEntity;
import cn.com.ty.lift.ud.dataBank.service.ILiftCategoryService;
import cn.com.xwy.boot.web.dto.RestResponse;

/**
 * 资料分类 -ServiceImpl
 *
 * @author Xson
 * @date 2020-04-23
 */
@Service
@Transactional
public class LiftCategoryServiceImpl extends ServiceImpl<LiftCategoryMapper, LiftCategoryEntity>
    implements ILiftCategoryService {

    @Autowired
    private LiftCategoryMapper liftCategoryMapper;
    @Autowired
    private LiftBrandMapper liftBrandMapper;

    @Override
    public RestResponse selectByExample(LiftCategoryQuery query) {
        IPage page = query.page();
        List<LiftCategoryEntity> list = liftCategoryMapper.selectByQuery(query.condition(), query);
        for (LiftCategoryEntity le : list) {
            LiftBrandEntity selectById2 = liftBrandMapper.selectById(le.getBrandId());
            if (selectById2 != null) {
                le.setBrandName(selectById2.getName());
            }
            if (le.getPid() != 0) {
                LiftCategoryEntity selectById = liftCategoryMapper.selectById(le.getPid());
                if (selectById != null) {
                    le.setPidName(selectById.getName());
                }
            }
        }
        int total = liftCategoryMapper.countByQuery(query.condition());
        page.setRecords(list);
        page.setTotal(total);
        return RestResponse.success(page, "Queried successfully");
    }

    @Override
    public void updateByIds(List<Long> ids, Integer status) {
        for (Long id : ids) {
            LiftCategoryEntity bit = new LiftCategoryEntity();
            bit.setId(id);
            bit.setStatuz(status);
            liftCategoryMapper.updateById(bit);
        }
    }

    @Override
    public List<LiftCategoryEntity> queryToTree(Long brandId) {
        List<LiftCategoryEntity> list = liftCategoryMapper.selectByBrandId(brandId);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        //获取一级分类
        List<LiftCategoryEntity> level1Caregorys = list.stream().filter(liftCategoryEntity -> {
            if (liftCategoryEntity.getPid() != 0) {
                return false;
            }
            return true;
        }).collect(Collectors.toList());

        //添加二级分类到一级分类中
        level1Caregorys.forEach(level1Caregory -> {
            if (level1Caregory.getChilList() == null){
                level1Caregory.setChilList(new ArrayList<>());
            }

            list.forEach(liftCategoryEntity1 -> {
                if (level1Caregory.getId().equals(liftCategoryEntity1.getPid())){
                    level1Caregory.getChilList().add(liftCategoryEntity1);
                }
            });
        });
//        return getByTargetList(null, list);
        return level1Caregorys;

    }


    @Override
    public int execuSql(String sql) {
        return liftCategoryMapper.execuSql(sql);
    }

    private List<LiftCategoryEntity> dealTreeResult(List<LiftCategoryEntity> list) {
        Long zero = 0l;
        if (!CollectionUtils.isEmpty(list)) {
            // 查询所有分类信息，转成id->该对象对应的Map
            Map<Long, LiftCategoryEntity> idToEntityMap =
                liftCategoryMapper.selectAll().stream().collect(Collectors.toMap(LiftCategoryEntity::getId, e -> e));

            // list中是符合条件的结果，但是还需要显示其父级信息，故再进行一次查询。
            Set<LiftCategoryEntity> targetSet = new HashSet<>();
            Long pid = null;
            // 遍历每一条记录，由它向上追溯到顶级。
            for (LiftCategoryEntity cur : list) {
                targetSet.add(cur);
                pid = cur.getPid();
                while (pid != zero) {
                    // 未到顶级，继续追溯。
                    targetSet.add(idToEntityMap.get(pid));
                    pid = idToEntityMap.get(pid).getPid();
                }
            }
            List<LiftCategoryEntity> targetList = targetSet.stream().collect(Collectors.toList());
            // 调用方法返回树形结构的结果。
            return getByTargetList(zero, targetList);
        }
        return null;
    }

    private List<LiftCategoryEntity> getByTargetList(Long parentId, List<LiftCategoryEntity> targetList) {
        if (null == parentId) {
            parentId = 0L;
        }
        if (CollectionUtils.isEmpty(targetList)) {
            targetList = liftCategoryMapper.selectAll();
        }
        Map<Long, List<LiftCategoryEntity>> parentIdToChilds =
            targetList.stream().collect(Collectors.groupingBy(LiftCategoryEntity::getPid));
        return createTree(parentId, parentIdToChilds);
    }

    private List<LiftCategoryEntity> createTree(Long pid, Map<Long, List<LiftCategoryEntity>> map) {
        return Optional.ofNullable(map.get(pid)).orElseGet(() -> new ArrayList<LiftCategoryEntity>()).stream()
            .sorted(Comparator.comparing(LiftCategoryEntity::getSort)).map(x -> {
                x.setChilList(createTree(x.getId(), map));
                return x;
            }).collect(Collectors.toList());
    }

}
