package com.bocloud.ims.service.topology;

import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.entity.topology.RelationCategory;
import com.bocloud.ims.interfaces.topology.RelationCategoryService;
import com.bocloud.ims.repository.topology.ModuleRelationRepository;
import com.bocloud.ims.repository.topology.RelationCategoryRepository;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 关系类型service层实现类
 *
 * @author lyy
 * @Version 1.0
 * @since 2017年9月18日
 */
@Service("relationCategoryService")
public class RelationCategoryServiceImpl implements RelationCategoryService {
    private static final Logger logger = LoggerFactory.getLogger(RelationCategoryServiceImpl.class);
    @Autowired
    private RelationCategoryRepository relationCategoryRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private ModuleRelationRepository moduleRelationRepository;

    @Override
    public BocloudResult list() {
        try {
            List<RelationCategory> relationCategorieList = relationCategoryRepository.list();
            if (ListTool.isEmpty(relationCategorieList)) {
                return new BocloudResult(true, relationCategorieList, "查询成功，数据为空");
            }
            // 5.6不需要平台拓扑，初始化数据暂时保留，通过代码层面控制
            relationCategorieList.removeIf(felationCategory -> "平台拓扑".equalsIgnoreCase(felationCategory.getName()));
            return new BocloudResult(true, relationCategorieList, "查询成功");
        } catch (Exception e) {
            logger.error("Query Relation Categorie list error:", e);
            return new BocloudResult(false, "查询失败");
        }
    }

    @Override
    public BocloudResult create(RelationCategory relationCategory) {
        try {
            relationCategory.setGmtCreate(new Date());
            relationCategory.setReserved(false);
            this.relationCategoryRepository.save(relationCategory);
/*            if (null == relationCategory) {
                logger.warn("Create notice relationCategory fail!");
                return new BocloudResult(false, "应用失败");
            }*/
        } catch (Exception e) {
            logger.error("Create Relation Category error:", e);
            return new BocloudResult(false, "添加失败");
        }
        return new BocloudResult(true, relationCategory, "添加成功");
    }

    @Override
    public BocloudResult modify(RelationCategory relationCategory, RequestContext requestContext) {
        String path = RelationCategory.class.getSimpleName() + "_" + relationCategory.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            RelationCategory object = this.relationCategoryRepository.query(relationCategory.getId());
            if (null == object) {
                logger.warn("relationCategory does not exist!");
                return new BocloudResult(false, "数据不存在");
            }
            BeanUtils.copyProperties(relationCategory, object);
            object.setGmtModify(new Date());
            object.setMenderId(requestContext.getTarget());
            this.relationCategoryRepository.update(object);
            return new BocloudResult(true, "修改成功");
        } catch (Exception e) {
            logger.error("Modify Relation Category fail:", e);
            return new BocloudResult(false, "修改失败");
        }
    }

    @Override
    public BocloudResult remove(Long id) {
        String path = RelationCategory.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            RelationCategory relationCategory = relationCategoryRepository.query(id);
            if (relationCategory == null) {
                return new BocloudResult(false, "此维度不存在");
            } else if (relationCategory.getReserved().equals(true)) {
                return new BocloudResult(false, "系统内置维度不允许删除");
            }
            int count = moduleRelationRepository.countUsedCategory(id);
            if (count > 0) {
                return new BocloudResult(false, "此维度已被使用,不可删除！");
            } else {
                this.relationCategoryRepository.remove(id);
                return new BocloudResult(true, "删除成功");
            }
        } catch (Exception e) {
            logger.error("Remove Relation Category fail:", e);
            return new BocloudResult(false, "删除失败");
        }
    }

}
