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.BiTunnel;
import com.bocloud.ims.interfaces.resource.f5.F5BiTunnelService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.f5.F5BiTunnelRepository;
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("f5BiTunnelService")
public class F5BiTunnelServiceImpl implements F5BiTunnelService {
    private static final Logger logger = LoggerFactory.getLogger(F5BiTunnelServiceImpl.class);
    @Autowired
    private F5BiTunnelRepository f5BiTunnelRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;

    @Override
    public BocloudResult<GridBean<BiTunnel>> 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 = f5BiTunnelRepository.count(params);
            if (simple) {
                List<SimpleBean> beans = this.f5BiTunnelRepository.list(params, sorter);
                gridBean = new GridBean(1, 1, total, beans);
            } else {
                List<BiTunnel> listBiTunnels = this.f5BiTunnelRepository.list(page, rows, params, sorter);
                gridBean = GridHelper.getBean(page, rows, total, listBiTunnels);
            }
            return new BocloudResult(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("Query BiTunnel list fail:", e);
            return new BocloudResult(false, "查询失败");
        }
    }

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

    @Override
    public BocloudResult modify(BiTunnel biTunnel, Long userId) {
        String path = Kvs.class.getSimpleName() + "_" + biTunnel.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Long vendorId = biTunnel.getVendorId();
            CloudVendor cloudVendor = cloudVendorRepository.query(vendorId);
            if (null == cloudVendor) {
                return new BocloudResult(false, "云平台不存在");
            }
            BiTunnel query = f5BiTunnelRepository.query(biTunnel.getId());
            if (null == query) {
                logger.warn("data does not exist!");
                return new BocloudResult(false, "数据不存在");
            }
            biTunnel.setMenderId(userId);
            biTunnel.setGmtModify(new Date());
            logger.info("update biTunnel start...");
            this.f5BiTunnelRepository.update(biTunnel);
            return new BocloudResult(true, biTunnel, "修改成功");
        } catch (Exception e) {
            logger.error("create biTunnel 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), "请求超时");
            BiTunnel biTunnel = f5BiTunnelRepository.query(id);
            if (null == biTunnel) {
                return new BocloudResult(false, "请求内容不存在");
            }
            CloudVendor cloudVendor = cloudVendorRepository.query(biTunnel.getVendorId());
            if (null == cloudVendor) {
                logger.error("get cloudVendor failure!");
                return new BocloudResult(false, "删除失败!");
            }
            logger.info("remove biTunnel start...");
            boolean remove = this.f5BiTunnelRepository.remove(id, userId);
            if (remove) {
                return new BocloudResult(true, "删除成功");
            } else {
                return new BocloudResult(false, "删除失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BocloudResult(false, "删除失败");
        }
    }

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

}
