package com.usoftchina.bi.server.service.dashboard;

import com.usoftchina.bi.core.base.RepCode;
import com.usoftchina.bi.core.base.RepEntity;
import com.usoftchina.bi.core.exception.MyException;
import com.usoftchina.bi.core.utils.GetTokenDataUtil;
import com.usoftchina.bi.server.dao.dashboard.DashBoardMenuMapper;
import com.usoftchina.bi.server.model.vo.configVo.DashBoardMenuInfo;
import com.usoftchina.bi.server.model.vo.configVo.DashBoardUpdateMenuInfo;
import com.usoftchina.bi.server.model.vo.dataVo.DashboardMenuRespDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author chenwei
 * @Date 2019-04-19
 */
@Service
public class DashBoardMenuService {

    @Autowired
    private DashBoardMenuMapper dashBoardMenuMapper;

    public List<DashboardMenuRespDTO> list(String token){
        int userId = Integer.parseInt(GetTokenDataUtil.getTokenData(token).get("id"));
        return getData(userId, 0);
    }

    private List<DashboardMenuRespDTO> getData(int userId, int id){
        List<DashboardMenuRespDTO> dashboardMenuRespDTOList = dashBoardMenuMapper.getMenuById(userId, id);
        if (!CollectionUtils.isEmpty(dashboardMenuRespDTOList)) {
            for (DashboardMenuRespDTO dashboardMenuRespDTO : dashboardMenuRespDTOList) {
                if ("menu".equals(dashboardMenuRespDTO.getType())) {
                    dashboardMenuRespDTO.setChildren(getData(userId, dashboardMenuRespDTO.getId()));
                }
            }
        }
        return dashboardMenuRespDTOList;
    }

    public void save(DashBoardMenuInfo dashBoardMenuInfo){
        dashBoardMenuMapper.insert(dashBoardMenuInfo);
    }

    public void update(DashBoardMenuInfo dashBoardMenuInfo){
        dashBoardMenuMapper.updateSelectiveByPrimaryKey(dashBoardMenuInfo);
    }

    public void deleteById(Long id){
        Assert.state(id > 0, "参数错误");
        // 判断是否存在报表,存在不允许删除目录
        int count = dashBoardMenuMapper.countDashboardByMenuId(id);
        if (count > 0) {
            throw new MyException(RepCode.MENU_USED_DASHBOARD);
        }
        dashBoardMenuMapper.deleteByPrimaryKey(id);
    }

    public void updateDashBoardMenu(DashBoardUpdateMenuInfo dashBoardUpdateMenuInfo){
        dashBoardMenuMapper.updateDashBoardMenu(dashBoardUpdateMenuInfo);
    }

    public RepEntity getDashBoardByMenuId(String token, int menuId){
        int userId = Integer.parseInt(GetTokenDataUtil.getTokenData(token).get("id"));
        return new RepEntity(RepCode.success, dashBoardMenuMapper.getDashBoardByMenuId(userId, menuId));
    }

}
