package yangtz.cs.liu.campus.service.impl.schoolEquipment;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yangtz.cs.liu.campus.domain.schoolEquipment.SchoolProductCategory;
import yangtz.cs.liu.campus.mapper.schoolEquipment.ProductCategoryMapper;
import yangtz.cs.liu.campus.service.schoolEquipment.IProductCategoryService;
import yangtz.cs.liu.campus.vo.schoolEquipment.SchoolProductCategoryVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, SchoolProductCategory> implements IProductCategoryService {

    @Autowired
    private ProductCategoryMapper productCategoryMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查看产品分类列表
     * @param schoolProductCategory
     * @return
     */
    @Override
    public List<SchoolProductCategory> selectSchoolProductCateGory(SchoolProductCategory schoolProductCategory) {
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        for (SysRole role : roles) {
            if (role.getRoleKey().equals("admin")){
                return productCategoryMapper.selectSchoolProductCateGory(schoolProductCategory);
            }else if (role.getRoleKey().equals("productCategoryAdmin")){
                schoolProductCategory.setAdminId(SecurityUtils.getLoginUser().getUser().getUserId());
                return productCategoryMapper.selectSchoolProductCateGoryGr(schoolProductCategory);
            }
        }
        if (user.isAdmin()){
            return productCategoryMapper.selectSchoolProductCateGory(schoolProductCategory);
        }
        return new ArrayList<>();
    }

    /**
     * 查看产品分类详细信息
     * @param id
     * @return
     */
    @Override
    public SchoolProductCategoryVo selectSchoolProductCateGoryById(Long id) {
        return productCategoryMapper.selectSchoolProductCateGoryById(id);
    }

    /**
     * 新增产品分类
     * @param schoolProductCategory
     * @return
     */
    @Override
    @Transactional
    public int insertSchoolProductCategory(SchoolProductCategory schoolProductCategory) {
        //查询分类编码是否重复
        LambdaQueryWrapper<SchoolProductCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SchoolProductCategory::getClassificationCode,schoolProductCategory.getClassificationCode());
        List<SchoolProductCategory> schoolProductCategories = productCategoryMapper.selectList(wrapper);
        if (schoolProductCategories != null && schoolProductCategories.size() > 0){
            throw new ServiceException("该分类编码已存在");
        }
        //父id
        if (StringUtils.isNotNull(schoolProductCategory.getParentId())){
            SchoolProductCategory schoolProductCategory1 = productCategoryMapper.selectById(schoolProductCategory.getParentId());
            schoolProductCategory.setAncestors(schoolProductCategory1.getAncestors() + "," + schoolProductCategory.getParentId());
        }else {
            schoolProductCategory.setParentId((long) 0);
            schoolProductCategory.setAncestors("0");
        }
        String[] split = schoolProductCategory.getAncestors().split(",");
        schoolProductCategory.setRank((long) split.length);
        switch (split.length){
            case 1:
                if (schoolProductCategory.getClassificationCode().length() < 2) {
                    throw new ServiceException("一级分类编码最小长度为2");
                }
                break;
            case 2:
                if (schoolProductCategory.getClassificationCode().length() < 4) {
                    throw new ServiceException("二级分类编码最小长度为4");
                }
                break;
            case 3:
                if (schoolProductCategory.getClassificationCode().length() < 6) {
                    throw new ServiceException("三级分类编码最小长度为6");
                }
                break;
            case 4:
                if (schoolProductCategory.getClassificationCode().length() < 8) {
                    throw new ServiceException("四级分类编码最小长度为8");
                }
                break;
            case 5:
                if (schoolProductCategory.getClassificationCode().length() < 10) {
                    throw new ServiceException("五级分类编码最小长度为10");
                }
                break;
            case 6:
                if (schoolProductCategory.getClassificationCode().length() < 12) {
                    throw new ServiceException("六级分类编码最小长度为12");
                }
                break;
        }
        String userName = sysUserMapper.selectUserById(schoolProductCategory.getAdminId()).getUserName();
        schoolProductCategory.setAdmin(userName);
        schoolProductCategory.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        schoolProductCategory.setCreateTime(DateUtils.getNowDate());
        return productCategoryMapper.insert(schoolProductCategory);
    }

    /**
     * 修改产品分类信息
     * @param schoolProductCategory
     * @return
     */
    @Override
    @Transactional
    public int updateSchoolProductCategory(SchoolProductCategory schoolProductCategory) {

        //查询分类编码是否重复
        LambdaQueryWrapper<SchoolProductCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SchoolProductCategory::getClassificationCode,schoolProductCategory.getClassificationCode())
                .notIn(SchoolProductCategory::getId,schoolProductCategory.getId());
        List<SchoolProductCategory> schoolProductCategories = productCategoryMapper.selectList(wrapper);
        if (schoolProductCategories != null && schoolProductCategories.size() > 0){
            throw new ServiceException("该分类编码已存在");
        }
        String[] split = schoolProductCategory.getAncestors().split(",");
        schoolProductCategory.setRank((long) split.length);
        switch (split.length){
            case 1:
                if (schoolProductCategory.getClassificationCode().length() < 2) {
                    throw new ServiceException("一级分类编码最小长度为2");
                }
                break;
            case 2:
                if (schoolProductCategory.getClassificationCode().length() < 4) {
                    throw new ServiceException("二级分类编码最小长度为4");
                }
                break;
            case 3:
                if (schoolProductCategory.getClassificationCode().length() < 6) {
                    throw new ServiceException("三级分类编码最小长度为6");
                }
                break;
            case 4:
                if (schoolProductCategory.getClassificationCode().length() < 8) {
                    throw new ServiceException("四级分类编码最小长度为8");
                }
                break;
            case 5:
                if (schoolProductCategory.getClassificationCode().length() < 10) {
                    throw new ServiceException("五级分类编码最小长度为10");
                }
                break;
            case 6:
                if (schoolProductCategory.getClassificationCode().length() < 12) {
                    throw new ServiceException("六级分类编码最小长度为12");
                }
                break;
        }
        //父id
        if (StringUtils.isNotNull(schoolProductCategory.getParentId())){
            SchoolProductCategory schoolProductCategory1 = productCategoryMapper.selectById(schoolProductCategory.getParentId());
            if (StringUtils.isNotNull(schoolProductCategory1)){
                schoolProductCategory.setAncestors(schoolProductCategory1.getAncestors() + "," + schoolProductCategory.getParentId());
            }
        }else {
            schoolProductCategory.setParentId((long) 0);
            schoolProductCategory.setAncestors("0");
        }
//        String[] split = schoolProductCategory.getAncestors().split(",");
//        schoolProductCategory.setRank((long) split.length);

        //根据用户id获取用户名
        String userName = sysUserMapper.selectUserById(schoolProductCategory.getAdminId()).getUserName();
        schoolProductCategory.setAdmin(userName);
        schoolProductCategory.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        schoolProductCategory.setUpdateTime(DateUtils.getNowDate());
        return productCategoryMapper.updateById(schoolProductCategory);
    }

    /**
     * 删除产品分类信息
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int deleteSchoolProductCategory(Long[] ids) {
        int i = 0;
        for (Long id : ids) {
            i += productCategoryMapper.deleteSchoolProductCategory(id);
        }
        return i;
    }

    /**
     * 获取设备分类下拉框
     * @param
     * @return
     */
    @Override
//    @DataScope(userAlias = "u")
    public List<Map<String, String>> getEquipmentType(SchoolProductCategory schoolProductCategory) {
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        for (SysRole role : roles) {
            if (role.getRoleKey().equals("admin")){
                return productCategoryMapper.getEquipmentType(schoolProductCategory);
            }else if (role.getRoleKey().equals("productCategoryAdmin")){
                schoolProductCategory.setAdminId(SecurityUtils.getLoginUser().getUser().getUserId());
                return productCategoryMapper.getEquipmentTypeGr(schoolProductCategory);
            }
        }
        if (user.isAdmin()){
            return productCategoryMapper.getEquipmentType(schoolProductCategory);
        }
        return new ArrayList<>();
    }

    /**
     * 获取管理员
     * @return
     */
    @Override
//    @DataScope(userAlias = "u")
    public List<Map<String, String>> getAdmin(SchoolProductCategory schoolProductCategory) {
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (user.isAdmin()){
            return productCategoryMapper.getAdmin(schoolProductCategory);
        }
        for (SysRole role : roles) {
            if (role.getRoleKey().equals("admin")){
                return productCategoryMapper.getAdmin(schoolProductCategory);
            }else if (role.getRoleKey().equals("productCategoryAdmin")){
                schoolProductCategory.setAdminId(SecurityUtils.getLoginUser().getUser().getUserId());
                return productCategoryMapper.getAdminGr(schoolProductCategory);
            }
        }
        return new ArrayList<>();
    }

    /**
     * 根据分类编码查询产品分类信息
     * @param code
     * @return
     */
    @Override
    public SchoolProductCategory getEquipmentByCode(String code) {
//        List<SchoolProductCategory> list = new ArrayList<>();
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (user.isAdmin()){
//            list.clear();
            LambdaQueryWrapper<SchoolProductCategory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SchoolProductCategory::getClassificationCode,code);
            return productCategoryMapper.selectOne(wrapper);
        }
        for (SysRole role : roles) {
            if (role.getRoleKey().equals("admin")){
//                list.clear();
                LambdaQueryWrapper<SchoolProductCategory> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SchoolProductCategory::getClassificationCode,code);
//                list.add(productCategoryMapper.selectOne(wrapper));
                return productCategoryMapper.selectOne(wrapper);
//                break;
            }else if (role.getRoleKey().equals("productCategoryAdmin")){
//                list.clear();
                LambdaQueryWrapper<SchoolProductCategory> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SchoolProductCategory::getClassificationCode,code)
                        .eq(SchoolProductCategory::getAdminId,SecurityUtils.getLoginUser().getUser().getUserId());
                return productCategoryMapper.selectOne(wrapper);
            }
        }
        throw new ServiceException("该设备不再您管辖范围内");
    }
}
