package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diagbot.entity.ProductService;
import com.diagbot.entity.ServiceInfo;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.ServiceTypeEnum;
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.beans.factory.annotation.Autowired;
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 {
    @Autowired
    private ProductServiceFacade productServiceFacade;

    /**
     * 新建服务端
     *
     * @param serviceSaveVO
     * @return
     */
    public ServiceInfo createService(ServiceSaveVO serviceSaveVO) {
        Long operatorId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        Long userId = null;
        if (null != serviceSaveVO.getUserId()){
            userId = serviceSaveVO.getUserId();
        } else {
            userId = operatorId;
        }
        QueryWrapper<ServiceInfo> qw = new QueryWrapper<>();
        qw.eq("name", serviceSaveVO.getName()).
                eq("user_id", userId).
                eq("is_deleted", IsDeleteEnum.N.getKey());
        ServiceInfo serviceInfo = this.getOne(qw);
        if (serviceInfo != null) {
            throw new CommonException(CommonErrorCode.IS_EXISTS,
                    "该用户已建立服务端【" + serviceSaveVO.getName() + "】，不允许重复建立");
        }
        serviceInfo = new ServiceInfo();
        serviceInfo.setName(serviceSaveVO.getName());
        serviceInfo.setDescription(serviceSaveVO.getDescription());
        serviceInfo.setType(serviceSaveVO.getType());
        serviceInfo.setUserId(userId);
        serviceInfo.setCreator(operatorId.toString());
        serviceInfo.setGmtCreate(new Date());
        this.save(serviceInfo);
        return serviceInfo;
    }

    /**
     * 修改服务端
     *
     * @param serviceInfo
     * @return
     */
    public Boolean updateService(ServiceInfo serviceInfo) {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        if (!userId.equals(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);
    }

    /**
     * 删除服务端
     * 删除之前判断是否有产品关联，如果有，不允许删除
     *
     * @param serviceId
     * @return
     */
    public Boolean delService(Long serviceId) {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        ServiceInfo serviceInfo = this.getById(serviceId);
        if (serviceInfo == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "服务端不存在");
        } else if (!userId.equals(serviceInfo.getUserId())) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "服务端【" + serviceInfo.getName() + "】关联用户与当前登录用户不匹配，不允许删除");
        }
        QueryWrapper<ProductService> qwps = new QueryWrapper<>();
        qwps.eq("is_deleted", IsDeleteEnum.N.getKey()).
                eq("service_id", serviceId);
        List<ProductService> psList = productServiceFacade.list(qwps);
        if (psList.size() > 0) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "无法删除该服务端，请先删除该服务端令牌");
        }
        serviceInfo.setIsDeleted(IsDeleteEnum.Y.getKey());
        this.updateById(serviceInfo);
        return true;
    }

    /**
     * 获取当前登录用户服务列表
     *
     * @return
     */
    public List<ServiceInfo> getServiceListByCurrentUser() {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        QueryWrapper<ServiceInfo> qw = new QueryWrapper<>();
        qw.eq("user_id", userId).
                eq("type", ServiceTypeEnum.User_Create.getKey()).
                eq("is_deleted", "N");
        List<ServiceInfo> list = this.list(qw);
        return list;
    }

    /**
     * 获取当前登录用户未关联服务列表
     * @param ids
     * @return
     */
    public List<ServiceInfo> getServiceListNoRelation(Long[] ids) {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        QueryWrapper<ServiceInfo> qw = new QueryWrapper<>();
        qw.eq("user_id", userId).
                eq("type", ServiceTypeEnum.User_Create.getKey()).
                eq("is_deleted", "N").
                notIn("id", ids);
        List<ServiceInfo> list = this.list(qw);
        return list;
    }

    /**
     * 获取当前登录用户服务分页列表
     *
     * @param page
     * @return
     */
    public IPage<ServiceInfo> getServiceListPageByCurrentUser(Page<ServiceInfo> page) {
        Long userId = Long.parseLong(UserUtils.getCurrentPrincipleID());
        ServiceInfo serviceInfoVO = new ServiceInfo();
        serviceInfoVO.setUserId(userId);
        serviceInfoVO.setType(ServiceTypeEnum.User_Create.getKey());
        QueryWrapper<ServiceInfo> qw = new QueryWrapper<>();
        qw.eq("is_deleted", IsDeleteEnum.N.getKey()).
                eq("type", ServiceTypeEnum.User_Create.getKey()).
                eq("user_id", userId).
                orderByDesc("gmt_create");
        IPage<ServiceInfo> pagelist = this.page(page, qw);
        return pagelist;
    }
}
