package com.sptg.permissions.biz.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.constant.SymbolConstant;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.permissions.api.dto.OrgDto;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.biz.mapper.OrganizationMapper;
import com.sptg.permissions.biz.service.OrgServiceInterface;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * title: OrgServiceImpl
 * package: com.sptg.permissions.biz.security.impl
 * description:
 *
 *                  
 *                 
 */
@Service
@RequiredArgsConstructor
public class OrgServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements OrgServiceInterface {

    private final RedisTemplate<String,String> redisTemplate;

    /**
     * 机构缓存名称
     */
    private final static String ORG_CACHE_NAME = "sptg:permissions:organization";

    /* ------------------------------------- 重写父类查询方法，过滤已删除的数据 ------------------------------------- */
    /* -------------------------------------------------------------------------------------------------------------- */

    @Override
    public Organization selectOne(Wrapper<Organization> wrapper) {
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return super.selectOne(wrapper);
    }

    @Override
    public List<Organization> selectList(Wrapper<Organization> wrapper) {
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return super.selectList(wrapper);
    }

    @Override
    public Page<Organization> selectPage(Page<Organization> page, Wrapper<Organization> wrapper) {
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return super.selectPage(page, wrapper);
    }

    /* -------------------------------------- 重写父类修改方法，删除Redis缓存 --------------------------------------- */
    /* -------------------------------------------------------------------------------------------------------------- */

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean updateById(Organization entity) {
        boolean result = super.updateById(entity);
        if (result){
            this.redisTemplate.opsForHash().delete(ORG_CACHE_NAME, entity.getId().toString());
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean updateBatchById(List<Organization> entityList) {
        boolean result = super.updateBatchById(entityList);
        if (result){
            HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
            entityList.forEach(item -> hashOperations.delete(ORG_CACHE_NAME, item.getId().toString()));
        }
        return result;
    }

    /* -------------------------------------------------- 业务代码 -------------------------------------------------- */
    /* -------------------------------------------------------------------------------------------------------------- */

    @Override
    public Organization selectById(Serializable id) {
        if (null == id){
            return null;
        }
        //  查询缓存
        HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
        String hashKey = id.toString();
        String json = hashOperations.get(ORG_CACHE_NAME, hashKey);
        if (StringUtils.isEmpty(json)){
            //  查询数据库
            Wrapper<Organization> wrapper = new EntityWrapper<>();
            wrapper.eq("l_id",id);
            Organization organization = this.selectOne(wrapper);
            if (null != organization){
                //  保存到缓存中
                json = JsonUtils.objectToJson(organization);
                hashOperations.put(ORG_CACHE_NAME,hashKey,json);
            }
            return organization;
        }
        return JsonUtils.jsonToPojo(json,Organization.class);
    }

    @Override
    public List<Organization> selectByPosition(String position) {
        Wrapper<Organization> wrapper = new EntityWrapper<>();
        wrapper.like("s_position",position, SqlLike.RIGHT);
        return this.selectList(wrapper);
    }

    @Override
    public List<Organization> selectByPid(Long pid) {
        Wrapper<Organization> wrapper = new EntityWrapper<>();
        wrapper.eq("l_pid",pid);
        return this.selectList(wrapper);
    }

    @Override
    public boolean insert(Organization entity) {
        //  创建人,创建时间
        entity.setCreateDate(new Date());
        //  初始化子节点数量，子部门数量，单元数量
        entity.setClientCount(OperationConstant.ZERO);
        entity.setDeptCount(OperationConstant.ZERO);
        //  删除标记：正常
        entity.setStatus(OperationConstant.ZERO);
        return super.insert(entity);
    }

    @Override
    public List<Organization> selecSubList(OrgDto dto) {
        Wrapper<Organization> wrapper = new EntityWrapper<>();
        String position = dto.getPosition();
        if (dto.getExcludeOwn() == OperationConstant.ONE){
            position += SymbolConstant.UNDERLINE + SymbolConstant.PER_CENT;
            wrapper.like("s_position",position, SqlLike.CUSTOM);
        }else {
            wrapper.like("s_position", position, SqlLike.RIGHT);
        }
        if (dto.getIsQueryDept() != OperationConstant.ONE){
            wrapper.notIn("i_flag",OperationConstant.THREE);
        }
        return this.selectList(wrapper);
    }

    @Override
    public int selectCount(OrgDto dto){
        Wrapper<Organization> wrapper = new EntityWrapper<>();
        //机构类型
        if(dto.getOrgType()!=null){
            wrapper.eq("i_org_type",dto.getOrgType());
        }
        //标识：{ 1：机构，2：小区，3：部门 }
        if(dto.getFlag()!=null){
            wrapper.eq("i_flag",dto.getFlag());
        }
        wrapper.like("s_position",  dto.getPosition(), SqlLike.RIGHT);
        //  删除标记：正常
        wrapper.eq("i_status",OperationConstant.ZERO);
        return this.selectCount(wrapper);
    }

    @Override
    public boolean checkNameIsExist(String name) {
        Wrapper<Organization> wrapper = new EntityWrapper<>();
        wrapper.eq("s_name",name);
        return this.selectCount(wrapper) > 0;
    }

    @Override
    public Page<Organization> showOrgList(PageBean<Organization,OrgDto> pageBean) {
        pageBean.setRecords(this.baseMapper.showOrgList(pageBean.getDto(),pageBean));
        return pageBean;
    }
}