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.BiSnatPool;
import com.bocloud.ims.interfaces.resource.f5.F5BiSnatPoolService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.f5.F5BiSnatPoolRepository;
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("f5BiSnatPoolService")
public class F5BiSnatPoolServiceImpl implements F5BiSnatPoolService {

    private static final Logger logger = LoggerFactory.getLogger(F5BiSnatPoolServiceImpl.class);
    @Autowired
    private F5BiSnatPoolRepository f5BiSnatPoolRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;

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

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

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

}
