package com.jeeplus.pubmodules.knowledge.service;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.pubmodules.knowledge.domain.KnowledgeShareType;
import com.jeeplus.pubmodules.knowledge.mapper.KnowledgeShareTypeMapper;
import com.jeeplus.pubmodules.knowledge.service.dto.KnowledgeShareTypeDto;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class KnowledgeTypeService {

    @Resource
    private KnowledgeShareTypeMapper mapper;

    public IPage<KnowledgeShareTypeDto> list(Page<KnowledgeShareTypeDto> page, KnowledgeShareType type) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        QueryWrapper<KnowledgeShareTypeDto> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.company_id",userDTO.getCompanyDTO().getId());
        return mapper.findList(page,queryWrapper, type.getKlgsType());
    }

    public Boolean save(KnowledgeShareType type) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        List<KnowledgeShareType> list = mapper.checkList(type,userDTO.getCompanyDTO().getId());
        if (CollectionUtils.isNotEmpty(list)) {
            return false;
        }
        if (StringUtils.isNotEmpty(type.getId())) {
            return update(type);
        } else {
            return add(type);
        }
    }

    public Boolean update(KnowledgeShareType type) {
        // 获取当前登录人
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        type.setUpdateById(userDTO.getId());
        type.setUpdateTime(new Date());
        mapper.updateById(type);
        return true;
    }

    public Boolean add(KnowledgeShareType type) {
        // 获取当前登录人
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        type.setId(id);
        type.setCreateById(userDTO.getId());
        type.setCreateTime(new Date());
        type.setUpdateById(userDTO.getId());
        type.setUpdateTime(new Date());
        type.setDelFlag(0);
        type.setOfficeId(userDTO.getOfficeDTO().getId());
        type.setCompanyId(userDTO.getCompanyDTO().getId());
        mapper.insert(type);
        return true;
    }

}
