package com.bocloud.ims.service.resource.f5;

import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.ims.entity.middleware.Kvs;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.f5.BiVlans;
import com.bocloud.ims.interfaces.resource.f5.F5BiVlansService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.f5.F5BiVlanRepository;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Map;
import java.util.concurrent.TimeUnit;

@Service("f5BiVlansService")
public class F5BiVlansServiceImpl implements F5BiVlansService {

    private static final Logger logger = LoggerFactory.getLogger(F5BiVlansServiceImpl.class);
    @Autowired
    private F5BiVlanRepository f5BiVlanRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;

    @Override
    public BocloudResult<GridBean<BiVlans>> list(Pager pager) {
        GridBean gridBean = null;
        try {
            int page = pager.getPage();
            int rows = pager.getRows();
            List<Param> params = pager.getParams();
            Map<String, String> sorter = pager.getSorter();
            boolean simple = pager.getSimple();


            if (null == params) {
                params = Lists.newArrayList();
            }
            if (null == sorter) {
                sorter = Maps.newHashMap();
            }
            sorter.put("gmtCreate", Common.ONE);
            int total = f5BiVlanRepository.count(params);
            if (simple) {
                List<SimpleBean> beans = this.f5BiVlanRepository.list(params, sorter);
                gridBean = new GridBean(1, 1, total, beans);
            } else {
                List<BiVlans> listBiVlans = this.f5BiVlanRepository.list(page, rows, params, sorter);
                gridBean = GridHelper.getBean(page, rows, total, listBiVlans);
            }
            return new BocloudResult(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("Query BiVlans list fail:", e);
            return new BocloudResult(false, "查询失败");
        }
    }

    @Override
    public BocloudResult create(BiVlans biVlans, Long userId) {
        String path = Kvs.class.getSimpleName() + "_" + biVlans.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Long vendorId = biVlans.getVendorId();
            boolean isExist = f5BiVlanRepository.existName(biVlans.getName(), vendorId, biVlans.getPartitionId());
            if (isExist) {
                return new BocloudResult(false, "添加失败：该名称已存在");
            }
            CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
            if (null == cloudVendor) {
                logger.error("get cloudVendor failure!");
                return new BocloudResult(false, "云平台不存在!");
            }
            biVlans.setCreatorId(userId);
            biVlans.setMenderId(userId);
            biVlans.setGmtCreate(new Date());
            logger.info("create biVlans start...");
            this.f5BiVlanRepository.save(biVlans);
            return new BocloudResult(true, "添加成功");
        } catch (Exception e) {
            logger.error("create biVlans error", e);
            return new BocloudResult(false, e.getMessage());
        }
    }

    @Override
    public BocloudResult modify(BiVlans biVlans, Long userId) {
        String path = Kvs.class.getSimpleName() + "_" + biVlans.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Long vendorId = biVlans.getVendorId();
            CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
            if (null == cloudVendor) {
                logger.error("get cloudVendor failure");
                return new BocloudResult(false, "云平台不存在，修改失败");
            }
            BiVlans query = f5BiVlanRepository.query(biVlans.getId());
            if (null == query) {
                logger.warn("data does not exist!");
                return new BocloudResult(false, "数据不存在");
            }
            biVlans.setMenderId(userId);
            biVlans.setGmtModify(new Date());
            logger.info("update biVlans start...");
            this.f5BiVlanRepository.update(biVlans);
            return new BocloudResult(true, "修改成功");
        } catch (Exception e) {
            logger.error("create biVlans error", e);
            return new BocloudResult(false, e.getMessage());
        }
    }

    @Override
    public BocloudResult remove(Long id, Long userId) {
        String path = Kvs.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            BiVlans biVlans = f5BiVlanRepository.query(id);
            if (null == biVlans) {
                return new BocloudResult(false, "请求内容不存在");
            }
            CloudVendor vendor = cloudVendorRepository.query(biVlans.getVendorId());
            if (null == vendor) {
                logger.error("get cloudVendor failure!");
                return new BocloudResult(false, "删除失败!");
            }
            logger.info("remove biVlans start...");
            boolean result = this.f5BiVlanRepository.remove(id, userId);
            if (result) {
                return new BocloudResult(true, "删除成功");
            } else {
                return new BocloudResult(false, "删除失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BocloudResult(false, "删除失败");
        }
    }

    @Override
    public BocloudResult<BiVlans> detail(Long id) {
        try {
            BiVlans biVlans = this.f5BiVlanRepository.query(id);
            if (null == biVlans) {
                return new BocloudResult(false, "数据不存在");
            }
            return new BocloudResult(true, biVlans, "查询数据成功");
        } catch (Exception e) {
            logger.error("Get biVlans error：", e);
            return new BocloudResult(false, "查询详情失败");
        }
    }

}
