package com.yami.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.Dept;
import com.yami.shop.dao.DeptMapper;
import com.yami.shop.service.DeptService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 部门Service实现类
 *
 * @author
 */
@Service
@AllArgsConstructor
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    private final DeptMapper deptMapper;

    @Override
    public List<Dept> listAllDept() {
        // 获取所有未删除的部门数据
        List<Dept> allDepts = deptMapper.selectListAll();
        // 构建树形结构
        return buildDeptTree(allDepts, 0L);
    }

    /**
     * 构建部门树形结构
     * @param depts 所有部门列表
     * @param parentId 父级ID
     * @return 树形结构的部门列表
     */
    private List<Dept> buildDeptTree(List<Dept> depts, Long parentId) {
        return depts.stream()
                .filter(dept -> dept.getParentId().equals(parentId))
                .peek(dept -> {
                    List<Dept> children = buildDeptTree(depts, dept.getDeptId());
                    dept.setChildren(children);
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<Dept> listByParentId(Long parentId) {
        return deptMapper.selectByParentId(parentId);
    }

    @Override
    public List<Dept> treeDept() {
        return deptMapper.selectDeptTree();
    }

    @Override
    public boolean saveDept(Dept dept) {
        dept.setCreateTime(new Date());
        dept.setUpdateTime(new Date());
        dept.setIsDelete(0); // 默认未删除
        return save(dept);
    }

    @Override
    public boolean updateDept(Dept dept) {
        dept.setUpdateTime(new Date());
        return updateById(dept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDept(Long deptId) {
        // 软删除：更新 is_delete 字段为 1
        Dept dept = new Dept();
        dept.setDeptId(deptId);
        dept.setIsDelete(1);
        dept.setUpdateTime(new Date());
        return updateById(dept);
    }

    @Override
    public List<Dept> listDeptsByUserId(Long userId) {
        return deptMapper.selectDeptsByUserId(userId);
    }


}
