package com.diagbot.facade;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diagbot.entity.ServiceInfo;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.ServiceInfoServiceImpl;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.ServiceSaveVO;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Description: 用户服务业务层
 * @author: zhaops
 * @time: 2018/9/18 16:31
 */
@Component
public class ServiceInfoFacade extends ServiceInfoServiceImpl {
    /**
     * @Description: 新建服务端
     * @author: zhaops
     * @time: 2018/9/18 16:31
     */
    public ServiceInfo createService(ServiceSaveVO serviceSaveVO) {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        ServiceInfo serviceInfo = new ServiceInfo();
        serviceInfo.setName(serviceSaveVO.getName());
        serviceInfo.setDescription(serviceSaveVO.getDescription());
        serviceInfo.setType(serviceSaveVO.getType());
        serviceInfo.setUserId(userId);
        serviceInfo.setCreator(userId.toString());
        serviceInfo.setGmtCreate(new Date());
        this.save(serviceInfo);
        return serviceInfo;
    }

    /**
     * @Description: 修改服务端
     * @author: zhaops
     * @time: 2018/9/18 16:31
     */
    public Boolean updateService(ServiceInfo serviceInfo) {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        if (userId != serviceInfo.getUserId()) {
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL,
                    "服务端【" + serviceInfo.getName() + "】关联用户与当前登录用户不匹配");
        }
        serviceInfo.setUserId(userId);
        serviceInfo.setModifier(userId.toString());
        serviceInfo.setGmtModified(new Date());
        return this.updateById(serviceInfo);
    }

    /**
     * @Description: 获取当前登录用户服务列表
     * @author: zhaops
     * @time: 2018/9/18 16:31
     */
    public List<ServiceInfo> getServiceListByCurrentUser() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        List<ServiceInfo> list = this.getListByUserId(userId);
        return list;
    }

    /**
     * @Description: 获取当前登录用户服务分页列表
     * @author: zhaops
     * @time: 2018/9/19 14:05
     */
    public IPage<ServiceInfo> getServiceListPageByCurrentUser(Page<ServiceInfo> page) {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        ServiceInfo serviceInfoVO = new ServiceInfo();
        serviceInfoVO.setUserId(userId);
        IPage<ServiceInfo> pagelist = this.selectServiceListPage(page, serviceInfoVO);
        return pagelist;
    }
}
