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.BiDnsResolvers;
import com.bocloud.ims.interfaces.resource.f5.F5BiDnsResolversService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.f5.F5BiDnsResolversRepository;
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("f5BiDnsResolversService")
public class F5BiDnsResolversServiceImpl implements F5BiDnsResolversService {

    private static final Logger logger = LoggerFactory.getLogger(F5BiDnsResolversServiceImpl.class);
    @Autowired
    private F5BiDnsResolversRepository f5BiDnsResolversRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;

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

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

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

}
