package com.fzm.mall.server.admin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.system.entity.dto.SysNavigationDTO;
import com.fzm.mall.server.admin.system.entity.dto.SysNavigationSaveDTO;
import com.fzm.mall.server.admin.system.entity.dto.SysNavigationUpdateDTO;
import com.fzm.mall.server.admin.system.mapper.SysNavigationMapper;
import com.fzm.mall.server.admin.system.model.SysNavigation;
import com.fzm.mall.server.admin.system.service.ISysNavigationService;
import com.fzm.mall.server.admin.util.CopyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 系统中心-常见问题-导航 服务实现类
 * </p>
 *
 * @author fzm
 * @since 2021-03-29
 */
@Service
@Transactional
public class SysNavigationServiceImpl extends ServiceImpl<SysNavigationMapper, SysNavigation> implements ISysNavigationService {

    @Resource
    private SysNavigationMapper navigationMapper;

    @Override
    public void save(SysNavigationSaveDTO navigationSaveDTO) {
        SysNavigation navigation = CopyUtil.to(navigationSaveDTO, SysNavigation.class);
        navigation.init();

        navigationMapper.insert(navigation);
    }

    @Override
    public void update(SysNavigationUpdateDTO navigationUpdateDTO) {
        SysNavigation navigation = CopyUtil.to(navigationUpdateDTO, SysNavigation.class);
        UpdateWrapper<SysNavigation> wrapper = new UpdateWrapper<>();
        wrapper.eq("navigation_id", navigation.getNavigationId())
                .eq("update_time", navigation.getUpdateTime());
        int update = navigationMapper.update(navigation, wrapper);
        if (update == 0) {
            throw new MyException(MallResponseError.UPDATE_FAIL);
        }
    }

    @Override
    public void delete(String navigationId) {
        UpdateWrapper<SysNavigation> wrapper = new UpdateWrapper<>();
        wrapper.eq("navigation_id", navigationId)
                .set("status", true);
        navigationMapper.update(null, wrapper);
    }

    @Override
    public SysNavigationDTO read(String navigationId) {
        SysNavigation navigation = navigationMapper.selectOne(new QueryWrapper<SysNavigation>().eq("navigation_id", navigationId));
        return CopyUtil.to(navigation, SysNavigationDTO.class);
    }

    @Override
    public List<SysNavigationDTO> listAll() {
        List<SysNavigation> result = navigationMapper.selectList(new QueryWrapper<SysNavigation>().eq("status", false).orderByAsc("display_order"));
        return CopyUtil.toList(result, SysNavigationDTO.class);
    }
}
