/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package cn.ysk.cashier.system.service.impl;

import cn.ysk.cashier.pojo.order.TbOrderInfo;
import cn.ysk.cashier.system.domain.Dict;
import cn.ysk.cashier.system.repository.DictDetailRepository;
import cn.ysk.cashier.system.repository.DictRepository;
import cn.ysk.cashier.system.service.DictService;
import cn.ysk.cashier.system.service.dto.DictDto;
import cn.ysk.cashier.system.service.dto.DictQueryCriteria;
import cn.ysk.cashier.system.service.mapstruct.DictMapper;
import cn.ysk.cashier.utils.CacheKey;
import cn.ysk.cashier.utils.PageUtil;
import cn.ysk.cashier.utils.QueryHelp;
import cn.ysk.cashier.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Zheng Jie
 * @date 2019-04-10
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
public class DictServiceImpl implements DictService {

    private final DictRepository dictRepository;
    private final DictMapper dictMapper;
    private final DictDetailRepository dictDetailRepository;
    private final RedisUtils redisUtils;

    @Override
    public Map<String, Object> queryAll(DictQueryCriteria criteria, Pageable pageable) {

        Page<Dict> page = dictRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = QueryHelp.getPredicate(root, criteria, criteriaBuilder);
            // 追加校验参数 status不为空 且 source不为空 不查询状态为 "refund" 的
            predicate = criteriaBuilder.and(predicate, criteriaBuilder.isNull(root.get("releId")));
            return predicate;
        }, pageable);
        Page<DictDto> pageDto = page.map(dictMapper::toDto);
        for (DictDto dictDto : pageDto.getContent()) {
            if (dictDto.getIsChild() != null && dictDto.getIsChild() == 1) {
                dictDto.setDictDetails(dictRepository.findByReleId(dictDto.getId()));
            }
        }
        return PageUtil.toPage(pageDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Dict resources) {
        resources.setIsChild(0);
        if (resources.getReleId() != null) {
            dictRepository.updateByReleId(resources.getReleId(), 1);
        }
        dictRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Dict resources) {
        // 清理缓存
        delCaches(resources);
        dictRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Integer> ids) {
        List<Dict> dicts = dictRepository.findByIdIn(ids);
        dictRepository.deleteByIdIn(ids);
        for (Dict dict : dicts) {
            if (dict.getIsChild() == 1) {
                dictRepository.deleteByReleId(dict.getId());
            } else {
                int x = dictRepository.countDictByReleId(dict.getReleId());
                if (x != 0) {
                    dictRepository.updateByReleId(dict.getReleId(), 0);
                }
            }
            delCaches(dict);
        }

    }

    public void delCaches(Dict dict) {
        redisUtils.del(CacheKey.DICT_NAME + dict.getName());
    }
}